@picked/app-kit
@picked/app-kit is the TypeScript library for the server and the pages of a Picked app. It
implements the app protocol.
Install
npm install @picked/app-kitLoad the package with import or with require. In TypeScript, set moduleResolution to
node16, nodenext or bundler.
Entry points
| Import | Runs in | Contents |
|---|---|---|
@picked/app-kit | Server and browser | The manifest, the protocol types and constants, and the key functions. |
@picked/app-kit/server | Server | The request handler, the installation client, and the environment reader. |
@picked/app-kit/oauth | Server | The start and the callback of an OAuth authorization. |
@picked/app-kit/node | Node.js | serve and frameScript. |
@picked/app-kit/frame | Browser | The functions for a page in a dashboard slot. |
@picked/app-kit/testing | Tests | A Picked API for tests. |
@picked/app-kit/server also gives all the functions, constants and types of
@picked/app-kit, but not FrameContext, FrameToHostMessage and HostToFrameMessage.
The package also has the command app-kit-copy-frame. See
app-kit-copy-frame.
@picked/app-kit
Manifest
parseManifest(value: unknown): { ok: true; manifest: AppManifest } | { ok: false; issues: string[] }
isAppUrl(value: unknown): value is string| Export | Description |
|---|---|
parseManifest | Checks a manifest. It returns all the problems that it finds. |
isAppUrl | Returns true for an https URL, or an http URL on localhost, 127.0.0.1 or [::1]. |
| Constant | Value |
|---|---|
APP_SLOT_LOCATIONS | ['app-home', 'workspace-prepublish-actions', 'workspace-postpublish-actions'] |
APP_EVENTS | ['workspace.published'] |
APP_VALUE_TYPES | ['string', 'number', 'boolean', 'json'] |
The types are AppManifest, AppSlot, AppWorkflowTool, AppToolArgument,
AppToolOutputField, AppSlotLocation, AppEventName and AppValueType. See
App manifest for each field and each validation message. An app
declares its manifest in the app section of picked.config.ts, with defineConfig from
@picked/config/define. See
The app section of picked.config.
Protocol
| Constant | Value |
|---|---|
SIGNATURE_HEADER | 'picked-signature' |
INSTALLATION_HEADER | 'picked-installation-id' |
APP_ASSERTION_HEADER | 'picked-app-assertion' |
CONTEXT_HEADER | 'picked-context' |
PICKED_KEYS_PATH | '/.well-known/picked-app-keys.json' |
PICKED_CONFIG_PATH | '/.well-known/picked-app-config.json' |
PickedAppConfig is the type of the document at PICKED_CONFIG_PATH. See
App config of Picked.
verifyBody(keys: PublicKeySet, body: string, header: string | null): Promise<boolean>
verifyMcpRequest(keys: PublicKeySet, headers: Headers, body: string): Promise<InstallationRef | null>
verifySessionToken(keys: PublicKeySet, token: string): Promise<SessionClaims | null>
createAppAssertion(signer: Signer, options: { installationId: string; audience: string }): Promise<string>
signBody(signer: Signer, body: string, timestamp?: number): Promise<string>| Function | Description |
|---|---|
verifyBody | Returns true when a key of keys signed body, and the time in header is not more than 300 seconds from the current time. |
verifyMcpRequest | Verifies an MCP request from Picked. It returns the installation from picked-context, or null. |
verifySessionToken | Verifies a session token. It returns the fields of the token. It returns null for a token that is not correct or that is after its time of expiry. |
createAppAssertion | Makes a picked-app-assertion token for the installation. It expires after 60 seconds. audience is the origin of the Picked API. |
signBody | Makes a picked-signature value. timestamp is in unix seconds, and is the current time when you do not give it. |
The protocol types are InstallationRef, InstallationCreatedEvent,
InstallationUpgradedEvent, InstallationDeletedEvent, LifecycleEvent,
WorkspacePublishedEvent, AppEvent, ToolCall, ToolResult, SessionClaims and
AppAssertionClaims. See App protocol for their fields.
Keys
generateKeyPair(): Promise<{ privateKey: string; publicKey: string; kid: string }>
createSigner(privateKey: string): Promise<Signer>
remoteKeySet(options: { url: string; fetch?: typeof fetch; refreshAfterMs?: number }): PublicKeySet
staticKeySet(keys: readonly PublicKey[]): PublicKeySet
toJwks(keys: readonly PublicKey[]): Jwks
keyIdOf(publicKey: string): Promise<string>| Function | Description |
|---|---|
generateKeyPair | Makes an Ed25519 private key and its public key. The private key is the base64 of its PKCS#8 DER, on one line. The public key is the base64url of its 32 raw bytes. |
createSigner | Makes a Signer from the base64 of a PKCS#8 DER private key, or from a PKCS#8 PEM. A PKCS#8 PEM can have \n in place of line breaks. It throws The value is not an Ed25519 private key in PKCS#8. |
remoteKeySet | A key set from a JSON Web Key Set URL. It reads the URL at the first use. For an unknown key ID, it reads the URL again after refreshAfterMs. The default is 60000. |
staticKeySet | A key set that holds the given keys. |
toJwks | Writes keys as a JSON Web Key Set. |
keyIdOf | Returns the key ID: the first 16 characters of the base64url of the SHA-256 of the public key. |
interface PublicKey {
kid: string
publicKey: string // base64url of the 32 raw bytes
}
interface Signer extends PublicKey {
sign: (message: string) => Promise<string> // base64url signature
}
interface PublicKeySet {
get: (kid: string) => Promise<CryptoKey | null>
}The package also gives the lower-level functions that these functions use: toBase64url,
fromBase64url, importPublicKey, verifySignature, signJwt, verifyJwt,
signerFor, deriveSecretKey, signMcpRequest, createSessionToken,
verifyAppAssertion and unverifiedAssertionSubject.
@picked/app-kit/server
createAppHandler
createAppHandler(options: AppHandlerOptions): (request: Request) => Promise<Response>createAppHandler returns a fetch handler for the endpoint of the manifest.
| Option | Type | Default | Description |
|---|---|---|---|
pickedKeys | PublicKeySet | required | The public keys of Picked. Each signed request must verify with them. |
basePath | string | '' | The path that endpoint points to, for example /picked. The handler removes it from the path before it finds the route. |
onInstall | (event: InstallationCreatedEvent) => Promise<void> | void | none | Runs for installation.created. |
onUpgrade | (event: InstallationUpgradedEvent) => Promise<void> | void | none | Runs for installation.upgraded. |
onUninstall | (event: InstallationDeletedEvent) => Promise<void> | void | none | Runs for installation.deleted. |
onEvent | (event: AppEvent) => Promise<void> | void | none | Runs for each event that the manifest lists in events. |
tools | Record<string, (call: ToolCall) => Promise<Record<string, unknown>>> | none | The body of each workflow tool, by the name in the manifest. The function returns the output. |
mcp | { path: string; handle: (request: Request, installation: InstallationRef) => Promise<Response> } | none | path is the path of mcp.url of the manifest, for example /mcp. The handler compares it with the full path of the request, with basePath. handle answers each MCP request after the handler verifies it. |
manifest | AppManifest | none | The manifest. The handler answers GET /manifest.json with it. |
fallback | (request: Request) => Promise<Response> | Response | none | Answers each other request, for example the pages of the app. |
| Request | Answer |
|---|---|
POST /lifecycle | Runs onInstall, onUpgrade or onUninstall, then answers 200 with { "ok": true }. When the function throws an error, the handler throws it. |
POST /events | Runs onEvent, then answers 200 with { "ok": true }. |
POST /tools/<name> | Runs tools[name], then answers 200 with { "output": … }. When the function throws an error, it answers 422 with { "error": { "message": … } }. |
POST /tools/<name> for an unknown tool | 404 with { "error": { "message": "Unknown tool <name>" } }. The body that is not a tool call gets the same answer. |
Any method on the mcp option's path | Verifies the request, then calls mcp.handle. |
| A signed request that does not verify | 401 with { "error": "invalid_signature" }. |
GET /manifest.json, with manifest | 200 with the manifest. |
| Each other request | fallback. Without fallback, 404 with { "error": "not_found" }. |
The handler verifies the picked-signature header of each request to /lifecycle,
/events, /tools/<name> and the path of the mcp option. It does not verify a request that goes to
fallback. fallback gets the request without changes, with basePath in its path.
import { createAppHandler, readAppEnvironment } from '@picked/app-kit/server'
import { serve } from '@picked/app-kit/node'
const port = process.env.APP_PORT ?? '4103'
const { pickedKeys } = readAppEnvironment(process.env, port)
const handler = createAppHandler({
pickedKeys,
onInstall: (event) => {
console.log(`Installed on ${event.projectId}; token scopes: ${event.scopes.join(', ')}`)
},
tools: {
score_lead(call) {
const email = typeof call.arguments.email === 'string' ? call.arguments.email : ''
return Promise.resolve({ score: email.endsWith('.com') ? 60 : 30, tier: 'warm' })
},
},
})
serve(handler, Number(port))Responses
json(body: unknown, status?: number): Response
page(html: string, options: { frameAncestors: string[] }): Response| Function | Description |
|---|---|
json | A JSON answer with Content-Type: application/json. status is 200 when you do not give it. |
page | An HTML answer with the headers Content-Security-Policy: frame-ancestors <origins>, Referrer-Policy: strict-origin and X-Content-Type-Options: nosniff. With an empty frameAncestors, the policy is frame-ancestors 'none'. |
Session tokens
sessionTokenOf(request: Request): string | null
readSession(request: Request, pickedKeys: PublicKeySet): Promise<SessionClaims | null>| Function | Description |
|---|---|
sessionTokenOf | Returns the token in the Authorization: Bearer <token> header, or null. It does not verify the token. |
readSession | Verifies the token in the Authorization: Bearer <token> header. It returns the fields of the token, or null. |
A page of the app gets the session token from connect or
keepConnected. See
Session tokens.
Installation client
installationClientFor(
ref: Pick<InstallationRef, 'apiUrl' | 'installationId' | 'token' | 'tokenExpiresAt'>,
options: { privateKey: string; sessionToken?: string | null; fetch?: typeof fetch },
): InstallationClient
createInstallationClient(options: InstallationClientOptions): InstallationClientAn installation client calls the GraphQL API at <apiUrl>/api/graphql as one installation.
The function installationClientFor makes a client from the installation in a request from
Picked. It also makes a client from the fields of a session token.
InstallationClientOptions | Type | Description |
|---|---|---|
apiUrl | string | The origin of the Picked API, from apiUrl of the request. |
installationId | string | The installation. |
privateKey | string | The private key of the app, as the base64 of its PKCS#8 DER, or as PKCS#8 PEM. |
token | string | An installation token from a request from Picked. |
tokenExpiresAt | string | The time at which token expires. |
sessionToken | string | The session token of the person on a page of the app. |
fetch | typeof fetch | The fetch function that the client uses. The default is the global fetch. |
The client uses token until 60 seconds before it expires. Then it gets a new token with
appInstallationTokenCreate, and it sends a picked-app-assertion signed with
privateKey. For an installation without offlineAccess, Picked gives a new token only
with sessionToken. See Installation tokens.
interface InstallationClient {
labels: InstallationLabels
token: () => Promise<string>
request: <Result, Variables extends Record<string, unknown>>(
document: TadaDocumentNode<Result, Variables>,
variables: Variables,
options?: AdminApiRequestOptions,
) => Promise<Result>
}| Member | Description |
|---|---|
labels | The labels of the installation. See Labels. |
token | Returns a token of the installation. The client sends it in the X-API-Key header. |
request | Sends a typed GraphQL document with the token. It returns data, with the type of the document. |
The client sends each request with createAdminApiClient from
@picked/admin-api-client. Make a document with
graphql from that package. TadaDocumentNode and AdminApiRequestOptions are types of that
package. options.timeoutMs sets the time limit of one request. The default is 30 seconds.
A request throws these errors:
| Error | When |
|---|---|
AdminApiResponseError | The answer has GraphQL errors. The message has the message of each error, one on each line. codes has the code of each error. |
AdminApiRateLimitError | Picked refuses the request with a 429 status 4 times. The client waits about 1 second before it sends each retry. |
Error | The request fails, it takes more than its time limit, or the answer has an HTTP error and no GraphQL errors. |
import { graphql } from '@picked/admin-api-client'
import { installationClientFor } from '@picked/app-kit/server'
const RecentLeadsDocument = graphql(`
query RecentLeads($projectId: ID!, $first: Int!) {
project(input: { id: $projectId }) {
leads(first: $first) {
matchCount
}
}
}
`)
const client = installationClientFor(event, { privateKey })
const data = await client.request(RecentLeadsDocument, { projectId: event.projectId, first: 10 })Labels
interface InstallationLabels {
list: () => Promise<AppLabel[]>
get: (namespace: string, key: string) => Promise<AppLabel | undefined>
set: (
labels: readonly AppLabelInput[],
options?: { atomic?: boolean },
) => Promise<{ labels: AppLabel[]; skipped: AppLabel[] }>
delete: (labels: readonly AppLabelIdentifier[]) => Promise<string[]>
}| Member | Description |
|---|---|
list | Returns each label of the installation that is not after its time of expiry. The values of secret labels are included. |
get | Returns one label, or undefined. |
set | Makes or replaces labels with labelsSet. skipped holds the labels that an onlyIfAbsent write did not change. The default of atomic is false. |
delete | Removes labels with labelsDelete. It returns the IDs of the removed labels. |
set and delete throw LabelWriteError when Picked refuses a label.
AppLabelInput | Type | Description |
|---|---|---|
namespace | string | 1 to 64 lowercase letters, digits, _ or -. |
key | string | 1 to 64 lowercase letters, digits, _ or -. |
type | 'text' | 'number' | 'boolean' | 'json' | How to read the value. |
value | string | The value, as a string of the type. Not used with increment. |
increment | number | A number to add to a number label, in place of value. |
expiresIn | number | Seconds until the label expires, from 1 to 31536000. |
onlyIfAbsent | boolean | Writes the label only when no label with this namespace and key exists. |
secret | boolean | Keeps the value secret. Only a token of the installation reads it. Only for text or json, without increment or onlyIfAbsent. |
AppLabelIdentifier | Type | Description |
|---|---|---|
namespace | string | The namespace of the label. |
key | string | The key of the label. |
ifValue | string | Removes the label only when it holds this value. |
interface AppLabel {
namespace: string
key: string
type: 'text' | 'number' | 'boolean' | 'json'
value: string
secret: boolean
expiresAt: string | null
updatedAt: string
}
class LabelWriteError extends Error {
readonly userErrors: readonly { field: string[]; message: string; code: string }[]
}For the limits of an installation, see How to store data for an installation. For the rules of a label, see Labels.
await client.labels.set([
{ namespace: 'zoho', key: 'client_secret', type: 'text', value: clientSecret, secret: true },
])
const secret = await client.labels.get('zoho', 'client_secret')installationLinkUrl
installationLinkUrl(link: {
dashboardOrigin: string
appId: string
namespace: string
key: string
value: string
}): stringReturns <dashboardOrigin>/apps/<appId>/open?label=<namespace>.<key>&value=<value>. This
dashboard URL opens the installation of the app that holds a label with that value. A
secret label does not match.
| Parameter | Description |
|---|---|
dashboardOrigin | The origin of the dashboard, for example https://dashboard.picked.app. The function ignores a path. |
appId | The app ID, for example app_k3v9x2m1q8zt. picked app deploy prints it. Each Picked environment has a different app ID. |
namespace | The namespace of a label that is not secret. |
key | The key of that label. |
value | The value of that label. |
It throws TypeError in these conditions:
appIddoes not match^app_[a-z0-9]+$.isAppId(value)returnstruewhenvaluematches.namespaceorkeydoes not match^[a-z0-9_-]{1,64}$.dashboardOriginis not a URL.
On the server of the app, use readAppEnvironment. Give its appId
and the first of its dashboardOrigins() to installationLinkUrl. When PICKED_APP_ID is not
set, appId is null. Before Picked gives the dashboard origins, the list is empty:
import { installationLinkUrl, readAppEnvironment } from '@picked/app-kit/server'
const { dashboardOrigins, appId } = readAppEnvironment(process.env, '4103')
const [dashboardOrigin] = await dashboardOrigins()
if (dashboardOrigin !== undefined && appId !== null) {
const url = installationLinkUrl({
dashboardOrigin,
appId,
namespace: 'vercel',
key: 'configuration_id',
value: 'icfg_123',
})
}readAppEnvironment
readAppEnvironment(
env: Record<string, string | undefined>,
port: string,
options?: { fetch?: typeof fetch; refreshAfterMs?: number; timeoutMs?: number },
): AppEnvironmentAppEnvironment | Type | Value |
|---|---|---|
privateKey | string | PICKED_APP_PRIVATE_KEY. |
pickedUrl | string | PICKED_API_URL, without a / at the end. |
pickedKeys | PublicKeySet | A remoteKeySet for <pickedUrl>/.well-known/picked-app-keys.json. |
publicUrl | string | APP_PUBLIC_URL, without a / at the end. |
frameAncestors | string[] | The dashboard origins that PICKED_DASHBOARD_ORIGINS or DASHBOARD_PORT gives, as a list. Empty when the environment gives none. |
dashboardOrigins | () => Promise<string[]> | frameAncestors, or the origins in <pickedUrl>/.well-known/picked-app-config.json when the environment gives none. Give it to page. Its first origin is the dashboard to give installationLinkUrl. |
appId | string | null | PICKED_APP_ID. null when it is not set, or when it is not an app ID. |
| Parameter | Value |
|---|---|
port | The port of the app on your computer. |
options.fetch | The fetch that reads the public keys and the app config of Picked. |
options.refreshAfterMs | The minimum time between two reads of the app config. The default is 5 minutes. |
options.timeoutMs | The maximum time of one read of the app config. The default is 5 seconds. |
See App environment variables for each variable, the values when a variable is not set, and the errors.
withRewrittenPath
withRewrittenPath(handler: (request: Request) => Promise<Response>): (request: Request) => Promise<Response>On Vercel, a rewrite from /:path* to /api?__path=/:path* sends each path to one
Vercel function. The function withRewrittenPath puts the path from __path back in the URL of the request,
then calls handler. A request without __path goes to handler without changes.
{
"rewrites": [{ "source": "/:path*", "destination": "/api?__path=/:path*" }]
}api/index.ts:
import { withRewrittenPath } from '@picked/app-kit/server'
import { handler } from '../src/server.js'
export default { fetch: withRewrittenPath(handler) }@picked/app-kit/oauth
These functions run the authorization code flow of OAuth for one installation. The flow completes only in the browser that started it.
startAuthorization(request: Request, options: StartAuthorizationOptions): Promise<Response>
finishAuthorization(request: Request, options: FinishAuthorizationOptions): Promise<Response>
oauthStartPage(): string
oauthCallbackPage(result: { ok: boolean; message: string }): string
const OAUTH_START_PATH = '/oauth/start'
const OAUTH_START_READY_MESSAGE = 'picked-app:oauth-start-ready'
const OAUTH_START_MESSAGE = 'picked-app:oauth-start'
const OAUTH_RESULT_MESSAGE = 'picked-app:oauth-result'Steps of the flow
authorizeInPopupopens a new window atGET /oauth/start, on the origin of the page.- The window sends
picked-app:oauth-start-readyto the page that opened it. - The page sends
{ type: 'picked-app:oauth-start', sessionToken, params }to that window only. - The window sends
POST /oauth/start, withAuthorization: Bearer <sessionToken>andparamsas the JSON body. startAuthorizationverifies the session token and sets the OAuth cookie to a new unique value. It answers{ "url": "<authorization URL>" }.- The window goes to the authorization URL. The service sends it back to the callback.
finishAuthorizationcompares thenoncein thestatewith the cookie. It then callscomplete, and answers with the callback page.- The callback page sends
picked-app:oauth-resultto the page that opened the window, and closes.
Each message goes to the origin of the app only. The window and the page accept a message only from that origin.
startAuthorization
Answers each request to OAUTH_START_PATH.
| Request | Answer |
|---|---|
GET | The page of oauthStartPage. |
POST | Calls authorize. For a URL, 200 with { "url": "<URL>" } and the OAuth cookie. |
POST, refused | The Response that authorize returns. It sets no cookie. |
| No session token | 401 with { "error": { "message": "Sign in again" } }. The token is not valid, or is expired. |
| Other methods | 405 with Allow: GET, POST. |
The body of POST is the params of the page, as JSON. When the body is not JSON, params
is null.
StartAuthorizationOptions | Type | Description |
|---|---|---|
privateKey | string | The private key of the app. It encrypts the state. |
pickedKeys | PublicKeySet | The public keys of Picked. They verify the session. |
authorize | (start: AuthorizationStart) => Promise<string | Response> | Returns the authorization URL, or an error answer. |
AuthorizationStart | Type | Description |
|---|---|---|
session | SessionClaims | The verified session of the person in the dashboard. |
sessionToken | string | The session token. Give it to installationClientFor as sessionToken. |
params | unknown | The params of authorizeInPopup, or null. |
state | (connection: string) => Promise<string> | Returns the state parameter for the installation of the session, with this connection. |
An error answer goes to the page as the result. To give the person a message, answer
{ "error": { "message": "<text>" } }. Otherwise, the message is The app answered <status>.
finishAuthorization
Answers the callback of the service. Serve it at the callback address of your OAuth client.
FinishAuthorizationOptions | Type | Description |
|---|---|---|
privateKey | string | The private key of the app. |
complete | (callback: OAuthCallback) => Promise<{ ok: boolean; message: string }> | Exchanges the code, and keeps the connection. |
OAuthCallback | Type | Description |
|---|---|---|
state | OAuthState | The state that startAuthorization made. |
url | URL | The address of the callback, with the code or the error of the service. |
finishAuthorization does not call complete in these conditions:
- The
stateis not set, is not from the app, has changes, or is expired. - The request has no OAuth cookie, or the value of the cookie is not the
nonceof thestate.
Then the callback page shows This connection link has expired or was opened in another browser; start again.
The cookie stays. Otherwise, finishAuthorization deletes the cookie, so that the callback
completes one time. The callback page shows the ok and message of complete.
State
interface OAuthState {
installationId: string
apiUrl: string
connection: string // which connection, for an app with more than one provider
sessionToken: string
exp: number // unix seconds
nonce: string
}| Field | Value |
|---|---|
installationId | The installation of the session. |
apiUrl | The Picked API of the installation. |
connection | The value that authorize gives to state, for example us. |
sessionToken | The session token of the person who started the flow. |
exp | The time of expiry: 600 seconds after startAuthorization. |
nonce | The value of the OAuth cookie that startAuthorization set. |
The state is encrypted with AES-GCM, with a key from the private key of the app. The
service cannot read or change it.
OAuth cookie
| Origin of the app | Name | Attributes |
|---|---|---|
http: on localhost, 127.0.0.1 or [::1] | picked-oauth-<port> | Path=/; HttpOnly; SameSite=Lax |
| Other origins | __Host-picked-oauth | Path=/; HttpOnly; SameSite=Lax; Secure |
The origin of the app comes from the Host header of the request, and from the
X-Forwarded-Proto header that a proxy adds. Without these headers, it comes from the URL of
the request. For example, serve behind an https: proxy sets __Host-picked-oauth.
The cookie expires after 600 seconds. It is for the host of /oauth/start only, so the
callback must be on the same host. A browser holds one flow for each app at a time. A new
start replaces the cookie of an earlier flow, and the earlier flow then fails.
Pages
| Function | Description |
|---|---|
oauthStartPage | Returns the HTML that GET /oauth/start answers. Without a page that opened it, it shows Start connecting from the app’s page in Picked. |
oauthCallbackPage | Returns the HTML of the callback page. When the window has no page that opened it, the window stays open. It shows the message and You can close this window and return to Picked. |
startAuthorization and finishAuthorization send their pages with
Content-Security-Policy: frame-ancestors 'none', Cache-Control: no-store and
Referrer-Policy: no-referrer.
@picked/app-kit/node
serve(handler: (request: Request) => Promise<Response>, port: number): Server
frameScript(): Promise<Response>| Function | Description |
|---|---|
serve | Starts a node:http server on port. It writes the method, the path and the status of each request to the console. When handler throws an error, the answer is 500. |
frameScript | Answers with the browser build of @picked/app-kit/frame, as text/javascript. |
Serve frameScript() at a path of the app, for example /app-kit/frame.js. A page of the
app then imports connect from that path:
if (pathname === '/app-kit/frame.js') return frameScript()@picked/app-kit/frame
These functions run in a page that the dashboard shows in a slot. See Messages between the page and the dashboard.
connect
connect(options?: { dashboardOrigin?: string }): Promise<FrameContext>Sends picked:ready to the dashboard. It returns the FrameContext that the dashboard
sends back. connect works only in a page that the dashboard shows in an iframe. In a page
that is not in an iframe, it returns an error.
It accepts a message only from the window that contains the iframe (window.parent), and
only from dashboardOrigin. Without dashboardOrigin, it uses the origin of
document.referrer, or the origin of the page when the referrer is empty. In the iframe,
the referrer is the dashboard, because page lets only the dashboard origins
show the page.
interface FrameContext {
installationId: string
organizationId: string
organizationSlug: string
projectId: string
location: 'app-home' | 'workspace-prepublish-actions' | 'workspace-postpublish-actions'
appVersion: number
sessionToken: string
theme: 'light' | 'dark'
}<script type="module">
import { connect, autoResize } from '/app-kit/frame.js'
const context = await connect()
autoResize()
const response = await fetch('/api/leads', {
headers: { authorization: 'Bearer ' + context.sessionToken },
})
</script>keepConnected
keepConnected(options?: { dashboardOrigin?: string }): Promise<FrameConnection>
interface FrameConnection {
context: () => FrameContext
stop: () => void
}Calls connect with options, and returns when the dashboard sends the first
FrameContext. Then it sends picked:ready again to get a new FrameContext. It sends it 2
minutes before the session token expires, and not more than 4 minutes after the last
FrameContext. It reads the time of the expiry from the exp of the token. See
Session tokens. When it cannot read exp, it
sends picked:ready after 4 minutes.
keepConnected accepts a new FrameContext only from window.parent, and only from the
origin that connect accepts.
After each FrameContext, keepConnected waits 1 minute or more before it sends
picked:ready again. It compares the time now with the time to send every 15 seconds, and
when the page becomes visible or active. For this reason, a computer that starts again after
sleep mode gets a new session token in 15 seconds. If the dashboard does not send a
FrameContext in 10 seconds, keepConnected sends picked:ready again after 15 seconds.
Until a new FrameContext comes, context returns the last one.
FrameConnection | Description |
|---|---|
context | Returns the newest FrameContext from the dashboard. |
stop | Stops the requests for a new FrameContext. context then returns the last one. |
Use keepConnected on a page that stays open for longer than the session token. Read
connection.context().sessionToken for each request, and for each authorizeInPopup. Then
the request does not have an expired session token.
<script type="module">
import { keepConnected } from '/app-kit/frame.js'
const connection = await keepConnected()
const leads = () =>
fetch('/api/leads', {
headers: { authorization: 'Bearer ' + connection.context().sessionToken },
})
</script>resize and autoResize
resize(height: number): void
autoResize(): () => void| Function | Description |
|---|---|
resize | Sends picked:resize with height, in pixels. It changes the value to the next integer above it. |
autoResize | Sends the height of the page now, and again after each change to the size of document.body. It returns a function that stops it. |
authorizeInPopup
authorizeInPopup(request: { sessionToken: string; params?: unknown; connected?: () => Promise<string | null> }): Promise<{ ok: boolean; message: string }>Opens a new window at /oauth/start on the origin of the page. When the window sends
picked-app:oauth-start-ready, it sends the window sessionToken and params. It accepts
messages only from that window, and only from the origin of the page. params goes
to authorize on the server. See Steps of the flow. Call authorizeInPopup from a
click handler. A browser can stop a new window that the page opens at a different time.
request | Description |
|---|---|
sessionToken | The session token from keepConnected. |
params | A value for authorize, for example a region. The default is null. |
connected | Optional. Reads the connection from your server. It returns the message to show when the connection exists, or null. |
| Result | When |
|---|---|
{ ok, message } from the callback page | The callback page sends picked-app:oauth-result. |
{ ok: false, message: 'Allow pop-ups to connect' } | The browser stops the new window. |
{ ok: false, message: <error message> } | POST /oauth/start answers with an error, for example Sign in again. |
{ ok: false, message: 'The app answered <status>' } | POST /oauth/start answers with an error that has no message, or with no URL. |
{ ok: false, message: 'The app could not start connecting' } | The window cannot send POST /oauth/start, or cannot read its answer. |
{ ok: true, message: <message of connected> } | The window closes without a result, and connected then returns a message. |
{ ok: false, message: 'The connection window closed. If you finished connecting there, it shows here' } | The window closes without a result, and the page is the active window. With connected, it also returns null for 30 seconds. |
A service can separate the window from the page with a Cross-Origin-Opener-Policy header.
Then the page cannot see the window, and reads it as closed. The person can continue in the
window. The callback page stays open, and shows its result.
authorizeInPopup waits until the
page is the active window again. Without connected, it then returns the result of a closed
window. With connected, it calls connected one time each second, for 30 seconds, and
returns when connected returns a message. Read the connection from the server after
authorizeInPopup returns.
@picked/app-kit/testing
createFakePicked
createFakePicked(options: {
appPrivateKey: string
apiUrl?: string
offlineAccess?: boolean
}): Promise<FakePicked>A Picked API for the tests of one app. Give its fetch to the installation client. It answers
the operations that the installation client sends: appInstallationTokenCreate, the labels
of an installation, labelsSet and labelsDelete. It also publishes its public keys at
/.well-known/picked-app-keys.json.
| Option | Default | Description |
|---|---|---|
appPrivateKey | required | The private key of the app. The test API accepts a picked-app-assertion from its public key. |
apiUrl | https://api.picked.test | The origin of the test API. |
offlineAccess | false | When true, each installation has offlineAccess. |
FakePicked | Type | Description |
|---|---|---|
apiUrl | string | The origin of the test API. |
fetch | typeof fetch | The fetch function that sends requests to the test API. |
pickedKeys | PublicKeySet | The public keys of the test API. Give them to createAppHandler. |
labels | Map<string, Map<string, AppLabel>> | The labels, by installation ID, then by <namespace>.<key>. |
received | { operationName: string; variables: Record<string, unknown> }[] | Each GraphQL operation that the test API got, from first to last. |
tokenFor | (installationId) => Promise<{ token; expiresAt }> | Makes an installation token. |
installationRef | (installationId, overrides?) => Promise<InstallationRef> | An InstallationRef with a new token. The default organization is org and the default project is proj_1. |
signedRequest | (url, payload) => Promise<Request> | A POST request that the test API signs, as Picked does. |
mcpRequest | (url, ref, payload) => Promise<Request> | An MCP request that the test API signs, as Picked does. |
sessionRequest | (params: { ref; url; method?; body? }) => Promise<Request> | A request from a page of the app, with a session token for the user user-test. |
toolCall
toolCall(ref: InstallationRef, tool: string, args: Record<string, unknown>, test?: boolean): ToolCallMakes a ToolCall body. With test: true, run.test is true.
import { generateKeyPair } from '@picked/app-kit'
import { createAppHandler } from '@picked/app-kit/server'
import { createFakePicked, toolCall } from '@picked/app-kit/testing'
const { privateKey } = await generateKeyPair()
const picked = await createFakePicked({ appPrivateKey: privateKey })
const handler = createAppHandler({
pickedKeys: picked.pickedKeys,
tools: { score_lead: async () => ({ score: 80, tier: 'hot' }) },
})
const ref = await picked.installationRef('appi_test')
const response = await handler(
await picked.signedRequest(
'https://app.test/tools/score_lead',
toolCall(ref, 'score_lead', { email: 'ada@example.com' }),
),
)
console.log(response.status, await response.json())oauthCookie
oauthCookie(response: Response): stringReturns the <name>=<value> of the cookie that a POST /oauth/start answer sets, or an
empty string. Give it as the cookie header of a callback request in a test.
In this example, handler, picked and ref are from the example of toolCall.
The fallback of handler sends /oauth/start and /oauth/callback to the OAuth functions.
const started = await handler(
await picked.sessionRequest({
ref,
url: 'https://app.test/oauth/start',
method: 'POST',
body: { region: 'eu' },
}),
)
const { url } = await started.json()
const state = new URL(url).searchParams.get('state') ?? ''
const callback = await handler(
new Request(`https://app.test/oauth/callback?code=abc&state=${state}`, {
headers: { cookie: oauthCookie(started) },
}),
)app-kit-copy-frame
app-kit-copy-frame <dir>Copies the browser build of @picked/app-kit/frame to <dir>/app-kit/frame.js. Use it on a
host that serves static files, for example the public directory of a Vercel project.
Without <dir>, it writes Usage: app-kit-copy-frame <dir> and stops with status 1.
Related
- App protocol — the requests and the messages that this package implements.
- App manifest — the fields of
AppManifest. - App environment variables — the variables of
readAppEnvironment. - How to test an app
- How to store data for an installation
- How to connect an external service with OAuth
