apps 1.0.0-beta.3 → 2.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -48
- package/check-publish.mjs +7 -0
- package/package.json +27 -56
- package/src/Access.ts +37 -0
- package/src/Accounts.ts +468 -0
- package/src/App.ts +11 -0
- package/src/Ask.ts +156 -0
- package/src/Changes.ts +13 -0
- package/src/Http.ts +30 -0
- package/src/Provider.ts +146 -0
- package/src/Session.ts +52 -0
- package/src/Settings.ts +164 -0
- package/src/contract.ts +852 -0
- package/src/css-modules.d.ts +2 -0
- package/src/desktop/Desktop.ts +192 -0
- package/src/desktop/bridge.ts +62 -0
- package/src/desktop/errors.ts +88 -0
- package/src/desktop/index.ts +15 -0
- package/src/entry.ts +48 -0
- package/src/index.ts +16 -4
- package/src/internal/defects.ts +62 -0
- package/src/internal/files.ts +369 -0
- package/src/internal/host.ts +17 -0
- package/src/internal/query.ts +114 -0
- package/src/internal/records.ts +838 -0
- package/src/internal/retention.ts +87 -0
- package/src/internal/retries.ts +185 -0
- package/src/internal/telemetry.ts +167 -0
- package/src/migrations.ts +110 -0
- package/src/page/Accounts.ts +27 -0
- package/src/page/Changes.ts +126 -0
- package/src/page/Session.ts +46 -0
- package/src/page/client.ts +107 -0
- package/src/page/errors.ts +15 -0
- package/src/page/http.ts +21 -0
- package/src/page/index.ts +18 -0
- package/src/page/paths.ts +22 -0
- package/src/providers/anthropic.ts +26 -0
- package/src/providers/github.ts +49 -0
- package/src/providers/google.ts +67 -0
- package/src/providers/openai.ts +62 -0
- package/src/providers/slack.ts +81 -0
- package/src/runtime.ts +1540 -0
- package/src/testing.ts +660 -0
- package/src/text-modules.d.ts +5 -0
- package/src/theme.css +50 -0
- package/dist/authoring/index.d.ts +0 -393
- package/dist/authoring/index.js +0 -36
- package/dist/chunk-4OZFMCTT.js +0 -17
- package/dist/chunk-A3H32P2J.js +0 -143
- package/dist/chunk-B7NEUIJL.js +0 -14
- package/dist/chunk-F7GZYEAC.js +0 -41
- package/dist/chunk-MUFMJRXR.js +0 -308
- package/dist/chunk-S5KFP4JQ.js +0 -20
- package/dist/chunk-Y6LLTN7W.js +0 -99
- package/dist/chunk-YUZ4TXOY.js +0 -27
- package/dist/http/index.d.ts +0 -9
- package/dist/http/index.js +0 -6
- package/dist/index.d.ts +0 -4
- package/dist/index.js +0 -48
- package/dist/manifest/contract.d.ts +0 -63
- package/dist/manifest/contract.js +0 -8
- package/dist/manifest/index.d.ts +0 -20
- package/dist/manifest/index.js +0 -16
- package/dist/mcp/client.d.ts +0 -9
- package/dist/mcp/index.d.ts +0 -11
- package/dist/mcp/index.js +0 -7
- package/dist/openapi/index.d.ts +0 -14
- package/dist/openapi/index.js +0 -7
- package/dist/openapi/mapper.d.ts +0 -7
- package/dist/runner/index.d.ts +0 -4
- package/dist/runner/index.js +0 -66
- package/dist/runner/protocol.d.ts +0 -33
- package/dist/runner/protocol.js +0 -8
- package/dist/runtime/index.d.ts +0 -83
- package/dist/runtime/index.js +0 -12
- package/dist/workerd/index.d.ts +0 -7
- package/dist/workerd/index.js +0 -10
- package/src/authoring/index.ts +0 -658
- package/src/http/index.ts +0 -26
- package/src/manifest/contract.ts +0 -64
- package/src/manifest/index.ts +0 -156
- package/src/mcp/client.ts +0 -59
- package/src/mcp/index.ts +0 -42
- package/src/openapi/index.ts +0 -70
- package/src/openapi/mapper.ts +0 -25
- package/src/runner/index.ts +0 -80
- package/src/runner/protocol.ts +0 -54
- package/src/runtime/index.ts +0 -550
- package/src/workerd/index.ts +0 -17
package/README.md
CHANGED
|
@@ -1,54 +1,16 @@
|
|
|
1
|
-
# apps
|
|
1
|
+
# apps (2, prerelease)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
validates, and serves them; credentials never enter your handler — each
|
|
6
|
-
requirement arrives as a capability that spends them for you.
|
|
3
|
+
The framework for Executor's new-format apps, written with Effect: tools, routes,
|
|
4
|
+
a page, workflows, scheduled jobs, settings and accounts.
|
|
7
5
|
|
|
8
|
-
|
|
6
|
+
This prerelease is published under the `next` tag only. Install the exact
|
|
7
|
+
version your Executor host runs:
|
|
9
8
|
|
|
10
|
-
```
|
|
11
|
-
|
|
12
|
-
import { defineApp, secrets, service } from "apps";
|
|
13
|
-
|
|
14
|
-
export const github = service({
|
|
15
|
-
origin: "api.github.com",
|
|
16
|
-
label: "GitHub",
|
|
17
|
-
auth: {
|
|
18
|
-
pat: secrets({
|
|
19
|
-
label: "Personal access token",
|
|
20
|
-
help: "Create a fine-grained token at github.com/settings/tokens.",
|
|
21
|
-
fields: { token: { label: "Token", secret: true } },
|
|
22
|
-
}),
|
|
23
|
-
},
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
export default defineApp({
|
|
27
|
-
key: "github",
|
|
28
|
-
label: "GitHub",
|
|
29
|
-
description: "Repositories, issues, and pull requests.",
|
|
30
|
-
});
|
|
9
|
+
```sh
|
|
10
|
+
npm install --save-exact apps@2.0.0-next.0 effect@4.1.6
|
|
31
11
|
```
|
|
32
12
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
import { defineTool } from "apps";
|
|
36
|
-
import { z } from "zod";
|
|
37
|
-
import { github } from "../app";
|
|
38
|
-
|
|
39
|
-
export default defineTool({
|
|
40
|
-
description: "Fetch a repository",
|
|
41
|
-
input: z.object({ owner: z.string(), repo: z.string() }),
|
|
42
|
-
requirements: { gh: github },
|
|
43
|
-
handler: async ({ owner, repo }, ctx) => {
|
|
44
|
-
const response = await ctx.gh.fetch(`/repos/${owner}/${repo}`);
|
|
45
|
-
return response.json();
|
|
46
|
-
},
|
|
47
|
-
});
|
|
48
|
-
```
|
|
13
|
+
Do not install `apps@latest`: that tag is an unrelated, earlier package. The
|
|
14
|
+
`beta` tag is today's app format.
|
|
49
15
|
|
|
50
|
-
The
|
|
51
|
-
builtins — so authored files run unmodified anywhere, including sandboxed
|
|
52
|
-
workers. `apps/runtime` is the single execution core every environment
|
|
53
|
-
shares; host machinery lives behind `apps/manifest` and `apps/runner` and
|
|
54
|
-
requires `effect`.
|
|
16
|
+
The authoring guide is the `app-authoring` skill that Executor serves to agents.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
|
|
3
|
+
const manifest = JSON.parse(await readFile(new URL("./package.json", import.meta.url), "utf8"));
|
|
4
|
+
const tag = process.env.npm_config_tag ?? manifest.publishConfig?.tag;
|
|
5
|
+
if (!/^2\.\d+\.\d+-next\.\d+$/u.test(manifest.version) || tag !== "next") {
|
|
6
|
+
throw new Error("Publish apps 2 as 2.x.y-next.N with --tag next only: never latest, never beta.");
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,72 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "apps",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Author
|
|
3
|
+
"version": "2.0.0-next.0",
|
|
4
|
+
"description": "Author Executor apps with Effect: tools, pages, workflows, jobs and accounts.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
"
|
|
10
|
-
"
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.ts",
|
|
9
|
+
"./contract": "./src/contract.ts",
|
|
10
|
+
"./runtime": "./src/runtime.ts",
|
|
11
|
+
"./providers/*": "./src/providers/*.ts",
|
|
12
|
+
"./entry": "./src/entry.ts",
|
|
13
|
+
"./page": "./src/page/index.ts",
|
|
14
|
+
"./desktop": "./src/desktop/index.ts",
|
|
15
|
+
"./theme.css": "./src/theme.css",
|
|
16
|
+
"./testing": "./src/testing.ts",
|
|
17
|
+
"./package.json": "./package.json"
|
|
11
18
|
},
|
|
12
|
-
"sideEffects": false,
|
|
13
19
|
"files": [
|
|
14
|
-
"dist",
|
|
15
20
|
"src",
|
|
21
|
+
"check-publish.mjs",
|
|
16
22
|
"README.md"
|
|
17
23
|
],
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"types": "./dist/index.d.ts",
|
|
21
|
-
"default": "./dist/index.js"
|
|
22
|
-
},
|
|
23
|
-
"./authoring": {
|
|
24
|
-
"types": "./dist/authoring/index.d.ts",
|
|
25
|
-
"default": "./dist/authoring/index.js"
|
|
26
|
-
},
|
|
27
|
-
"./runtime": {
|
|
28
|
-
"types": "./dist/runtime/index.d.ts",
|
|
29
|
-
"default": "./dist/runtime/index.js"
|
|
30
|
-
},
|
|
31
|
-
"./manifest": {
|
|
32
|
-
"types": "./dist/manifest/index.d.ts",
|
|
33
|
-
"default": "./dist/manifest/index.js"
|
|
34
|
-
},
|
|
35
|
-
"./manifest/contract": {
|
|
36
|
-
"types": "./dist/manifest/contract.d.ts",
|
|
37
|
-
"default": "./dist/manifest/contract.js"
|
|
38
|
-
},
|
|
39
|
-
"./runner": {
|
|
40
|
-
"types": "./dist/runner/index.d.ts",
|
|
41
|
-
"default": "./dist/runner/index.js"
|
|
42
|
-
},
|
|
43
|
-
"./runner/protocol": {
|
|
44
|
-
"types": "./dist/runner/protocol.d.ts",
|
|
45
|
-
"default": "./dist/runner/protocol.js"
|
|
46
|
-
},
|
|
47
|
-
"./mcp": {
|
|
48
|
-
"types": "./dist/mcp/index.d.ts",
|
|
49
|
-
"default": "./dist/mcp/index.js"
|
|
50
|
-
},
|
|
51
|
-
"./openapi": {
|
|
52
|
-
"types": "./dist/openapi/index.d.ts",
|
|
53
|
-
"default": "./dist/openapi/index.js"
|
|
54
|
-
},
|
|
55
|
-
"./http": {
|
|
56
|
-
"types": "./dist/http/index.d.ts",
|
|
57
|
-
"default": "./dist/http/index.js"
|
|
58
|
-
},
|
|
59
|
-
"./workerd": {
|
|
60
|
-
"types": "./dist/workerd/index.d.ts",
|
|
61
|
-
"default": "./dist/workerd/index.js"
|
|
62
|
-
}
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@effect/sql-sqlite-do": "4.1.6"
|
|
63
26
|
},
|
|
64
27
|
"peerDependencies": {
|
|
65
|
-
"effect": "4.
|
|
28
|
+
"@effect/sql-sqlite-node": "4.1.6",
|
|
29
|
+
"effect": "4.1.6"
|
|
66
30
|
},
|
|
67
31
|
"peerDependenciesMeta": {
|
|
68
|
-
"effect": {
|
|
69
|
-
"optional":
|
|
32
|
+
"@effect/sql-sqlite-node": {
|
|
33
|
+
"optional": true
|
|
70
34
|
}
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public",
|
|
38
|
+
"tag": "next"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"prepublishOnly": "node check-publish.mjs"
|
|
71
42
|
}
|
|
72
43
|
}
|
package/src/Access.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may reach the app's routes. By default only signed-in members of the
|
|
3
|
+
* organization reach the app; Executor refuses anyone else before the app
|
|
4
|
+
* wakes. A path declared public is reachable by anyone (an inbound webhook, a
|
|
5
|
+
* public page). The name `Access` is provisional.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* export const access = Access.declare({ public: ["/webhooks/gmail"] })
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* A pattern is an exact path, or a prefix ending in `/*`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export interface AccessDeclaration {
|
|
15
|
+
readonly public: ReadonlyArray<string>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Every declaration in this bundle, for `describe()`. */
|
|
19
|
+
export const declarations: { readonly public: Array<string> } = { public: [] };
|
|
20
|
+
|
|
21
|
+
export const declare = (spec: { readonly public?: ReadonlyArray<string> }): AccessDeclaration => {
|
|
22
|
+
for (const path of spec.public ?? []) {
|
|
23
|
+
if (!path.startsWith("/")) throw new Error(`Access.declare: "${path}" must start with "/"`);
|
|
24
|
+
if (path.includes("*") && !path.endsWith("/*"))
|
|
25
|
+
throw new Error(`Access.declare: "${path}" may only end in "/*"`);
|
|
26
|
+
if (!declarations.public.includes(path)) declarations.public.push(path);
|
|
27
|
+
}
|
|
28
|
+
return { public: [...(spec.public ?? [])] };
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Whether `pathname` matches one of `patterns`. The host uses the same rule. */
|
|
32
|
+
export const isPublic = (patterns: ReadonlyArray<string>, pathname: string): boolean =>
|
|
33
|
+
patterns.some((pattern) =>
|
|
34
|
+
pattern.endsWith("/*")
|
|
35
|
+
? pathname === pattern.slice(0, -2) || pathname.startsWith(pattern.slice(0, -1))
|
|
36
|
+
: pathname === pattern,
|
|
37
|
+
);
|
package/src/Accounts.ts
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Linked accounts. Executor is a broker: it stores the grant, refreshes it and
|
|
3
|
+
* hands the app a fresh, real token. Whose account is always said explicitly.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* export const accounts = Accounts.declare({
|
|
7
|
+
* user: { github: GitHub }, // each member links their own
|
|
8
|
+
* app: { slack: Slack }, // an admin links one for everyone
|
|
9
|
+
* })
|
|
10
|
+
*
|
|
11
|
+
* const { user } = yield* Session.current
|
|
12
|
+
* const github = yield* accounts.user.github.of(user.id)
|
|
13
|
+
* const token = yield* github.accessToken // Redacted: does not print in logs
|
|
14
|
+
* const repos = yield* github.http.get("https://api.github.com/user/repos") // token attached, a 401 retried once
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* The token is the base; `http` is a convenience that attaches it and, on a
|
|
18
|
+
* 401, reports the rejected token (Executor renews it) and retries once. For a
|
|
19
|
+
* command-line tool or a socket, use `accessToken` and call `reportRejected`
|
|
20
|
+
* when the service refuses it.
|
|
21
|
+
*/
|
|
22
|
+
import { Duration, Effect, Option, Redacted, Schema, Stream } from "effect";
|
|
23
|
+
import { HttpClient, HttpClientError, HttpClientRequest, HttpServerRequest } from "effect/http";
|
|
24
|
+
import { CALL_HEADER } from "./contract.ts";
|
|
25
|
+
import type {
|
|
26
|
+
AccountCredential,
|
|
27
|
+
AccountDeclaration,
|
|
28
|
+
AccountEvent,
|
|
29
|
+
AccountOwner,
|
|
30
|
+
AccountProfile,
|
|
31
|
+
AccountRef,
|
|
32
|
+
ContractError,
|
|
33
|
+
HostCapabilities,
|
|
34
|
+
} from "./contract.ts";
|
|
35
|
+
import { Host } from "./internal/host.ts";
|
|
36
|
+
import type { Provider } from "./Provider.ts";
|
|
37
|
+
import * as Session from "./Session.ts";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The owner has not linked this account to the app. `url` is the page where
|
|
41
|
+
* they link it: an agent shows it to the person.
|
|
42
|
+
*/
|
|
43
|
+
export class NotLinked extends Schema.TaggedError<NotLinked>()("NotLinked", {
|
|
44
|
+
account: Schema.String,
|
|
45
|
+
owner: Schema.String,
|
|
46
|
+
url: Schema.optionalKey(Schema.String),
|
|
47
|
+
message: Schema.String,
|
|
48
|
+
}) {}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The account's credential no longer works (the provider refused a renewed
|
|
52
|
+
* token, or the person revoked access). `url` is where they reconnect it.
|
|
53
|
+
*/
|
|
54
|
+
export class NeedsReconnection extends Schema.TaggedError<NeedsReconnection>()(
|
|
55
|
+
"NeedsReconnection",
|
|
56
|
+
{
|
|
57
|
+
account: Schema.String,
|
|
58
|
+
owner: Schema.String,
|
|
59
|
+
url: Schema.optionalKey(Schema.String),
|
|
60
|
+
message: Schema.String,
|
|
61
|
+
},
|
|
62
|
+
) {}
|
|
63
|
+
|
|
64
|
+
/** Executor could not answer: not running under Executor, or a host failure. */
|
|
65
|
+
export class AccountUnavailable extends Schema.TaggedError<AccountUnavailable>()(
|
|
66
|
+
"AccountUnavailable",
|
|
67
|
+
{
|
|
68
|
+
account: Schema.String,
|
|
69
|
+
message: Schema.String,
|
|
70
|
+
},
|
|
71
|
+
) {}
|
|
72
|
+
|
|
73
|
+
export type AccountError = NotLinked | NeedsReconnection | AccountUnavailable;
|
|
74
|
+
|
|
75
|
+
/** The account's credential: the token, and every value it holds (several for a multi-field API key). */
|
|
76
|
+
export interface Credential {
|
|
77
|
+
readonly token: Redacted.Redacted<string>;
|
|
78
|
+
readonly fields: Readonly<Record<string, Redacted.Redacted<string>>>;
|
|
79
|
+
/** Epoch milliseconds, when known. */
|
|
80
|
+
readonly expiresAt: number | null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface Account {
|
|
84
|
+
readonly name: string;
|
|
85
|
+
readonly owner: AccountOwner;
|
|
86
|
+
/** The member who owns it, for a `user` account. */
|
|
87
|
+
readonly userId: string | undefined;
|
|
88
|
+
/** The account's name in Executor ("Work"), where known: `.all` knows it, `.of` does not. */
|
|
89
|
+
readonly label: string | undefined;
|
|
90
|
+
/** A fresh token. */
|
|
91
|
+
readonly accessToken: Effect.Effect<Redacted.Redacted<string>, AccountError>;
|
|
92
|
+
/** A fresh credential, with every field. */
|
|
93
|
+
readonly credential: Effect.Effect<Credential, AccountError>;
|
|
94
|
+
/** Effect's `HttpClient` with the token attached. On a 401 it reports the token and retries once. */
|
|
95
|
+
readonly http: HttpClient.HttpClient.With<HttpClientError.HttpClientError | AccountError>;
|
|
96
|
+
/** For non-HTTP uses (a CLI, a socket): tell Executor the provider rejected this token. */
|
|
97
|
+
readonly reportRejected: (
|
|
98
|
+
token: Redacted.Redacted<string>,
|
|
99
|
+
) => Effect.Effect<void, AccountUnavailable>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface UserAccount {
|
|
103
|
+
/** The account of the member with this id. */
|
|
104
|
+
readonly of: (userId: string) => Effect.Effect<Account, never, HttpClient.HttpClient>;
|
|
105
|
+
/** The current caller's account. */
|
|
106
|
+
readonly mine: Effect.Effect<Account, Session.NoSession, HttpClient.HttpClient>;
|
|
107
|
+
/** Every member who has linked it. */
|
|
108
|
+
readonly all: Stream.Stream<Account, AccountUnavailable, HttpClient.HttpClient>;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export type AppAccount = Effect.Effect<Account, never, HttpClient.HttpClient>;
|
|
112
|
+
|
|
113
|
+
export interface Declared<U extends Record<string, Provider>, A extends Record<string, Provider>> {
|
|
114
|
+
readonly user: { readonly [K in keyof U]: UserAccount };
|
|
115
|
+
readonly app: { readonly [K in keyof A]: AppAccount };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Every declaration in this bundle, for `describe()`. */
|
|
119
|
+
export const declarations: Array<AccountDeclaration> = [];
|
|
120
|
+
|
|
121
|
+
const ownerLabel = (owner: AccountOwner) => (owner.kind === "app" ? "app" : `user:${owner.userId}`);
|
|
122
|
+
|
|
123
|
+
const capabilities = (name: string): Effect.Effect<HostCapabilities, AccountUnavailable> =>
|
|
124
|
+
Effect.flatMap(Effect.service(Host), (host) =>
|
|
125
|
+
host.capabilities === undefined
|
|
126
|
+
? Effect.fail(
|
|
127
|
+
new AccountUnavailable({ account: name, message: "Not running under Executor" }),
|
|
128
|
+
)
|
|
129
|
+
: Effect.succeed(host.capabilities),
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
const call = <A>(name: string, f: (host: HostCapabilities) => Promise<A>) =>
|
|
133
|
+
Effect.flatMap(capabilities(name), (host) =>
|
|
134
|
+
Effect.tryPromise({
|
|
135
|
+
try: () => f(host),
|
|
136
|
+
catch: (cause) => new AccountUnavailable({ account: name, message: String(cause) }),
|
|
137
|
+
}),
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
const fromError = (ref: AccountRef, error: ContractError): AccountError => {
|
|
141
|
+
const fields = {
|
|
142
|
+
account: ref.name,
|
|
143
|
+
owner: ownerLabel(ref.owner),
|
|
144
|
+
message: error.message,
|
|
145
|
+
...(error.url === undefined ? {} : { url: error.url }),
|
|
146
|
+
};
|
|
147
|
+
return error.reason === "NotLinked"
|
|
148
|
+
? new NotLinked(fields)
|
|
149
|
+
: error.reason === "NeedsReconnection"
|
|
150
|
+
? new NeedsReconnection(fields)
|
|
151
|
+
: new AccountUnavailable({ account: ref.name, message: error.message });
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** The user the app is acting for: the caller of the current request, if any. */
|
|
155
|
+
const invocation = Effect.map(
|
|
156
|
+
Effect.serviceOption(HttpServerRequest.HttpServerRequest),
|
|
157
|
+
Option.match({
|
|
158
|
+
onNone: () => null,
|
|
159
|
+
onSome: (request) => {
|
|
160
|
+
const header = request.headers[CALL_HEADER];
|
|
161
|
+
if (header === undefined) return null;
|
|
162
|
+
try {
|
|
163
|
+
const parsed = JSON.parse(header) as { readonly invocation?: unknown };
|
|
164
|
+
return typeof parsed.invocation === "string" ? parsed.invocation : null;
|
|
165
|
+
} catch {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
}),
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
const caller = Effect.map(
|
|
173
|
+
Effect.option(Session.current),
|
|
174
|
+
Option.match({
|
|
175
|
+
onNone: () => null,
|
|
176
|
+
onSome: (session) => session.user.id,
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
const redacted = (credential: AccountCredential): Credential => ({
|
|
181
|
+
token: Redacted.make(credential.token),
|
|
182
|
+
fields: Object.fromEntries(
|
|
183
|
+
Object.entries(credential.fields).map(([key, value]) => [key, Redacted.make(value)]),
|
|
184
|
+
),
|
|
185
|
+
expiresAt: credential.expiresAt,
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
const declaredHosts = (name: string): ReadonlyArray<string> =>
|
|
189
|
+
declarations.find((declaration) => declaration.name === name)?.provider.hosts ?? [];
|
|
190
|
+
|
|
191
|
+
const hostMatches = (pattern: string, url: URL) => {
|
|
192
|
+
const separator = pattern.lastIndexOf(":");
|
|
193
|
+
const [host, port] =
|
|
194
|
+
separator > 0 && /^\d+$/u.test(pattern.slice(separator + 1))
|
|
195
|
+
? [pattern.slice(0, separator), pattern.slice(separator + 1)]
|
|
196
|
+
: [pattern, ""];
|
|
197
|
+
if (port !== url.port) return false;
|
|
198
|
+
const hostname = url.hostname.toLowerCase();
|
|
199
|
+
if (!host.startsWith("*.")) return hostname === host.toLowerCase();
|
|
200
|
+
const domain = host.slice(2).toLowerCase();
|
|
201
|
+
if (!hostname.endsWith(`.${domain}`)) return false;
|
|
202
|
+
const label = hostname.slice(0, -(domain.length + 1));
|
|
203
|
+
return label.length > 0 && !label.includes(".");
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
const onDeclaredHost = (name: string, url: URL) =>
|
|
207
|
+
declaredHosts(name).some((pattern) => hostMatches(pattern, url));
|
|
208
|
+
|
|
209
|
+
const makeAccount = (
|
|
210
|
+
ref: AccountRef,
|
|
211
|
+
label?: string,
|
|
212
|
+
): Effect.Effect<Account, never, HttpClient.HttpClient> =>
|
|
213
|
+
Effect.map(Effect.service(HttpClient.HttpClient), (base) => {
|
|
214
|
+
const credential: Effect.Effect<Credential, AccountError> = Effect.gen(function* () {
|
|
215
|
+
const use = { caller: yield* caller, invocation: yield* invocation };
|
|
216
|
+
const result = yield* call(ref.name, (host) => host.accounts.token(ref, use));
|
|
217
|
+
return result.ok ? redacted(result.value) : yield* Effect.fail(fromError(ref, result.error));
|
|
218
|
+
});
|
|
219
|
+
const accessToken = Effect.map(credential, (value) => value.token);
|
|
220
|
+
const reported = (token: Redacted.Redacted<string>) =>
|
|
221
|
+
Effect.flatMap(
|
|
222
|
+
call(ref.name, (host) => host.accounts.rejected(ref, Redacted.value(token))),
|
|
223
|
+
(result) =>
|
|
224
|
+
result.ok
|
|
225
|
+
? Effect.succeed(result.value.renewed)
|
|
226
|
+
: Effect.fail(
|
|
227
|
+
new AccountUnavailable({ account: ref.name, message: result.error.message }),
|
|
228
|
+
),
|
|
229
|
+
);
|
|
230
|
+
const http = HttpClient.transform(base, (_, request) =>
|
|
231
|
+
Effect.gen(function* () {
|
|
232
|
+
const url = new URL(request.url);
|
|
233
|
+
if (!onDeclaredHost(ref.name, url)) {
|
|
234
|
+
return yield* Effect.fail(
|
|
235
|
+
new AccountUnavailable({
|
|
236
|
+
account: ref.name,
|
|
237
|
+
message:
|
|
238
|
+
`${url.host} is not one of the hosts ${ref.name}'s provider declares, so account.http does not send its token there. ` +
|
|
239
|
+
"Add the host to the provider's hosts, or use account.accessToken with a client of your own.",
|
|
240
|
+
}),
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const token = yield* accessToken;
|
|
244
|
+
const response = yield* base.execute(HttpClientRequest.bearerToken(request, token));
|
|
245
|
+
if (response.status !== 401) return response;
|
|
246
|
+
yield* reported(token);
|
|
247
|
+
const fresh = yield* accessToken;
|
|
248
|
+
const retried = yield* base.execute(HttpClientRequest.bearerToken(request, fresh));
|
|
249
|
+
if (retried.status !== 401) return retried;
|
|
250
|
+
yield* reported(fresh);
|
|
251
|
+
yield* accessToken;
|
|
252
|
+
return retried;
|
|
253
|
+
}),
|
|
254
|
+
);
|
|
255
|
+
return {
|
|
256
|
+
name: ref.name,
|
|
257
|
+
owner: ref.owner,
|
|
258
|
+
userId: ref.owner.kind === "user" ? ref.owner.userId : undefined,
|
|
259
|
+
label,
|
|
260
|
+
accessToken,
|
|
261
|
+
credential,
|
|
262
|
+
http,
|
|
263
|
+
reportRejected: (token) => Effect.asVoid(reported(token)),
|
|
264
|
+
} satisfies Account;
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
const userAccount = (name: string): UserAccount => {
|
|
268
|
+
const of = (userId: string) => makeAccount({ name, owner: { kind: "user", userId } });
|
|
269
|
+
return {
|
|
270
|
+
of,
|
|
271
|
+
mine: Effect.flatMap(Session.current, (session) => of(session.user.id)),
|
|
272
|
+
all: Stream.unwrap(
|
|
273
|
+
Effect.flatMap(
|
|
274
|
+
call(name, (host) => host.accounts.owners(name)),
|
|
275
|
+
(result) =>
|
|
276
|
+
result.ok
|
|
277
|
+
? Effect.succeed(
|
|
278
|
+
Stream.mapEffect(Stream.fromIterable(result.value), (entry) =>
|
|
279
|
+
makeAccount({ name, owner: entry.owner }, entry.label),
|
|
280
|
+
),
|
|
281
|
+
)
|
|
282
|
+
: Effect.fail(new AccountUnavailable({ account: name, message: result.error.message })),
|
|
283
|
+
),
|
|
284
|
+
),
|
|
285
|
+
};
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
/** Declare the accounts the app uses: `user` accounts each member links, `app` accounts an admin links once. */
|
|
289
|
+
export const declare = <
|
|
290
|
+
const U extends Record<string, Provider> = {},
|
|
291
|
+
const A extends Record<string, Provider> = {},
|
|
292
|
+
>(spec: {
|
|
293
|
+
readonly user?: U;
|
|
294
|
+
readonly app?: A;
|
|
295
|
+
}): Declared<U, A> => {
|
|
296
|
+
const user: Record<string, UserAccount> = {};
|
|
297
|
+
const app: Record<string, AppAccount> = {};
|
|
298
|
+
for (const [name, provider] of Object.entries(spec.user ?? {})) {
|
|
299
|
+
declarations.push({ name, owner: "user", provider: provider.description });
|
|
300
|
+
user[name] = userAccount(name);
|
|
301
|
+
}
|
|
302
|
+
for (const [name, provider] of Object.entries(spec.app ?? {})) {
|
|
303
|
+
declarations.push({ name, owner: "app", provider: provider.description });
|
|
304
|
+
app[name] = makeAccount({ name, owner: { kind: "app" } });
|
|
305
|
+
}
|
|
306
|
+
return { user, app } as Declared<U, A>;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/** The account a hook runs for. Its token works in both hooks. */
|
|
310
|
+
export interface Linked extends Account {
|
|
311
|
+
/** The account's id at the provider, when its profile says (e.g. a Slack team id). */
|
|
312
|
+
readonly externalId: string | null;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export interface HookEvent {
|
|
316
|
+
/** Stable for one delivery, so a retried delivery can be recognised. */
|
|
317
|
+
readonly id: string;
|
|
318
|
+
/**
|
|
319
|
+
* Why it runs. `link`/`unlink`: a person linked or unlinked the account. `deploy`: a new version
|
|
320
|
+
* was activated and every linked account is offered to the link hook again, so a hook added later
|
|
321
|
+
* runs for accounts linked before it existed. `removed`: the account, or the app itself, is being removed from Executor.
|
|
322
|
+
*/
|
|
323
|
+
readonly cause: AccountEvent["cause"];
|
|
324
|
+
readonly account: Linked;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export interface HookHandlers<R> {
|
|
328
|
+
/** After an account is linked to the app. */
|
|
329
|
+
readonly onLink?: (event: HookEvent) => Effect.Effect<void, unknown, R>;
|
|
330
|
+
/** Before an account is unlinked, while its token still works. */
|
|
331
|
+
readonly onUnlink?: (event: HookEvent) => Effect.Effect<void, unknown, R>;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Hooks on linking and unlinking, e.g. to register a webhook at the provider
|
|
336
|
+
* and remove it again. The link hook runs more than once for the same account:
|
|
337
|
+
* after every deploy (`cause: "deploy"`), and again when a delivery is retried
|
|
338
|
+
* after a failure (same `id`). Make it safe to repeat: check what is already
|
|
339
|
+
* registered before registering. An `onUnlink` that fails or takes longer than
|
|
340
|
+
* about 30 seconds does not stop the unlink; the failure is shown on the app's
|
|
341
|
+
* page. A failing `onLink` is retried a few times, then shown there too.
|
|
342
|
+
*
|
|
343
|
+
* Unlinking stops Executor handing out new tokens for the account. A token
|
|
344
|
+
* already handed to the app stays usable until the provider expires it:
|
|
345
|
+
* unlinking does not revoke it at the provider.
|
|
346
|
+
*/
|
|
347
|
+
export const hooks = <R>(
|
|
348
|
+
_accounts: Declared<Record<string, Provider>, Record<string, Provider>>,
|
|
349
|
+
handlers: HookHandlers<R>,
|
|
350
|
+
): HookHandlers<R> => {
|
|
351
|
+
registered.push(handlers as HookHandlers<unknown>);
|
|
352
|
+
return handlers;
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
const registered: Array<HookHandlers<unknown>> = [];
|
|
356
|
+
|
|
357
|
+
/** How many link and unlink hooks this bundle registered, for `describe()`. */
|
|
358
|
+
export const hookCounts = (): { readonly onLink: number; readonly onUnlink: number } => ({
|
|
359
|
+
onLink: registered.filter((handlers) => handlers.onLink !== undefined).length,
|
|
360
|
+
onUnlink: registered.filter((handlers) => handlers.onUnlink !== undefined).length,
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
const PROFILE_HEADERS = new Set([
|
|
364
|
+
"authorization",
|
|
365
|
+
"x-api-key",
|
|
366
|
+
"api-key",
|
|
367
|
+
"private-token",
|
|
368
|
+
"x-auth-token",
|
|
369
|
+
]);
|
|
370
|
+
|
|
371
|
+
const pathValue = (value: unknown, path: string): unknown =>
|
|
372
|
+
path
|
|
373
|
+
.split(".")
|
|
374
|
+
.reduce<unknown>(
|
|
375
|
+
(current, key) =>
|
|
376
|
+
typeof current === "object" && current !== null
|
|
377
|
+
? (current as Record<string, unknown>)[key]
|
|
378
|
+
: undefined,
|
|
379
|
+
value,
|
|
380
|
+
);
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Read a linked account's profile, here in the app: a GET of the provider's `profile.url` with the
|
|
384
|
+
* account's token, the declared fields picked from the reply. A refusal is reported as `failed`,
|
|
385
|
+
* never as a rejected token.
|
|
386
|
+
*/
|
|
387
|
+
export const readProfile = (
|
|
388
|
+
ref: AccountRef,
|
|
389
|
+
): Effect.Effect<AccountProfile, never, HttpClient.HttpClient> =>
|
|
390
|
+
Effect.gen(function* () {
|
|
391
|
+
const profile = declarations.find((declaration) => declaration.name === ref.name)?.provider
|
|
392
|
+
.profile;
|
|
393
|
+
if (profile === undefined) return { status: "unchecked" } as const;
|
|
394
|
+
const url = URL.parse(profile.url);
|
|
395
|
+
if (url === null || !onDeclaredHost(ref.name, url)) {
|
|
396
|
+
return {
|
|
397
|
+
status: "failed",
|
|
398
|
+
message: "The profile address is not on one of the provider's hosts.",
|
|
399
|
+
} as const;
|
|
400
|
+
}
|
|
401
|
+
const header = profile.header ?? { name: "authorization", scheme: "Bearer" };
|
|
402
|
+
if (!PROFILE_HEADERS.has(header.name.toLowerCase())) {
|
|
403
|
+
return {
|
|
404
|
+
status: "failed",
|
|
405
|
+
message: `The profile header ${header.name} is not one Executor sends a token in.`,
|
|
406
|
+
} as const;
|
|
407
|
+
}
|
|
408
|
+
const result = yield* call(ref.name, (host) => host.accounts.token(ref, { caller: null }));
|
|
409
|
+
if (!result.ok) return { status: "failed", message: result.error.message } as const;
|
|
410
|
+
const token = result.value.token;
|
|
411
|
+
const client = yield* HttpClient.HttpClient;
|
|
412
|
+
const outcome = yield* Effect.gen(function* () {
|
|
413
|
+
const response = yield* client.execute(
|
|
414
|
+
HttpClientRequest.get(url).pipe(
|
|
415
|
+
HttpClientRequest.setHeaders({
|
|
416
|
+
accept: "application/json",
|
|
417
|
+
[header.name]: header.scheme === null ? token : `${header.scheme} ${token}`,
|
|
418
|
+
}),
|
|
419
|
+
),
|
|
420
|
+
);
|
|
421
|
+
if (response.status < 200 || response.status >= 300) {
|
|
422
|
+
return { status: "failed", message: `The service answered ${response.status}.` } as const;
|
|
423
|
+
}
|
|
424
|
+
const body = yield* response.json;
|
|
425
|
+
const info: Record<string, string> = {};
|
|
426
|
+
for (const [field, path] of Object.entries(profile.map)) {
|
|
427
|
+
const value = path === undefined ? undefined : pathValue(body, path);
|
|
428
|
+
if (typeof value === "string" || typeof value === "number") info[field] = String(value);
|
|
429
|
+
}
|
|
430
|
+
return { status: "ok", info } as const;
|
|
431
|
+
}).pipe(
|
|
432
|
+
Effect.timeout(Duration.seconds(10)),
|
|
433
|
+
Effect.catch(() =>
|
|
434
|
+
Effect.succeed({ status: "failed", message: "The service could not be reached." } as const),
|
|
435
|
+
),
|
|
436
|
+
);
|
|
437
|
+
return outcome as AccountProfile;
|
|
438
|
+
}).pipe(
|
|
439
|
+
Effect.catch(() =>
|
|
440
|
+
Effect.succeed({
|
|
441
|
+
status: "failed",
|
|
442
|
+
message: "Executor could not read the account.",
|
|
443
|
+
} as const),
|
|
444
|
+
),
|
|
445
|
+
);
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Runs the registered hooks for one event, in the app's own context. `externalId` is what the
|
|
449
|
+
* profile read just before said, when it said anything.
|
|
450
|
+
*/
|
|
451
|
+
export const runHooks = (
|
|
452
|
+
event: AccountEvent,
|
|
453
|
+
externalId: string | null = event.account.externalId,
|
|
454
|
+
): Effect.Effect<void, unknown, HttpClient.HttpClient> =>
|
|
455
|
+
Effect.gen(function* () {
|
|
456
|
+
const handlers = registered
|
|
457
|
+
.map((entry) => (event.kind === "linked" ? entry.onLink : entry.onUnlink))
|
|
458
|
+
.filter((handler) => handler !== undefined);
|
|
459
|
+
if (handlers.length === 0) return;
|
|
460
|
+
const account = yield* makeAccount(event.account, event.account.label);
|
|
461
|
+
const linked: Linked = { ...account, externalId };
|
|
462
|
+
for (const handler of handlers) {
|
|
463
|
+
yield* handler({ id: event.id, cause: event.cause, account: linked }) as Effect.Effect<
|
|
464
|
+
void,
|
|
465
|
+
unknown
|
|
466
|
+
>;
|
|
467
|
+
}
|
|
468
|
+
});
|