picked 0.0.111-next.3 → 0.0.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/docs/explanation/app-authentication.md +178 -0
- package/docs/explanation/apps.md +169 -0
- package/docs/explanation/conditions-and-the-logic-engine.md +12 -2
- package/docs/explanation/feature-flag-allocation.md +5 -3
- package/docs/how-to/apps/add-a-page-to-the-dashboard.md +257 -0
- package/docs/how-to/apps/add-a-workflow-tool.md +199 -0
- package/docs/how-to/apps/add-an-mcp-server-to-an-app.md +210 -0
- package/docs/how-to/apps/connect-a-third-party-service-with-oauth.md +307 -0
- package/docs/how-to/apps/create-an-app-in-the-dashboard.md +162 -0
- package/docs/how-to/apps/deploy-an-app.md +201 -0
- package/docs/how-to/apps/develop-an-app-locally.md +152 -0
- package/docs/how-to/apps/host-an-app-on-vercel.md +226 -0
- package/docs/how-to/apps/install-an-app.md +116 -0
- package/docs/how-to/apps/link-to-an-installation-from-your-site.md +134 -0
- package/docs/how-to/apps/read-project-data-from-an-app.md +225 -0
- package/docs/how-to/apps/rotate-an-app-key.md +130 -0
- package/docs/how-to/apps/run-code-when-a-workspace-publishes.md +148 -0
- package/docs/how-to/apps/store-data-for-an-installation.md +230 -0
- package/docs/how-to/apps/test-an-app.md +359 -0
- package/docs/how-to/apps/upgrade-or-uninstall-an-app.md +97 -0
- package/docs/how-to/apps/use-an-app-tool-in-a-workflow.md +112 -0
- package/docs/index.md +6 -3
- package/docs/reference/apps/app-kit.md +811 -0
- package/docs/reference/apps/environment.md +116 -0
- package/docs/reference/apps/manifest.md +311 -0
- package/docs/reference/apps/protocol.md +497 -0
- package/docs/reference/dashboard/apps.md +504 -0
- package/docs/reference/dashboard/external-apis.md +5 -0
- package/docs/reference/dashboard/features.mdx +5 -5
- package/docs/reference/dashboard/labels.md +25 -8
- package/docs/reference/dashboard/lead-search.md +6 -6
- package/docs/reference/dashboard/reports.mdx +13 -5
- package/docs/reference/dashboard/workflow-tools.md +14 -0
- package/docs/reference/glossary.md +153 -140
- package/docs/reference/management-api/authentication.md +36 -27
- package/docs/reference/management-api/authorization-and-scopes.md +73 -21
- package/docs/reference/management-api/schema/api-key.md +10 -10
- package/docs/reference/management-api/schema/app.md +726 -0
- package/docs/reference/management-api/schema/auth.md +7 -7
- package/docs/reference/management-api/schema/common.md +54 -35
- package/docs/reference/management-api/schema/feature.md +1 -1
- package/docs/reference/management-api/schema/feedback.md +1 -1
- package/docs/reference/management-api/schema/index.md +35 -20
- package/docs/reference/management-api/schema/label.md +31 -8
- package/docs/reference/management-api/schema/organization.md +66 -66
- package/docs/reference/management-api/schema/project.md +5 -5
- package/docs/reference/management-api/schema/report.md +1 -1
- package/docs/reference/management-api/schema/shopify.md +19 -19
- package/docs/reference/management-api/schema/workflow.md +6 -1
- package/docs/reference/management-api/schema/workspace.md +2 -2
- package/docs/reference/sdk/analytics-events.md +42 -36
- package/docs/reference/sdk/conditions.md +3 -3
- package/docs/reference/sdk/fields.md +5 -4
- package/docs/reference/sdk/index.md +4 -4
- package/docs/reference/sdk/plugins/create-experience.md +11 -9
- package/docs/reference/sdk/plugins/hotjar.md +2 -2
- package/docs/reference/sdk/plugins/sentry.md +2 -2
- package/docs/reference/sdk/plugins/shopify.md +2 -2
- package/docs/reference/sdk/predicates.md +5 -5
- package/docs/reference/sdk/type-generation.md +24 -19
- package/docs/reference/tools/admin-api-client.md +15 -0
- package/docs/reference/tools/cli.md +192 -41
- package/docs/reference/tools/mcp.md +30 -9
- package/docs/tutorials/first-app.md +308 -0
- package/package.json +4 -4
- package/docs/explanation/how-pickedql-works.md +0 -76
- package/docs/how-to/analytics/index.md +0 -324
- package/docs/reference/management-api/schema/analytics.md +0 -75
- package/docs/reference/pickedql/data-sources.md +0 -174
- package/docs/reference/pickedql/dimensions.md +0 -103
- package/docs/reference/pickedql/filtering.md +0 -64
- package/docs/reference/pickedql/index.md +0 -18
- package/docs/reference/pickedql/schema.md +0 -172
- package/docs/reference/pickedql/virtual-functions.md +0 -248
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
---
|
|
2
|
+
type: reference
|
|
3
|
+
layout: docs
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# `@picked/app-kit`
|
|
7
|
+
|
|
8
|
+
`@picked/app-kit` is the TypeScript library for the server and the pages of a Picked app. It
|
|
9
|
+
implements the [app protocol](/reference/apps/protocol).
|
|
10
|
+
|
|
11
|
+
## Entry points
|
|
12
|
+
|
|
13
|
+
| Import | Runs in | Contents |
|
|
14
|
+
| ------------------------- | ------------------ | ------------------------------------------------------------------------- |
|
|
15
|
+
| `@picked/app-kit` | Server and browser | The manifest, the protocol types and constants, and the key functions. |
|
|
16
|
+
| `@picked/app-kit/server` | Server | The request handler, the installation client, and the environment reader. |
|
|
17
|
+
| `@picked/app-kit/oauth` | Server | The start and the callback of an OAuth authorization. |
|
|
18
|
+
| `@picked/app-kit/node` | `Node.js` | `serve` and `frameScript`. |
|
|
19
|
+
| `@picked/app-kit/frame` | Browser | The functions for a page in a dashboard slot. |
|
|
20
|
+
| `@picked/app-kit/testing` | Tests | A Picked API for tests. |
|
|
21
|
+
|
|
22
|
+
`@picked/app-kit/server` also gives the protocol and key functions of `@picked/app-kit`, but
|
|
23
|
+
not the manifest functions. The package also has the command `app-kit-copy-frame`. See
|
|
24
|
+
[`app-kit-copy-frame`](#app-kit-copy-frame).
|
|
25
|
+
|
|
26
|
+
## `@picked/app-kit`
|
|
27
|
+
|
|
28
|
+
### Manifest
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
parseManifest(value: unknown): { ok: true; manifest: AppManifest } | { ok: false; issues: string[] }
|
|
32
|
+
isAppUrl(value: unknown): value is string
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
| Export | Description |
|
|
36
|
+
| --------------- | ------------------------------------------------------------------------------------------- |
|
|
37
|
+
| `parseManifest` | Checks a manifest. It returns all the problems that it finds. |
|
|
38
|
+
| `isAppUrl` | Returns `true` for an `https` URL, or an `http` URL on `localhost`, `127.0.0.1` or `[::1]`. |
|
|
39
|
+
|
|
40
|
+
| Constant | Value |
|
|
41
|
+
| -------------------- | ------------------------------------------------------------------------------- |
|
|
42
|
+
| `APP_SLOT_LOCATIONS` | `['app-home', 'workspace-prepublish-actions', 'workspace-postpublish-actions']` |
|
|
43
|
+
| `APP_EVENTS` | `['workspace.published']` |
|
|
44
|
+
| `APP_VALUE_TYPES` | `['string', 'number', 'boolean', 'json']` |
|
|
45
|
+
|
|
46
|
+
The types are `AppManifest`, `AppSlot`, `AppWorkflowTool`, `AppToolArgument`,
|
|
47
|
+
`AppToolOutputField`, `AppSlotLocation`, `AppEventName` and `AppValueType`. See
|
|
48
|
+
[App manifest](/reference/apps/manifest) for each field and each validation message. An app
|
|
49
|
+
declares its manifest in the `app` section of `picked.config.ts`, with `defineConfig` from
|
|
50
|
+
`@picked/config/define`. See
|
|
51
|
+
[The `app` section of `picked.config`](/reference/apps/manifest#the-app-section-of-pickedconfig).
|
|
52
|
+
|
|
53
|
+
### Protocol
|
|
54
|
+
|
|
55
|
+
| Constant | Value |
|
|
56
|
+
| ---------------------- | ------------------------------------- |
|
|
57
|
+
| `SIGNATURE_HEADER` | `'picked-signature'` |
|
|
58
|
+
| `INSTALLATION_HEADER` | `'picked-installation-id'` |
|
|
59
|
+
| `APP_ASSERTION_HEADER` | `'picked-app-assertion'` |
|
|
60
|
+
| `CONTEXT_HEADER` | `'picked-context'` |
|
|
61
|
+
| `PICKED_KEYS_PATH` | `'/.well-known/picked-app-keys.json'` |
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
verifyBody(keys: PublicKeySet, body: string, header: string | null): Promise<boolean>
|
|
65
|
+
verifyMcpRequest(keys: PublicKeySet, headers: Headers, body: string): Promise<InstallationRef | null>
|
|
66
|
+
verifySessionToken(keys: PublicKeySet, token: string): Promise<SessionClaims | null>
|
|
67
|
+
createAppAssertion(signer: Signer, options: { installationId: string; audience: string }): Promise<string>
|
|
68
|
+
signBody(signer: Signer, body: string, timestamp?: number): Promise<string>
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| Function | Description |
|
|
72
|
+
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
73
|
+
| `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. |
|
|
74
|
+
| `verifyMcpRequest` | Verifies an MCP request from Picked. It returns the installation from `picked-context`, or `null`. |
|
|
75
|
+
| `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. |
|
|
76
|
+
| `createAppAssertion` | Makes a `picked-app-assertion` token for the installation. It expires after 60 seconds. `audience` is the origin of the Picked API. |
|
|
77
|
+
| `signBody` | Makes a `picked-signature` value. `timestamp` is in `unix` seconds, and is the current time when you do not give it. |
|
|
78
|
+
|
|
79
|
+
The protocol types are `InstallationRef`, `InstallationCreatedEvent`,
|
|
80
|
+
`InstallationUpgradedEvent`, `InstallationDeletedEvent`, `LifecycleEvent`,
|
|
81
|
+
`WorkspacePublishedEvent`, `AppEvent`, `ToolCall`, `ToolResult`, `SessionClaims` and
|
|
82
|
+
`AppAssertionClaims`. See [App protocol](/reference/apps/protocol) for their fields.
|
|
83
|
+
|
|
84
|
+
### Keys
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
generateKeyPair(): Promise<{ privateKey: string; publicKey: string; kid: string }>
|
|
88
|
+
createSigner(privateKey: string): Promise<Signer>
|
|
89
|
+
remoteKeySet(options: { url: string; fetch?: typeof fetch; refreshAfterMs?: number }): PublicKeySet
|
|
90
|
+
staticKeySet(keys: readonly PublicKey[]): PublicKeySet
|
|
91
|
+
toJwks(keys: readonly PublicKey[]): Jwks
|
|
92
|
+
keyIdOf(publicKey: string): Promise<string>
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
| Function | Description |
|
|
96
|
+
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
97
|
+
| `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. |
|
|
98
|
+
| `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`. |
|
|
99
|
+
| `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`. |
|
|
100
|
+
| `staticKeySet` | A key set that holds the given keys. |
|
|
101
|
+
| `toJwks` | Writes keys as a JSON Web Key Set. |
|
|
102
|
+
| `keyIdOf` | Returns the key ID: the first 16 characters of the `base64url` of the SHA-256 of the public key. |
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
interface PublicKey {
|
|
106
|
+
kid: string
|
|
107
|
+
publicKey: string // base64url of the 32 raw bytes
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface Signer extends PublicKey {
|
|
111
|
+
sign: (message: string) => Promise<string> // base64url signature
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
interface PublicKeySet {
|
|
115
|
+
get: (kid: string) => Promise<CryptoKey | null>
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The package also gives the lower-level functions that these functions use: `toBase64url`,
|
|
120
|
+
`fromBase64url`, `importPublicKey`, `verifySignature`, `signJwt`, `verifyJwt`,
|
|
121
|
+
`signerFor`, `deriveSecretKey`, `signMcpRequest`, `createSessionToken`,
|
|
122
|
+
`verifyAppAssertion` and `unverifiedAssertionSubject`.
|
|
123
|
+
|
|
124
|
+
## `@picked/app-kit/server`
|
|
125
|
+
|
|
126
|
+
### `createAppHandler`
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
createAppHandler(options: AppHandlerOptions): (request: Request) => Promise<Response>
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`createAppHandler` returns a `fetch` handler for the `endpoint` of the manifest.
|
|
133
|
+
|
|
134
|
+
| Option | Type | Default | Description |
|
|
135
|
+
| ------------- | -------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------- |
|
|
136
|
+
| `pickedKeys` | `PublicKeySet` | required | The public keys of Picked. Each signed request must verify with them. |
|
|
137
|
+
| `basePath` | `string` | `''` | The path that `endpoint` points to, for example `/picked`. The handler removes it from the path before it finds the route. |
|
|
138
|
+
| `onInstall` | `(event: InstallationCreatedEvent) => Promise<void> \| void` | none | Runs for `installation.created`. |
|
|
139
|
+
| `onUpgrade` | `(event: InstallationUpgradedEvent) => Promise<void> \| void` | none | Runs for `installation.upgraded`. |
|
|
140
|
+
| `onUninstall` | `(event: InstallationDeletedEvent) => Promise<void> \| void` | none | Runs for `installation.deleted`. |
|
|
141
|
+
| `onEvent` | `(event: AppEvent) => Promise<void> \| void` | none | Runs for each event that the manifest lists in `events`. |
|
|
142
|
+
| `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`. |
|
|
143
|
+
| `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. |
|
|
144
|
+
| `manifest` | `AppManifest` | none | The manifest. The handler answers `GET /manifest.json` with it. |
|
|
145
|
+
| `fallback` | `(request: Request) => Promise<Response> \| Response` | none | Answers each other request, for example the pages of the app. |
|
|
146
|
+
|
|
147
|
+
| Request | Answer |
|
|
148
|
+
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
149
|
+
| `POST /lifecycle` | Runs `onInstall`, `onUpgrade` or `onUninstall`, then answers `200` with `{ "ok": true }`. When the function throws an error, the handler throws it. |
|
|
150
|
+
| `POST /events` | Runs `onEvent`, then answers `200` with `{ "ok": true }`. |
|
|
151
|
+
| `POST /tools/<name>` | Runs `tools[name]`, then answers `200` with `{ "output": … }`. When the function throws an error, it answers `422` with `{ "error": { "message": … } }`. |
|
|
152
|
+
| `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. |
|
|
153
|
+
| Any method on the `mcp` option's `path` | Verifies the request, then calls `mcp.handle`. |
|
|
154
|
+
| A signed request that does not verify | `401` with `{ "error": "invalid_signature" }`. |
|
|
155
|
+
| `GET /manifest.json`, with `manifest` | `200` with the manifest. |
|
|
156
|
+
| Each other request | `fallback`. Without `fallback`, `404` with `{ "error": "not_found" }`. |
|
|
157
|
+
|
|
158
|
+
The handler verifies the `picked-signature` header of each request to `/lifecycle`,
|
|
159
|
+
`/events`, `/tools/<name>` and the `path` of the `mcp` option. It does not verify a request that goes to
|
|
160
|
+
`fallback`. `fallback` gets the request without changes, with `basePath` in its path.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { createAppHandler, readAppEnvironment } from '@picked/app-kit/server'
|
|
164
|
+
import { serve } from '@picked/app-kit/node'
|
|
165
|
+
|
|
166
|
+
const port = process.env.APP_PORT ?? '4103'
|
|
167
|
+
const { pickedKeys } = readAppEnvironment(process.env, port)
|
|
168
|
+
|
|
169
|
+
const handler = createAppHandler({
|
|
170
|
+
pickedKeys,
|
|
171
|
+
onInstall: (event) => {
|
|
172
|
+
console.log(`Installed on ${event.projectId}; token scopes: ${event.scopes.join(', ')}`)
|
|
173
|
+
},
|
|
174
|
+
tools: {
|
|
175
|
+
score_lead(call) {
|
|
176
|
+
const email = typeof call.arguments.email === 'string' ? call.arguments.email : ''
|
|
177
|
+
return Promise.resolve({ score: email.endsWith('.com') ? 60 : 30, tier: 'warm' })
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
serve(handler, Number(port))
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Responses
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
json(body: unknown, status?: number): Response
|
|
189
|
+
page(html: string, options: { frameAncestors: string[] }): Response
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
| Function | Description |
|
|
193
|
+
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
194
|
+
| `json` | A JSON answer with `Content-Type: application/json`. `status` is `200` when you do not give it. |
|
|
195
|
+
| `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'`. |
|
|
196
|
+
|
|
197
|
+
### Session tokens
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
sessionTokenOf(request: Request): string | null
|
|
201
|
+
readSession(request: Request, pickedKeys: PublicKeySet): Promise<SessionClaims | null>
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
| Function | Description |
|
|
205
|
+
| ---------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
206
|
+
| `sessionTokenOf` | Returns the token in the `Authorization: Bearer <token>` header, or `null`. It does not verify the token. |
|
|
207
|
+
| `readSession` | Verifies the token in the `Authorization: Bearer <token>` header. It returns the fields of the token, or `null`. |
|
|
208
|
+
|
|
209
|
+
A page of the app gets the session token from [`connect`](#connect). See
|
|
210
|
+
[Session tokens](/reference/apps/protocol#session-tokens).
|
|
211
|
+
|
|
212
|
+
### Installation client
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
installationClientFor(
|
|
216
|
+
ref: Pick<InstallationRef, 'apiUrl' | 'installationId' | 'token' | 'tokenExpiresAt'>,
|
|
217
|
+
options: { privateKey: string; sessionToken?: string | null; fetch?: typeof fetch },
|
|
218
|
+
): InstallationClient
|
|
219
|
+
|
|
220
|
+
createInstallationClient(options: InstallationClientOptions): InstallationClient
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
An installation client calls the GraphQL API at `<apiUrl>/api/graphql` as one installation.
|
|
224
|
+
The function `installationClientFor` makes a client from the installation in a request from
|
|
225
|
+
Picked. It also makes a client from the fields of a session token.
|
|
226
|
+
|
|
227
|
+
| `InstallationClientOptions` | Type | Description |
|
|
228
|
+
| --------------------------- | -------------- | ------------------------------------------------------------------------------------ |
|
|
229
|
+
| `apiUrl` | `string` | The origin of the Picked API, from `apiUrl` of the request. |
|
|
230
|
+
| `installationId` | `string` | The installation. |
|
|
231
|
+
| `privateKey` | `string` | The private key of the app, as the `base64` of its `PKCS#8 DER`, or as `PKCS#8 PEM`. |
|
|
232
|
+
| `token` | `string` | An installation token from a request from Picked. |
|
|
233
|
+
| `tokenExpiresAt` | `string` | The time at which `token` expires. |
|
|
234
|
+
| `sessionToken` | `string` | The session token of the person on a page of the app. |
|
|
235
|
+
| `fetch` | `typeof fetch` | The `fetch` function that the client uses. The default is the global `fetch`. |
|
|
236
|
+
|
|
237
|
+
The client uses `token` until 60 seconds before it expires. Then it gets a new token with
|
|
238
|
+
`appInstallationTokenCreate`, and it sends a `picked-app-assertion` signed with
|
|
239
|
+
`privateKey`. For an installation without `offlineAccess`, Picked gives a new token only
|
|
240
|
+
with `sessionToken`. See [Installation tokens](/reference/apps/protocol#installation-tokens).
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
interface InstallationClient {
|
|
244
|
+
labels: InstallationLabels
|
|
245
|
+
token: () => Promise<string>
|
|
246
|
+
request: <Result, Variables extends Record<string, unknown>>(
|
|
247
|
+
document: TadaDocumentNode<Result, Variables>,
|
|
248
|
+
variables: Variables,
|
|
249
|
+
options?: AdminApiRequestOptions,
|
|
250
|
+
) => Promise<Result>
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
| Member | Description |
|
|
255
|
+
| --------- | ------------------------------------------------------------------------------------------------ |
|
|
256
|
+
| `labels` | The labels of the installation. See [Labels](#labels). |
|
|
257
|
+
| `token` | Returns a token of the installation. The client sends it in the `X-API-Key` header. |
|
|
258
|
+
| `request` | Sends a typed GraphQL document with the token. It returns `data`, with the type of the document. |
|
|
259
|
+
|
|
260
|
+
The client sends each request with `createAdminApiClient` from
|
|
261
|
+
[`@picked/admin-api-client`](/reference/tools/admin-api-client). Make a document with
|
|
262
|
+
`graphql` from that package. `TadaDocumentNode` and `AdminApiRequestOptions` are types of that
|
|
263
|
+
package. `options.timeoutMs` sets the time limit of one request. The default is 30 seconds.
|
|
264
|
+
|
|
265
|
+
A request throws these errors:
|
|
266
|
+
|
|
267
|
+
| Error | When |
|
|
268
|
+
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
|
269
|
+
| `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. |
|
|
270
|
+
| `Error` | The request fails, it takes more than its time limit, or the answer has an HTTP error and no GraphQL errors. |
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
import { graphql } from '@picked/admin-api-client'
|
|
274
|
+
import { installationClientFor } from '@picked/app-kit/server'
|
|
275
|
+
|
|
276
|
+
const RecentLeadsDocument = graphql(`
|
|
277
|
+
query RecentLeads($projectId: ID!, $first: Int!) {
|
|
278
|
+
project(input: { id: $projectId }) {
|
|
279
|
+
leads(first: $first) {
|
|
280
|
+
matchCount
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
`)
|
|
285
|
+
|
|
286
|
+
const client = installationClientFor(event, { privateKey })
|
|
287
|
+
const data = await client.request(RecentLeadsDocument, { projectId: event.projectId, first: 10 })
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
### Labels
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
interface InstallationLabels {
|
|
294
|
+
list: () => Promise<AppLabel[]>
|
|
295
|
+
get: (namespace: string, key: string) => Promise<AppLabel | undefined>
|
|
296
|
+
set: (
|
|
297
|
+
labels: readonly AppLabelInput[],
|
|
298
|
+
options?: { atomic?: boolean },
|
|
299
|
+
) => Promise<{ labels: AppLabel[]; skipped: AppLabel[] }>
|
|
300
|
+
delete: (labels: readonly AppLabelIdentifier[]) => Promise<string[]>
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
| Member | Description |
|
|
305
|
+
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
306
|
+
| `list` | Returns each label of the installation that is not after its time of expiry. The values of secret labels are included. |
|
|
307
|
+
| `get` | Returns one label, or `undefined`. |
|
|
308
|
+
| `set` | Makes or replaces labels with `labelsSet`. `skipped` holds the labels that an `onlyIfAbsent` write did not change. The default of `atomic` is `false`. |
|
|
309
|
+
| `delete` | Removes labels with `labelsDelete`. It returns the IDs of the removed labels. |
|
|
310
|
+
|
|
311
|
+
`set` and `delete` throw `LabelWriteError` when Picked refuses a label.
|
|
312
|
+
|
|
313
|
+
| `AppLabelInput` | Type | Description |
|
|
314
|
+
| --------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
|
315
|
+
| `namespace` | `string` | 1 to 64 lowercase letters, digits, `_` or `-`. |
|
|
316
|
+
| `key` | `string` | 1 to 64 lowercase letters, digits, `_` or `-`. |
|
|
317
|
+
| `type` | `'text' \| 'number' \| 'boolean' \| 'json'` | How to read the value. |
|
|
318
|
+
| `value` | `string` | The value, as a string of the `type`. Not used with `increment`. |
|
|
319
|
+
| `increment` | `number` | A number to add to a `number` label, in place of `value`. |
|
|
320
|
+
| `expiresIn` | `number` | Seconds until the label expires, from 1 to 31536000. |
|
|
321
|
+
| `onlyIfAbsent` | `boolean` | Writes the label only when no label with this `namespace` and `key` exists. |
|
|
322
|
+
| `secret` | `boolean` | Keeps the value secret. Only a token of the installation reads it. Only for `text` or `json`, without `increment` or `onlyIfAbsent`. |
|
|
323
|
+
|
|
324
|
+
| `AppLabelIdentifier` | Type | Description |
|
|
325
|
+
| -------------------- | -------- | ------------------------------------------------ |
|
|
326
|
+
| `namespace` | `string` | The namespace of the label. |
|
|
327
|
+
| `key` | `string` | The key of the label. |
|
|
328
|
+
| `ifValue` | `string` | Removes the label only when it holds this value. |
|
|
329
|
+
|
|
330
|
+
```ts
|
|
331
|
+
interface AppLabel {
|
|
332
|
+
namespace: string
|
|
333
|
+
key: string
|
|
334
|
+
type: 'text' | 'number' | 'boolean' | 'json'
|
|
335
|
+
value: string
|
|
336
|
+
secret: boolean
|
|
337
|
+
expiresAt: string | null
|
|
338
|
+
updatedAt: string
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
class LabelWriteError extends Error {
|
|
342
|
+
readonly userErrors: readonly { field: string[]; message: string; code: string }[]
|
|
343
|
+
}
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
For the limits of an installation, see
|
|
347
|
+
[How to store data for an installation](/how-to/apps/store-data-for-an-installation#6-handle-a-refused-write).
|
|
348
|
+
For the rules of a label, see [Labels](/reference/dashboard/labels).
|
|
349
|
+
|
|
350
|
+
```ts
|
|
351
|
+
await client.labels.set([
|
|
352
|
+
{ namespace: 'zoho', key: 'client_secret', type: 'text', value: clientSecret, secret: true },
|
|
353
|
+
])
|
|
354
|
+
const secret = await client.labels.get('zoho', 'client_secret')
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
### `installationLinkUrl`
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
installationLinkUrl(link: {
|
|
361
|
+
dashboardOrigin: string
|
|
362
|
+
appId: string
|
|
363
|
+
namespace: string
|
|
364
|
+
key: string
|
|
365
|
+
value: string
|
|
366
|
+
}): string
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
Returns `<dashboardOrigin>/apps/<appId>/open?label=<namespace>.<key>&value=<value>`. This
|
|
370
|
+
dashboard URL opens the installation of the app that holds a label with that value. A
|
|
371
|
+
secret label does not match.
|
|
372
|
+
|
|
373
|
+
| Parameter | Description |
|
|
374
|
+
| ----------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
|
375
|
+
| `dashboardOrigin` | The origin of the dashboard, for example `https://dashboard.picked.app`. The function ignores a path. |
|
|
376
|
+
| `appId` | The app ID, for example `app_k3v9x2m1q8zt`. `picked app deploy` prints it. Each Picked environment has a different app ID. |
|
|
377
|
+
| `namespace` | The namespace of a label that is not secret. |
|
|
378
|
+
| `key` | The key of that label. |
|
|
379
|
+
| `value` | The value of that label. |
|
|
380
|
+
|
|
381
|
+
It throws `TypeError` in these conditions:
|
|
382
|
+
|
|
383
|
+
- `appId` does not match `^app_[a-z0-9]+$`.
|
|
384
|
+
- `namespace` or `key` does not match `^[a-z0-9_-]{1,64}$`.
|
|
385
|
+
- `dashboardOrigin` is not a URL.
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
import { installationLinkUrl } from '@picked/app-kit/server'
|
|
389
|
+
|
|
390
|
+
const url = installationLinkUrl({
|
|
391
|
+
dashboardOrigin: 'https://dashboard.picked.app',
|
|
392
|
+
appId: 'app_k3v9x2m1q8zt',
|
|
393
|
+
namespace: 'vercel',
|
|
394
|
+
key: 'configuration_id',
|
|
395
|
+
value: 'icfg_123',
|
|
396
|
+
})
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
### `readAppEnvironment`
|
|
400
|
+
|
|
401
|
+
```ts
|
|
402
|
+
readAppEnvironment(
|
|
403
|
+
env: Record<string, string | undefined>,
|
|
404
|
+
port: string,
|
|
405
|
+
options?: { fetch?: typeof fetch },
|
|
406
|
+
): AppEnvironment
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
| `AppEnvironment` | Type | Value |
|
|
410
|
+
| ---------------- | -------------- | ----------------------------------------------------------------------- |
|
|
411
|
+
| `privateKey` | `string` | `PICKED_APP_PRIVATE_KEY`. |
|
|
412
|
+
| `pickedUrl` | `string` | `PICKED_API_URL`, without a `/` at the end. |
|
|
413
|
+
| `pickedKeys` | `PublicKeySet` | A `remoteKeySet` for `<pickedUrl>/.well-known/picked-app-keys.json`. |
|
|
414
|
+
| `publicUrl` | `string` | `APP_PUBLIC_URL`, without a `/` at the end. |
|
|
415
|
+
| `frameAncestors` | `string[]` | `PICKED_DASHBOARD_ORIGINS`, as a list. Give it to [`page`](#responses). |
|
|
416
|
+
|
|
417
|
+
`port` is the port of the app on your computer. `options.fetch` reads the public keys of
|
|
418
|
+
Picked. See [App environment variables](/reference/apps/environment) for each variable, the
|
|
419
|
+
values when a variable is not set, and the errors.
|
|
420
|
+
|
|
421
|
+
### `withRewrittenPath`
|
|
422
|
+
|
|
423
|
+
```ts
|
|
424
|
+
withRewrittenPath(handler: (request: Request) => Promise<Response>): (request: Request) => Promise<Response>
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
On Vercel, a rewrite from `/:path*` to `/api?__path=/:path*` sends each path to one
|
|
428
|
+
Vercel function. The function `withRewrittenPath` puts the path from `__path` back in the URL of the request,
|
|
429
|
+
then calls `handler`. A request without `__path` goes to `handler` without changes.
|
|
430
|
+
|
|
431
|
+
```json
|
|
432
|
+
{
|
|
433
|
+
"rewrites": [{ "source": "/:path*", "destination": "/api?__path=/:path*" }]
|
|
434
|
+
}
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
`api/index.ts`:
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
import { withRewrittenPath } from '@picked/app-kit/server'
|
|
441
|
+
import { handler } from '../src/server.js'
|
|
442
|
+
|
|
443
|
+
export default { fetch: withRewrittenPath(handler) }
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
## `@picked/app-kit/oauth`
|
|
447
|
+
|
|
448
|
+
These functions run the authorization code flow of OAuth for one installation. The flow
|
|
449
|
+
completes only in the browser that started it.
|
|
450
|
+
|
|
451
|
+
```ts
|
|
452
|
+
startAuthorization(request: Request, options: StartAuthorizationOptions): Promise<Response>
|
|
453
|
+
finishAuthorization(request: Request, options: FinishAuthorizationOptions): Promise<Response>
|
|
454
|
+
oauthStartPage(): string
|
|
455
|
+
oauthCallbackPage(result: { ok: boolean; message: string }): string
|
|
456
|
+
|
|
457
|
+
const OAUTH_START_PATH = '/oauth/start'
|
|
458
|
+
const OAUTH_START_READY_MESSAGE = 'picked-app:oauth-start-ready'
|
|
459
|
+
const OAUTH_START_MESSAGE = 'picked-app:oauth-start'
|
|
460
|
+
const OAUTH_RESULT_MESSAGE = 'picked-app:oauth-result'
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
### Steps of the flow
|
|
464
|
+
|
|
465
|
+
1. [`authorizeInPopup`](#authorizeinpopup) opens a new window at `GET /oauth/start`, on the
|
|
466
|
+
origin of the page.
|
|
467
|
+
2. The window sends `picked-app:oauth-start-ready` to the page that opened it.
|
|
468
|
+
3. The page sends `{ type: 'picked-app:oauth-start', sessionToken, params }` to that window
|
|
469
|
+
only.
|
|
470
|
+
4. The window sends `POST /oauth/start`, with `Authorization: Bearer <sessionToken>` and
|
|
471
|
+
`params` as the JSON body.
|
|
472
|
+
5. `startAuthorization` verifies the session token and sets the OAuth cookie to a new
|
|
473
|
+
unique value. It answers `{ "url": "<authorization URL>" }`.
|
|
474
|
+
6. The window goes to the authorization URL. The service sends it back to the callback.
|
|
475
|
+
7. `finishAuthorization` compares the `nonce` in the `state` with the cookie. It then calls
|
|
476
|
+
`complete`, and answers with the callback page.
|
|
477
|
+
8. The callback page sends `picked-app:oauth-result` to the page that opened the window, and
|
|
478
|
+
closes.
|
|
479
|
+
|
|
480
|
+
Each message goes to the origin of the app only. The window and the page accept a message
|
|
481
|
+
only from that origin.
|
|
482
|
+
|
|
483
|
+
### `startAuthorization`
|
|
484
|
+
|
|
485
|
+
Answers each request to `OAUTH_START_PATH`.
|
|
486
|
+
|
|
487
|
+
| Request | Answer |
|
|
488
|
+
| ---------------- | ------------------------------------------------------------------------------------------------ |
|
|
489
|
+
| `GET` | The page of `oauthStartPage`. |
|
|
490
|
+
| `POST` | Calls `authorize`. For a URL, `200` with `{ "url": "<URL>" }` and the OAuth cookie. |
|
|
491
|
+
| `POST`, refused | The `Response` that `authorize` returns. It sets no cookie. |
|
|
492
|
+
| No session token | `401` with `{ "error": { "message": "Sign in again" } }`. The token is not valid, or is expired. |
|
|
493
|
+
| Other methods | `405` with `Allow: GET, POST`. |
|
|
494
|
+
|
|
495
|
+
The body of `POST` is the `params` of the page, as JSON. When the body is not JSON, `params`
|
|
496
|
+
is `null`.
|
|
497
|
+
|
|
498
|
+
| `StartAuthorizationOptions` | Type | Description |
|
|
499
|
+
| --------------------------- | ------------------------------------------------------------ | ---------------------------------------------------- |
|
|
500
|
+
| `privateKey` | `string` | The private key of the app. It encrypts the `state`. |
|
|
501
|
+
| `pickedKeys` | `PublicKeySet` | The public keys of Picked. They verify the session. |
|
|
502
|
+
| `authorize` | `(start: AuthorizationStart) => Promise<string \| Response>` | Returns the authorization URL, or an error answer. |
|
|
503
|
+
|
|
504
|
+
| `AuthorizationStart` | Type | Description |
|
|
505
|
+
| -------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------ |
|
|
506
|
+
| `session` | `SessionClaims` | The verified session of the person in the dashboard. |
|
|
507
|
+
| `sessionToken` | `string` | The session token. Give it to `installationClientFor` as `sessionToken`. |
|
|
508
|
+
| `params` | `unknown` | The `params` of `authorizeInPopup`, or `null`. |
|
|
509
|
+
| `state` | `(connection: string) => Promise<string>` | Returns the `state` parameter for the installation of the session, with this `connection`. |
|
|
510
|
+
|
|
511
|
+
An error answer goes to the page as the result. To give the person a message, answer
|
|
512
|
+
`{ "error": { "message": "<text>" } }`. Otherwise, the message is `The app answered <status>`.
|
|
513
|
+
|
|
514
|
+
### `finishAuthorization`
|
|
515
|
+
|
|
516
|
+
Answers the callback of the service. Serve it at the callback address of your OAuth client.
|
|
517
|
+
|
|
518
|
+
| `FinishAuthorizationOptions` | Type | Description |
|
|
519
|
+
| ---------------------------- | ------------------------------------------------------------------------ | --------------------------------------------- |
|
|
520
|
+
| `privateKey` | `string` | The private key of the app. |
|
|
521
|
+
| `complete` | `(callback: OAuthCallback) => Promise<{ ok: boolean; message: string }>` | Exchanges the code, and keeps the connection. |
|
|
522
|
+
|
|
523
|
+
| `OAuthCallback` | Type | Description |
|
|
524
|
+
| --------------- | ------------ | --------------------------------------------------------------------------- |
|
|
525
|
+
| `state` | `OAuthState` | The `state` that `startAuthorization` made. |
|
|
526
|
+
| `url` | `URL` | The address of the callback, with the `code` or the `error` of the service. |
|
|
527
|
+
|
|
528
|
+
`finishAuthorization` does not call `complete` in these conditions:
|
|
529
|
+
|
|
530
|
+
- The `state` is not set, is not from the app, has changes, or is expired.
|
|
531
|
+
- The request has no OAuth cookie, or the value of the cookie is not the `nonce` of the `state`.
|
|
532
|
+
|
|
533
|
+
Then the callback page shows `This connection link has expired or was opened in another browser; start again`.
|
|
534
|
+
The cookie stays. Otherwise, `finishAuthorization` deletes the cookie, so that the callback
|
|
535
|
+
completes one time. The callback page shows the `ok` and `message` of `complete`.
|
|
536
|
+
|
|
537
|
+
### State
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
interface OAuthState {
|
|
541
|
+
installationId: string
|
|
542
|
+
apiUrl: string
|
|
543
|
+
connection: string // which connection, for an app with more than one provider
|
|
544
|
+
sessionToken: string
|
|
545
|
+
exp: number // unix seconds
|
|
546
|
+
nonce: string
|
|
547
|
+
}
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
| Field | Value |
|
|
551
|
+
| ---------------- | -------------------------------------------------------------- |
|
|
552
|
+
| `installationId` | The installation of the session. |
|
|
553
|
+
| `apiUrl` | The Picked API of the installation. |
|
|
554
|
+
| `connection` | The value that `authorize` gives to `state`, for example `us`. |
|
|
555
|
+
| `sessionToken` | The session token of the person who started the flow. |
|
|
556
|
+
| `exp` | The time of expiry: 600 seconds after `startAuthorization`. |
|
|
557
|
+
| `nonce` | The value of the OAuth cookie that `startAuthorization` set. |
|
|
558
|
+
|
|
559
|
+
The `state` is encrypted with `AES-GCM`, with a key from the private key of the app. The
|
|
560
|
+
service cannot read or change it.
|
|
561
|
+
|
|
562
|
+
### OAuth cookie
|
|
563
|
+
|
|
564
|
+
| Origin of the app | Name | Attributes |
|
|
565
|
+
| ---------------------------------------------- | --------------------- | ---------------------------------------- |
|
|
566
|
+
| `http:` on `localhost`, `127.0.0.1` or `[::1]` | `picked-oauth-<port>` | `Path=/; HttpOnly; SameSite=Lax` |
|
|
567
|
+
| Other origins | `__Host-picked-oauth` | `Path=/; HttpOnly; SameSite=Lax; Secure` |
|
|
568
|
+
|
|
569
|
+
The origin of the app comes from the `Host` header of the request, and from the
|
|
570
|
+
`X-Forwarded-Proto` header that a proxy adds. Without these headers, it comes from the URL of
|
|
571
|
+
the request. For example, `serve` behind an `https:` proxy sets `__Host-picked-oauth`.
|
|
572
|
+
|
|
573
|
+
The cookie expires after 600 seconds. It is for the host of `/oauth/start` only, so the
|
|
574
|
+
callback must be on the same host. A browser holds one flow for each app at a time. A new
|
|
575
|
+
start replaces the cookie of an earlier flow, and the earlier flow then fails.
|
|
576
|
+
|
|
577
|
+
### Pages
|
|
578
|
+
|
|
579
|
+
| Function | Description |
|
|
580
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
581
|
+
| `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.` |
|
|
582
|
+
| `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.` |
|
|
583
|
+
|
|
584
|
+
`startAuthorization` and `finishAuthorization` send their pages with
|
|
585
|
+
`Content-Security-Policy: frame-ancestors 'none'`, `Cache-Control: no-store` and
|
|
586
|
+
`Referrer-Policy: no-referrer`.
|
|
587
|
+
|
|
588
|
+
## `@picked/app-kit/node`
|
|
589
|
+
|
|
590
|
+
```ts
|
|
591
|
+
serve(handler: (request: Request) => Promise<Response>, port: number): Server
|
|
592
|
+
frameScript(): Promise<Response>
|
|
593
|
+
```
|
|
594
|
+
|
|
595
|
+
| Function | Description |
|
|
596
|
+
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
597
|
+
| `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`. |
|
|
598
|
+
| `frameScript` | Answers with the browser build of `@picked/app-kit/frame`, as `text/javascript`. |
|
|
599
|
+
|
|
600
|
+
Serve `frameScript()` at a path of the app, for example `/app-kit/frame.js`. A page of the
|
|
601
|
+
app then imports `connect` from that path:
|
|
602
|
+
|
|
603
|
+
```ts
|
|
604
|
+
if (pathname === '/app-kit/frame.js') return frameScript()
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
## `@picked/app-kit/frame`
|
|
608
|
+
|
|
609
|
+
These functions run in a page that the dashboard shows in a slot. See
|
|
610
|
+
[Messages between the page and the dashboard](/reference/apps/protocol#messages-between-the-page-and-the-dashboard).
|
|
611
|
+
|
|
612
|
+
### `connect`
|
|
613
|
+
|
|
614
|
+
```ts
|
|
615
|
+
connect(options?: { dashboardOrigin?: string }): Promise<FrameContext>
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
Sends `picked:ready` to the dashboard. It returns the `FrameContext` that the dashboard
|
|
619
|
+
sends back. `connect` works only in a page that the dashboard shows in an `iframe`. In a page
|
|
620
|
+
that is not in an `iframe`, it returns an error.
|
|
621
|
+
|
|
622
|
+
It accepts a message only from the window that contains the `iframe` (`window.parent`), and
|
|
623
|
+
only from `dashboardOrigin`. Without `dashboardOrigin`, it uses the origin of
|
|
624
|
+
`document.referrer`, or the origin of the page when the referrer is empty. In the `iframe`,
|
|
625
|
+
the referrer is the dashboard, because [`page`](#responses) lets only the dashboard origins
|
|
626
|
+
show the page.
|
|
627
|
+
|
|
628
|
+
```ts
|
|
629
|
+
interface FrameContext {
|
|
630
|
+
installationId: string
|
|
631
|
+
organizationId: string
|
|
632
|
+
organizationSlug: string
|
|
633
|
+
projectId: string
|
|
634
|
+
location: 'app-home' | 'workspace-prepublish-actions' | 'workspace-postpublish-actions'
|
|
635
|
+
appVersion: number
|
|
636
|
+
sessionToken: string
|
|
637
|
+
theme: 'light' | 'dark'
|
|
638
|
+
}
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
```html
|
|
642
|
+
<script type="module">
|
|
643
|
+
import { connect, autoResize } from '/app-kit/frame.js'
|
|
644
|
+
const context = await connect()
|
|
645
|
+
autoResize()
|
|
646
|
+
const response = await fetch('/api/leads', {
|
|
647
|
+
headers: { authorization: 'Bearer ' + context.sessionToken },
|
|
648
|
+
})
|
|
649
|
+
</script>
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
### `resize` and `autoResize`
|
|
653
|
+
|
|
654
|
+
```ts
|
|
655
|
+
resize(height: number): void
|
|
656
|
+
autoResize(): () => void
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
| Function | Description |
|
|
660
|
+
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
661
|
+
| `resize` | Sends `picked:resize` with `height`, in pixels. It changes the value to the next integer above it. |
|
|
662
|
+
| `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. |
|
|
663
|
+
|
|
664
|
+
### `authorizeInPopup`
|
|
665
|
+
|
|
666
|
+
```ts
|
|
667
|
+
authorizeInPopup(request: { sessionToken: string; params?: unknown }): Promise<{ ok: boolean; message: string }>
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
Opens a new window at `/oauth/start` on the origin of the page. When the window sends
|
|
671
|
+
`picked-app:oauth-start-ready`, it sends the window `sessionToken` and `params`. It accepts
|
|
672
|
+
messages only from that window, and only from the origin of the page. `params` goes
|
|
673
|
+
to `authorize` on the server. See [Steps of the flow](#steps-of-the-flow). Call `authorizeInPopup` from a
|
|
674
|
+
`click` handler. A browser can stop a new window that the page opens at a different time.
|
|
675
|
+
|
|
676
|
+
| `request` | Description |
|
|
677
|
+
| -------------- | --------------------------------------------------------------------- |
|
|
678
|
+
| `sessionToken` | The session token from [`connect`](#connect). |
|
|
679
|
+
| `params` | A value for `authorize`, for example a region. The default is `null`. |
|
|
680
|
+
|
|
681
|
+
| Result | When |
|
|
682
|
+
| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
|
|
683
|
+
| `{ ok, message }` from the callback page | The callback page sends `picked-app:oauth-result`. |
|
|
684
|
+
| `{ ok: false, message: 'Allow pop-ups to connect' }` | The browser stops the new window. |
|
|
685
|
+
| `{ ok: false, message: <error message> }` | `POST /oauth/start` answers with an error, for example `Sign in again`. |
|
|
686
|
+
| `{ ok: false, message: 'The app answered <status>' }` | `POST /oauth/start` answers with an error that has no message, or with no URL. |
|
|
687
|
+
| `{ ok: false, message: 'The app could not start connecting' }` | The window cannot send `POST /oauth/start`, or cannot read its answer. |
|
|
688
|
+
| `{ 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. |
|
|
689
|
+
|
|
690
|
+
A service can separate the window from the page with a `Cross-Origin-Opener-Policy` header.
|
|
691
|
+
Then the page cannot see the window, and reads it as closed. The person can continue in the
|
|
692
|
+
window. The callback page stays open, and shows its result. `authorizeInPopup` waits until the
|
|
693
|
+
page is the active window again. Then it returns the result of a closed window. Read the connection from the server
|
|
694
|
+
after `authorizeInPopup` returns.
|
|
695
|
+
|
|
696
|
+
## `@picked/app-kit/testing`
|
|
697
|
+
|
|
698
|
+
### `createFakePicked`
|
|
699
|
+
|
|
700
|
+
```ts
|
|
701
|
+
createFakePicked(options: {
|
|
702
|
+
appPrivateKey: string
|
|
703
|
+
apiUrl?: string
|
|
704
|
+
offlineAccess?: boolean
|
|
705
|
+
}): Promise<FakePicked>
|
|
706
|
+
```
|
|
707
|
+
|
|
708
|
+
A Picked API for the tests of one app. Give its `fetch` to the installation client. It answers
|
|
709
|
+
the operations that the installation client sends: `appInstallationTokenCreate`, the labels
|
|
710
|
+
of an installation, `labelsSet` and `labelsDelete`. It also publishes its public keys at
|
|
711
|
+
`/.well-known/picked-app-keys.json`.
|
|
712
|
+
|
|
713
|
+
| Option | Default | Description |
|
|
714
|
+
| --------------- | ------------------------- | ---------------------------------------------------------------------------------------------- |
|
|
715
|
+
| `appPrivateKey` | required | The private key of the app. The test API accepts a `picked-app-assertion` from its public key. |
|
|
716
|
+
| `apiUrl` | `https://api.picked.test` | The origin of the test API. |
|
|
717
|
+
| `offlineAccess` | `false` | When `true`, each installation has `offlineAccess`. |
|
|
718
|
+
|
|
719
|
+
| `FakePicked` | Type | Description |
|
|
720
|
+
| ----------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
|
721
|
+
| `apiUrl` | `string` | The origin of the test API. |
|
|
722
|
+
| `fetch` | `typeof fetch` | The `fetch` function that sends requests to the test API. |
|
|
723
|
+
| `pickedKeys` | `PublicKeySet` | The public keys of the test API. Give them to `createAppHandler`. |
|
|
724
|
+
| `labels` | `Map<string, Map<string, AppLabel>>` | The labels, by installation ID, then by `<namespace>.<key>`. |
|
|
725
|
+
| `received` | `{ operationName: string; variables: Record<string, unknown> }[]` | Each GraphQL operation that the test API got, from first to last. |
|
|
726
|
+
| `tokenFor` | `(installationId) => Promise<{ token; expiresAt }>` | Makes an installation token. |
|
|
727
|
+
| `installationRef` | `(installationId, overrides?) => Promise<InstallationRef>` | An `InstallationRef` with a new token. The default organization is `org` and the default project is `proj_1`. |
|
|
728
|
+
| `signedRequest` | `(url, payload) => Promise<Request>` | A `POST` request that the test API signs, as Picked does. |
|
|
729
|
+
| `mcpRequest` | `(url, ref, payload) => Promise<Request>` | An MCP request that the test API signs, as Picked does. |
|
|
730
|
+
| `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`. |
|
|
731
|
+
|
|
732
|
+
### `toolCall`
|
|
733
|
+
|
|
734
|
+
```ts
|
|
735
|
+
toolCall(ref: InstallationRef, tool: string, args: Record<string, unknown>, test?: boolean): ToolCall
|
|
736
|
+
```
|
|
737
|
+
|
|
738
|
+
Makes a `ToolCall` body. With `test: true`, `run.test` is `true`.
|
|
739
|
+
|
|
740
|
+
```ts
|
|
741
|
+
import { generateKeyPair } from '@picked/app-kit'
|
|
742
|
+
import { createAppHandler } from '@picked/app-kit/server'
|
|
743
|
+
import { createFakePicked, toolCall } from '@picked/app-kit/testing'
|
|
744
|
+
|
|
745
|
+
const { privateKey } = await generateKeyPair()
|
|
746
|
+
const picked = await createFakePicked({ appPrivateKey: privateKey })
|
|
747
|
+
const handler = createAppHandler({
|
|
748
|
+
pickedKeys: picked.pickedKeys,
|
|
749
|
+
tools: { score_lead: async () => ({ score: 80, tier: 'hot' }) },
|
|
750
|
+
})
|
|
751
|
+
|
|
752
|
+
const ref = await picked.installationRef('appi_test')
|
|
753
|
+
const response = await handler(
|
|
754
|
+
await picked.signedRequest(
|
|
755
|
+
'https://app.test/tools/score_lead',
|
|
756
|
+
toolCall(ref, 'score_lead', { email: 'ada@example.com' }),
|
|
757
|
+
),
|
|
758
|
+
)
|
|
759
|
+
console.log(response.status, await response.json())
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
### `oauthCookie`
|
|
763
|
+
|
|
764
|
+
```ts
|
|
765
|
+
oauthCookie(response: Response): string
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
Returns the `<name>=<value>` of the cookie that a `POST /oauth/start` answer sets, or an
|
|
769
|
+
empty string. Give it as the `cookie` header of a callback request in a test.
|
|
770
|
+
|
|
771
|
+
In this example, `handler`, `picked` and `ref` are from the example of [`toolCall`](#toolcall).
|
|
772
|
+
The `fallback` of `handler` sends `/oauth/start` and `/oauth/callback` to the OAuth functions.
|
|
773
|
+
|
|
774
|
+
```ts
|
|
775
|
+
const started = await handler(
|
|
776
|
+
await picked.sessionRequest({
|
|
777
|
+
ref,
|
|
778
|
+
url: 'https://app.test/oauth/start',
|
|
779
|
+
method: 'POST',
|
|
780
|
+
body: { region: 'eu' },
|
|
781
|
+
}),
|
|
782
|
+
)
|
|
783
|
+
const { url } = await started.json()
|
|
784
|
+
const state = new URL(url).searchParams.get('state') ?? ''
|
|
785
|
+
const callback = await handler(
|
|
786
|
+
new Request(`https://app.test/oauth/callback?code=abc&state=${state}`, {
|
|
787
|
+
headers: { cookie: oauthCookie(started) },
|
|
788
|
+
}),
|
|
789
|
+
)
|
|
790
|
+
```
|
|
791
|
+
|
|
792
|
+
## `app-kit-copy-frame`
|
|
793
|
+
|
|
794
|
+
```sh
|
|
795
|
+
app-kit-copy-frame <dir>
|
|
796
|
+
```
|
|
797
|
+
|
|
798
|
+
Copies the browser build of `@picked/app-kit/frame` to `<dir>/app-kit/frame.js`. Use it on a
|
|
799
|
+
host that serves static files, for example the `public` directory of a Vercel project.
|
|
800
|
+
Without `<dir>`, it writes `Usage: app-kit-copy-frame <dir>` and stops with status `1`.
|
|
801
|
+
|
|
802
|
+
## Related
|
|
803
|
+
|
|
804
|
+
- [App protocol](/reference/apps/protocol) — the requests and the messages that this
|
|
805
|
+
package implements.
|
|
806
|
+
- [App manifest](/reference/apps/manifest) — the fields of `AppManifest`.
|
|
807
|
+
- [App environment variables](/reference/apps/environment) — the variables of
|
|
808
|
+
`readAppEnvironment`.
|
|
809
|
+
- [How to test an app](/how-to/apps/test-an-app)
|
|
810
|
+
- [How to store data for an installation](/how-to/apps/store-data-for-an-installation)
|
|
811
|
+
- [How to connect an external service with OAuth](/how-to/apps/connect-a-third-party-service-with-oauth)
|