@gjermundgaraba/effect-actions 0.25.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Action.mjs +1 -1
- package/dist/ActionRpc.mjs +5 -2
- package/dist/authentication/provider.d.mts +4 -3
- package/dist/contract/callback.mjs +0 -4
- package/dist/contract/feed.mjs +1 -1
- package/dist/contract/implementation.d.mts +5 -15
- package/dist/contract/log.mjs +1 -1
- package/dist/contract/push.mjs +6 -10
- package/dist/contract/subscribe.mjs +0 -4
- package/dist/http/events.mjs +4 -1
- package/dist/mcp/bridge.mjs +1 -1
- package/dist/webhook/attempt.mjs +2 -2
- package/dist/webhook/health.mjs +99 -0
- package/dist/webhook/receiver.mjs +2 -2
- package/dist/webhook/signing.mjs +2 -6
- package/dist/webhook/subscriptions.mjs +34 -46
- package/docs/Action-failures.md +1 -1
- package/docs/ActionCli.md +1 -1
- package/docs/ActionHttp.md +1 -1
- package/docs/ActionRpc.md +0 -4
- package/docs/Authentication-advanced.md +16 -19
- package/docs/Authentication-failures.md +1 -1
- package/docs/Authentication.md +0 -4
- package/docs/Webhook.md +3 -6
- package/examples/build-events/src/notifier/routes.ts +3 -6
- package/examples/build-events/src/notifier.ts +4 -2
- package/examples/build-events/test/notifier.test.ts +1 -1
- package/examples/kitchen-sink/README.md +3 -3
- package/examples/kitchen-sink/src/identity/authenticate.ts +2 -2
- package/examples/kitchen-sink/src/identity/workspace-header.ts +19 -0
- package/examples/kitchen-sink/src/routes.ts +2 -2
- package/examples/live-rpc/src/chat/room.ts +0 -4
- package/examples/notes-service/src/identity/Identity.ts +0 -4
- package/package.json +1 -1
- package/examples/kitchen-sink/src/workspaces/tenant.ts +0 -22
package/dist/Action.mjs
CHANGED
|
@@ -121,7 +121,7 @@ const watcherOf = (feeds) => (event, input, options) => {
|
|
|
121
121
|
poll: polledOn("In process", event.name)((cursor) => feed.poll(value, cursor, { subscriber })),
|
|
122
122
|
stream: (cursor) => Stream$1.unwrap(Effect.flatMap(feed.stream(value), (open) => Effect.map(queuedPush(open, cursor, Effect.succeed, {
|
|
123
123
|
ending: Function.identity,
|
|
124
|
-
|
|
124
|
+
positions: "watermark",
|
|
125
125
|
capacity: 1
|
|
126
126
|
}), (queue) => Stream$1.fromQueue(queue)))).pipe(readOn("In process", event.name))
|
|
127
127
|
}, options).pipe(Stream$1.ensuring(feed.release?.(value, subscriber) ?? Effect.void));
|
package/dist/ActionRpc.mjs
CHANGED
|
@@ -178,7 +178,10 @@ const subscriptionHandlerOf = (feed, steps, error, keeper) => {
|
|
|
178
178
|
const call = Effect.gen(function* () {
|
|
179
179
|
const { input, cursor } = yield* Effect.mapError(decode(payload), InvalidInput.fromSchemaError);
|
|
180
180
|
const open = yield* feed.stream(yield* decodeEventInput(input));
|
|
181
|
-
if (keeper === void 0) return yield* queuedPush(open, cursor, encode, {
|
|
181
|
+
if (keeper === void 0) return yield* queuedPush(open, cursor, encode, {
|
|
182
|
+
ending: boundary,
|
|
183
|
+
positions: "heartbeat"
|
|
184
|
+
});
|
|
182
185
|
yield* keeper.keep({
|
|
183
186
|
clientId: options.client.id,
|
|
184
187
|
requestId: options.requestId,
|
|
@@ -195,7 +198,7 @@ const subscriptionHandlerOf = (feed, steps, error, keeper) => {
|
|
|
195
198
|
});
|
|
196
199
|
return yield* queuedPush(open, cursor, encode, {
|
|
197
200
|
ending: boundary,
|
|
198
|
-
|
|
201
|
+
positions: "watermark"
|
|
199
202
|
});
|
|
200
203
|
});
|
|
201
204
|
const wrapped = throughSteps(steps, call, {
|
|
@@ -114,10 +114,11 @@ export type DescriptorOf<O> = [O] extends [{
|
|
|
114
114
|
export type Matching<A extends Pick<Any$2, "caller">, D> = unknown extends Covered<Protected<A>> ? unknown : [Exclude<Covered<Protected<A>>, D extends Descriptor<infer I, unknown, Security, string, Errors> ? I : never>] extends [never] ? unknown : {
|
|
115
115
|
readonly "Authentication descriptor does not cover every protected action": never;
|
|
116
116
|
};
|
|
117
|
-
|
|
118
|
-
export type RemoteRequest<App, A extends Any$2> = ServedRequest<App, Extract<A, {
|
|
117
|
+
type PublicRequest<App, A extends Any$2> = ServedRequest<App, Extract<A, {
|
|
119
118
|
readonly caller: typeof Anyone;
|
|
120
|
-
}
|
|
119
|
+
}>>;
|
|
120
|
+
type ProtectedRequestLessIdentity<App, A extends Any$2> = Exclude<ServedRequest<App, Protected<A>>, Identity<Protected<A>>>;
|
|
121
|
+
export type RemoteRequest<App, A extends Any$2> = PublicRequest<App, A> | ProtectedRequestLessIdentity<App, A>;
|
|
121
122
|
/**
|
|
122
123
|
* The identity a remote layer's authentication provides every request, where `App` serves only
|
|
123
124
|
* protected actions of `A` and event types of `E`: its middleware reading it then owes nothing.
|
|
@@ -9,10 +9,6 @@ const SigningSecret = Schema.Struct({
|
|
|
9
9
|
const secretPrefix = "whsec_";
|
|
10
10
|
const decodeBase64 = Schema.decodeUnknownOption(Schema.Uint8ArrayFromBase64);
|
|
11
11
|
const keyOf = (text) => text.startsWith(secretPrefix) ? Option.filter(decodeBase64(text.slice(6)), (key) => key.length >= 24 && key.length <= 64) : Option.none();
|
|
12
|
-
/**
|
|
13
|
-
* A webhook's signing secret, as Standard Webhooks writes one: `whsec_` and the base64 of 24 to
|
|
14
|
-
* 64 bytes, decoded as the `SigningSecret` it is.
|
|
15
|
-
*/
|
|
16
12
|
const WebhookSecret = Schema.String.annotate({ description: "whsec_ and the base64 of 24 to 64 random bytes, which signs each delivery." }).pipe(Schema.decodeTo(SigningSecret, SchemaTransformation.transformEffect({
|
|
17
13
|
decode: (text, options) => Option.match(keyOf(text), {
|
|
18
14
|
onNone: () => Effect.fail(new SchemaIssue.InvalidValue({ message: "whsec_ and the base64 of 24 to 64 random bytes" }, text, options)),
|
package/dist/contract/feed.mjs
CHANGED
|
@@ -111,7 +111,7 @@ const logRun = (event, source, log) => {
|
|
|
111
111
|
stream: (input, cursor) => Stream.unwrap(Effect.map(keyOf(source, input), (key) => log.follow(cursor, logPageSize).pipe(Stream.mapEffect((read) => Effect.map(received(input, key, read), (items) => fedOf({
|
|
112
112
|
items,
|
|
113
113
|
truncated: read.truncated,
|
|
114
|
-
from: read.
|
|
114
|
+
from: read.from,
|
|
115
115
|
to: read.cursor
|
|
116
116
|
}))), Stream.flattenIterable)))
|
|
117
117
|
};
|
|
@@ -7,15 +7,9 @@ import { Any as Any$1 } from "../Action.mjs";
|
|
|
7
7
|
import { Context, Effect, Layer, Scope, Stream } from "effect";
|
|
8
8
|
/** Decoded values at the dispatch boundary every surface shares. */
|
|
9
9
|
export type ErasedValue = Any$1["input"]["Type"];
|
|
10
|
-
/**
|
|
11
|
-
* A handler as written, erased: its answer, or the stream of an action answering one. Method
|
|
12
|
-
* extraction makes the argument bivariant: a surface selects the action before it invokes a
|
|
13
|
-
* handler, so its decoded input is the matching handler input, and handlers are not widened at
|
|
14
|
-
* their public API.
|
|
15
|
-
*/
|
|
16
10
|
export type WrittenHandler<R> = {
|
|
17
|
-
|
|
18
|
-
}["
|
|
11
|
+
bivarianceHack(input: ErasedValue, reporting?: Reporting): Effect.Effect<ErasedValue, ErasedValue, R> | Stream.Stream<ErasedValue, ErasedValue, R>;
|
|
12
|
+
}["bivarianceHack"];
|
|
19
13
|
/**
|
|
20
14
|
* A handler behind its action's authentication, authorization and declared errors, as a surface
|
|
21
15
|
* calls it. For an action answering a stream it succeeds at once with the call's stream, which
|
|
@@ -48,9 +42,7 @@ export interface Memoized<S, E, R> {
|
|
|
48
42
|
* its handlers' builder, `RA` what its authorizer reads per request, and `EAX` and `RAX` the
|
|
49
43
|
* failures and services of the authorizer's builder.
|
|
50
44
|
*/
|
|
51
|
-
export declare class Implementation<A extends Any$1, RequestServices
|
|
52
|
-
readonly [name: string]: unknown;
|
|
53
|
-
}, EX, RX, RA = never, EAX = never, RAX = never> {
|
|
45
|
+
export declare class Implementation<A extends Any$1, RequestServices, EX, RX, RA = never, EAX = never, RAX = never> {
|
|
54
46
|
#private;
|
|
55
47
|
/** Type-only: each action's handler's request-time requirements. */
|
|
56
48
|
readonly "~request": RequestServices;
|
|
@@ -98,9 +90,7 @@ export declare class Implementation<A extends Any$1, RequestServices extends {
|
|
|
98
90
|
* admits every implementation, while a value of this type owes `unknown`, which no surface can be
|
|
99
91
|
* given.
|
|
100
92
|
*/
|
|
101
|
-
export type AnyImplementation<A extends Any$1 = Any$1> = Implementation<A,
|
|
102
|
-
readonly [name: string]: unknown;
|
|
103
|
-
}, unknown, unknown, unknown, unknown, unknown>;
|
|
93
|
+
export type AnyImplementation<A extends Any$1 = Any$1> = Implementation<A, unknown, unknown, unknown, unknown, unknown, unknown>;
|
|
104
94
|
/** What a surface serves: one implementation, of actions or of events, or a list of them. */
|
|
105
95
|
export type Served = AnyImplementation | AnyEventImplementation | ReadonlyArray<AnyImplementation | AnyEventImplementation>;
|
|
106
96
|
/** What a surface serving no events takes: one action implementation, or a list of them. */
|
|
@@ -192,7 +182,7 @@ type AuthenticationOf<A extends Any$1> = A["caller"] extends typeof Anyone ? nev
|
|
|
192
182
|
export type RequestOf<App, A extends Any$1> = App extends {
|
|
193
183
|
readonly "~request": infer R;
|
|
194
184
|
readonly "~authorizeRequest": infer RA;
|
|
195
|
-
} ? A extends Any$1 ? [A["name"] & keyof R] extends [never] ? never : R[A["name"] & keyof R] | (A["caller"] extends typeof Anyone ? never : RA) | AuthenticationOf<A> : never : never;
|
|
185
|
+
} ? A extends Any$1 ? unknown extends R ? unknown : [A["name"] & keyof R] extends [never] ? never : R[A["name"] & keyof R] | (A["caller"] extends typeof Anyone ? never : RA) | AuthenticationOf<A> : never : never;
|
|
196
186
|
type OwnActions<App> = Extract<ActionOf<App>, Any$1>;
|
|
197
187
|
/**
|
|
198
188
|
* What a surface serving the actions `Listed` of the implementations `App` fails with at startup:
|
package/dist/contract/log.mjs
CHANGED
|
@@ -100,7 +100,7 @@ const makeLogStore = (storage, { maxAge = defaultBounds.maxAge, maxEvents = defa
|
|
|
100
100
|
at: stored.at,
|
|
101
101
|
value: stored.logged
|
|
102
102
|
})),
|
|
103
|
-
|
|
103
|
+
from: cursorAt(epoch, after),
|
|
104
104
|
cursor: cursorAt(epoch, page.at(-1)?.[0] ?? after),
|
|
105
105
|
truncated,
|
|
106
106
|
hasMore: pending.length > limit
|
package/dist/contract/push.mjs
CHANGED
|
@@ -4,10 +4,6 @@ import { Checked, Gap, OccurrenceOf } from "./occurrence.mjs";
|
|
|
4
4
|
import { defaultNextPoll } from "./feed.mjs";
|
|
5
5
|
import { Cause, Duration, Effect, Latch, Match, Queue, Schema, Stream } from "effect";
|
|
6
6
|
// src/contract/push.ts
|
|
7
|
-
/**
|
|
8
|
-
* A push subscription read on through a failure no refusal explains, such as an upstream's
|
|
9
|
-
* outage: its cause is logged and reported, and reading resumes from the position reached.
|
|
10
|
-
*/
|
|
11
7
|
const Failed = Schema.TaggedStruct("Failed", {});
|
|
12
8
|
const PushedOf = (event) => Schema.Union([
|
|
13
9
|
OccurrenceOf(event),
|
|
@@ -21,7 +17,7 @@ const subscriptionWith = (input) => Schema.Struct({
|
|
|
21
17
|
});
|
|
22
18
|
const SubscriptionOf = (event) => subscriptionWith(event.input);
|
|
23
19
|
const Subscription = subscriptionWith(Schema.Json);
|
|
24
|
-
const
|
|
20
|
+
const defaultCapacity = 16;
|
|
25
21
|
const heartbeatEvery = Duration.seconds(30);
|
|
26
22
|
const isFailed = Schema.is(Failed);
|
|
27
23
|
const readOn = (surface, name) => (sent) => sent.pipe(Stream.mapEffect((element) => isFailed(element) ? Effect.as(Effect.logWarning(`${surface} event "${name}" failed to read, and resumes`), []) : Effect.succeed([element])), Stream.flattenIterable);
|
|
@@ -34,7 +30,7 @@ const polledOn = (surface, name) => (poll) => (cursor) => Effect.catchCauseIf(po
|
|
|
34
30
|
hasMore: false,
|
|
35
31
|
nextPoll: defaultNextPoll
|
|
36
32
|
}));
|
|
37
|
-
const pushed = (open, cursor, deliver, { resumesUnconfirmed = false,
|
|
33
|
+
const pushed = (open, cursor, deliver, { resumesUnconfirmed = false, positions }) => Effect.gen(function* () {
|
|
38
34
|
const confirmed = yield* Latch.make();
|
|
39
35
|
let reached = cursor;
|
|
40
36
|
let active = false;
|
|
@@ -50,7 +46,7 @@ const pushed = (open, cursor, deliver, { resumesUnconfirmed = false, inOrder = f
|
|
|
50
46
|
Checked: (checked) => {
|
|
51
47
|
if (!active) return sent(checked, checked.cursor);
|
|
52
48
|
if (checked.cursor === null || checked.cursor === reached) return Effect.void;
|
|
53
|
-
return
|
|
49
|
+
return positions === "watermark" ? sent(checked, checked.cursor) : movedTo(checked.cursor);
|
|
54
50
|
},
|
|
55
51
|
Occurrence: (occurrence) => Effect.andThen(active ? Effect.void : sent(Checked.make({ cursor: reached }), reached), Effect.suspend(() => sent(occurrence, occurrence.cursor ?? reached)))
|
|
56
52
|
});
|
|
@@ -60,13 +56,13 @@ const pushed = (open, cursor, deliver, { resumesUnconfirmed = false, inOrder = f
|
|
|
60
56
|
});
|
|
61
57
|
const once = Stream.suspend(() => Duration.isZero(wait) ? open(reached) : Stream.unwrap(Effect.as(Effect.sleep(wait), open(reached)))).pipe(Stream.runForEach(delivered), Effect.catchCauseIf(resumes, (cause) => Effect.andThen(reported(cause), deliver(Failed.make({})))), Effect.andThen(waiting));
|
|
62
58
|
const heartbeat = Effect.andThen(confirmed.await, Effect.forever(Effect.andThen(Effect.sleep(heartbeatEvery), () => Effect.suspend(() => deliver(Checked.make({ cursor: reached }))))));
|
|
63
|
-
return yield*
|
|
59
|
+
return yield* positions === "watermark" ? Effect.forever(once) : Effect.raceFirst(Effect.forever(once), heartbeat);
|
|
64
60
|
});
|
|
65
|
-
const queuedPush = (open, cursor, encode, { ending,
|
|
61
|
+
const queuedPush = (open, cursor, encode, { ending, positions, capacity = defaultCapacity }) => Effect.gen(function* () {
|
|
66
62
|
const queue = yield* Queue.bounded(capacity);
|
|
67
63
|
yield* pushed(open, cursor, (sent) => Effect.flatMap(encode(sent), (element) => Queue.offer(queue, element)), {
|
|
68
64
|
resumesUnconfirmed: true,
|
|
69
|
-
|
|
65
|
+
positions
|
|
70
66
|
}).pipe(ending, Queue.into(queue), Effect.forkScoped({ startImmediately: true }));
|
|
71
67
|
return queue;
|
|
72
68
|
});
|
|
@@ -17,10 +17,6 @@ const WebhookCancellationOf = (event) => Schema.Struct({
|
|
|
17
17
|
input: event.input,
|
|
18
18
|
delivery: WebhookTarget
|
|
19
19
|
});
|
|
20
|
-
/**
|
|
21
|
-
* How a webhook subscription's deliveries are going, as a refresh answers it: whether it is
|
|
22
|
-
* delivering, when it last delivered, and the category of its last failure, since when it fails.
|
|
23
|
-
*/
|
|
24
20
|
const DeliveryStatus = Schema.Struct({
|
|
25
21
|
active: Schema.Boolean,
|
|
26
22
|
lastDeliveryAt: Schema.NullOr(Schema.String),
|
package/dist/http/events.mjs
CHANGED
|
@@ -64,7 +64,10 @@ const answering = (feed, authentication) => {
|
|
|
64
64
|
return ({ payload: { input, cursor } }) => Effect.gen(function* () {
|
|
65
65
|
if (((yield* HttpServerRequest.HttpServerRequest).headers["accept"] ?? "").includes("text/event-stream")) {
|
|
66
66
|
const open = yield* feed.stream(input);
|
|
67
|
-
return Stream.fromQueue(yield* queuedPush(open, cursor, encode, {
|
|
67
|
+
return Stream.fromQueue(yield* queuedPush(open, cursor, encode, {
|
|
68
|
+
ending: Function.identity,
|
|
69
|
+
positions: "heartbeat"
|
|
70
|
+
}));
|
|
68
71
|
}
|
|
69
72
|
const subscriber = yield* principalOf(feed.event, authentication);
|
|
70
73
|
return yield* feed.poll(input, cursor, { subscriber });
|
package/dist/mcp/bridge.mjs
CHANGED
|
@@ -199,7 +199,7 @@ const withEvents = (base, serving) => {
|
|
|
199
199
|
requestId,
|
|
200
200
|
wire,
|
|
201
201
|
_meta: yield* meta
|
|
202
|
-
}, (deliver) => asSubscriber(feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver))));
|
|
202
|
+
}, (deliver) => asSubscriber(feed.event, Effect.flatMap(feed.stream(input), (open) => pushed(open, cursor ?? null, deliver, { positions: "heartbeat" }))));
|
|
203
203
|
}).pipe(fromBuilt),
|
|
204
204
|
"events/subscribe": ({ name, arguments: args, delivery: { url, secret }, cursor, ttlMs }) => Effect.gen(function* () {
|
|
205
205
|
yield* routedTo(name);
|
package/dist/webhook/attempt.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { standardWebhooksSignature } from "./signing.mjs";
|
|
2
2
|
import { Clock, Data, Duration, Effect, Option, Schema, Stream } from "effect";
|
|
3
3
|
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
|
|
4
4
|
// src/webhook/attempt.ts
|
|
@@ -15,7 +15,7 @@ const sent = ({ url, subscriptionId, webhookId, body, keys }, checked, answer) =
|
|
|
15
15
|
final: false
|
|
16
16
|
});
|
|
17
17
|
const timestamp = Math.floor((yield* Clock.currentTimeMillis) / 1e3);
|
|
18
|
-
const signed = yield*
|
|
18
|
+
const signed = yield* standardWebhooksSignature(keys, webhookId, timestamp, body);
|
|
19
19
|
const client = HttpClient.withScope(yield* HttpClient.HttpClient);
|
|
20
20
|
const request = HttpClientRequest.post(url).pipe(HttpClientRequest.setHeaders({
|
|
21
21
|
"webhook-id": webhookId,
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { DateTime, Option } from "effect";
|
|
2
|
+
// src/webhook/health.ts
|
|
3
|
+
const deliveryHealth = (retryForMs) => {
|
|
4
|
+
const spent = (failedSince, at) => at - failedSince >= retryForMs;
|
|
5
|
+
const transition = (health, event) => {
|
|
6
|
+
const { lastDeliveryAt } = health;
|
|
7
|
+
switch (health.value) {
|
|
8
|
+
case "Delivering":
|
|
9
|
+
if (event.type === "Refreshed") return health;
|
|
10
|
+
if (event.type === "Delivered") return {
|
|
11
|
+
value: "Delivering",
|
|
12
|
+
lastDeliveryAt: event.at,
|
|
13
|
+
lastError: null
|
|
14
|
+
};
|
|
15
|
+
if (event.final) return event.category === health.lastError ? health : {
|
|
16
|
+
...health,
|
|
17
|
+
lastError: event.category
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
value: spent(event.at, event.at) ? "Suspended" : "Failing",
|
|
21
|
+
lastDeliveryAt,
|
|
22
|
+
lastError: event.category,
|
|
23
|
+
failedSince: event.at
|
|
24
|
+
};
|
|
25
|
+
case "Failing":
|
|
26
|
+
if (event.type === "Refreshed") return health;
|
|
27
|
+
if (event.type === "Delivered") return {
|
|
28
|
+
value: "Delivering",
|
|
29
|
+
lastDeliveryAt: event.at,
|
|
30
|
+
lastError: null
|
|
31
|
+
};
|
|
32
|
+
if (event.final) return {
|
|
33
|
+
value: "Delivering",
|
|
34
|
+
lastDeliveryAt,
|
|
35
|
+
lastError: event.category
|
|
36
|
+
};
|
|
37
|
+
if (spent(health.failedSince, event.at)) return {
|
|
38
|
+
...health,
|
|
39
|
+
value: "Suspended",
|
|
40
|
+
lastError: event.category
|
|
41
|
+
};
|
|
42
|
+
return event.category === health.lastError ? health : {
|
|
43
|
+
...health,
|
|
44
|
+
lastError: event.category
|
|
45
|
+
};
|
|
46
|
+
case "Suspended": return event.type === "Refreshed" ? {
|
|
47
|
+
value: "Delivering",
|
|
48
|
+
lastDeliveryAt,
|
|
49
|
+
lastError: health.lastError
|
|
50
|
+
} : health;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
return {
|
|
54
|
+
initialState: {
|
|
55
|
+
value: "Delivering",
|
|
56
|
+
lastDeliveryAt: null,
|
|
57
|
+
lastError: null
|
|
58
|
+
},
|
|
59
|
+
transition
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
|
|
63
|
+
const millisOf = (text) => {
|
|
64
|
+
const millis = Date.parse(text);
|
|
65
|
+
return Number.isNaN(millis) ? Option.none() : Option.some(millis);
|
|
66
|
+
};
|
|
67
|
+
const statusOf = (health) => {
|
|
68
|
+
const lastDeliveryAt = health.lastDeliveryAt === null ? null : iso(health.lastDeliveryAt);
|
|
69
|
+
if (health.value === "Delivering") return {
|
|
70
|
+
active: true,
|
|
71
|
+
lastDeliveryAt,
|
|
72
|
+
lastError: health.lastError
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
active: health.value === "Failing",
|
|
76
|
+
lastDeliveryAt,
|
|
77
|
+
lastError: health.lastError,
|
|
78
|
+
failedSince: iso(health.failedSince)
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
const healthOf = (status) => Option.gen(function* () {
|
|
82
|
+
const lastDeliveryAt = status.lastDeliveryAt === null ? null : yield* millisOf(status.lastDeliveryAt);
|
|
83
|
+
if (status.failedSince === void 0) {
|
|
84
|
+
if (!status.active) return yield* Option.none();
|
|
85
|
+
return {
|
|
86
|
+
value: "Delivering",
|
|
87
|
+
lastDeliveryAt,
|
|
88
|
+
lastError: status.lastError
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
value: status.active ? "Failing" : "Suspended",
|
|
93
|
+
lastDeliveryAt,
|
|
94
|
+
lastError: yield* Option.fromNullOr(status.lastError),
|
|
95
|
+
failedSince: yield* millisOf(status.failedSince)
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
const failingForMs = (health, now) => health.value === "Failing" ? now - health.failedSince : 0;
|
|
99
|
+
export { deliveryHealth, failingForMs, healthOf, statusOf };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { watchParameter } from "../contract/receiving.mjs";
|
|
2
2
|
import { makeRecent } from "../contract/recent.mjs";
|
|
3
|
-
import { constantTimeEqual,
|
|
3
|
+
import { constantTimeEqual, standardWebhooksSignature } from "./signing.mjs";
|
|
4
4
|
import { Clock, Effect, Option, Predicate, Schema } from "effect";
|
|
5
5
|
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
6
6
|
import { Base64, Base64Url } from "effect/encoding";
|
|
@@ -40,7 +40,7 @@ const makeReceiver = (path) => Effect.sync(() => {
|
|
|
40
40
|
const now = Math.floor((yield* Clock.currentTimeMillis) / 1e3);
|
|
41
41
|
if (id === void 0 || !Number.isInteger(timestamp) || Math.abs(now - timestamp) > timestampToleranceSeconds) return unauthorized;
|
|
42
42
|
const text = yield* Effect.orElseSucceed(request.text, () => "");
|
|
43
|
-
const expected = yield*
|
|
43
|
+
const expected = yield* standardWebhooksSignature([place.key], id, timestamp, text);
|
|
44
44
|
if (!signatures.some((each) => constantTimeEqual(each, expected))) return unauthorized;
|
|
45
45
|
const body = decodeBody(text);
|
|
46
46
|
if (Option.isNone(body)) return HttpServerResponse.empty({ status: 400 });
|
package/dist/webhook/signing.mjs
CHANGED
|
@@ -11,12 +11,8 @@ const hmac = (key, content) => Effect.promise(async () => {
|
|
|
11
11
|
}, false, ["sign"]);
|
|
12
12
|
return new Uint8Array(await crypto.subtle.sign("HMAC", imported, encoder.encode(content)));
|
|
13
13
|
});
|
|
14
|
-
|
|
15
|
-
* A delivery's `webhook-signature`: Standard Webhooks' `v1,` HMAC-SHA256 of `id.timestamp.body`
|
|
16
|
-
* under each key, space apart, so a receiver mid-rotation verifies under either.
|
|
17
|
-
*/
|
|
18
|
-
const signature = (keys, id, timestamp, body) => Effect.map(Effect.forEach(keys, (key) => hmac(key, `${id}.${timestamp}.${body}`)), (signed) => signed.map((bytes) => `v1,${Base64.encode(bytes)}`).join(" "));
|
|
14
|
+
const standardWebhooksSignature = (keys, id, timestamp, body) => Effect.map(Effect.forEach(keys, (key) => hmac(key, `${id}.${timestamp}.${body}`)), (signed) => signed.map((bytes) => `v1,${Base64.encode(bytes)}`).join(" "));
|
|
19
15
|
const subscriptionId = (key) => Effect.map(sha256Hex(key), (hex) => `sub_${hex.slice(0, 32)}`);
|
|
20
16
|
const randomToken = Effect.sync(() => Hex.encode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
|
|
21
17
|
const constantTimeEqual = (a, b) => Mac.timingSafeEqual(encoder.encode(a), encoder.encode(b));
|
|
22
|
-
export { constantTimeEqual, randomToken,
|
|
18
|
+
export { constantTimeEqual, randomToken, standardWebhooksSignature, subscriptionId };
|
|
@@ -7,7 +7,8 @@ import { randomToken, subscriptionId } from "./signing.mjs";
|
|
|
7
7
|
import { pushed, refusalIn } from "../contract/push.mjs";
|
|
8
8
|
import { checkedHost } from "./address.mjs";
|
|
9
9
|
import { attempt, challenged } from "./attempt.mjs";
|
|
10
|
-
import {
|
|
10
|
+
import { deliveryHealth, failingForMs, healthOf, statusOf } from "./health.mjs";
|
|
11
|
+
import { Cause, Clock, Context, DateTime, Deferred, Duration, Effect, Exit, Fiber, FiberMap, Match, Option, RcMap, Schedule, Schema, Scope, Semaphore, Stream } from "effect";
|
|
11
12
|
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
12
13
|
// src/webhook/subscriptions.ts
|
|
13
14
|
const minTtl = Duration.minutes(1);
|
|
@@ -16,10 +17,6 @@ const maxBody = 262144;
|
|
|
16
17
|
const encoder = new TextEncoder();
|
|
17
18
|
const terminatedEnvelopeRetries = Schedule.exponential(Duration.seconds(1)).pipe(Schedule.upTo({ times: 3 }));
|
|
18
19
|
const iso = (millis) => DateTime.formatIso(DateTime.makeUnsafe(millis));
|
|
19
|
-
const resumedWithFreshBudget = (status) => status.active ? status : {
|
|
20
|
-
...Struct.omit(status, ["failedSince"]),
|
|
21
|
-
active: true
|
|
22
|
-
};
|
|
23
20
|
const grantOf = (ttlMs, policy) => Duration.clamp(ttlMs === null || ttlMs === void 0 ? policy.maxTtl : Duration.millis(ttlMs), {
|
|
24
21
|
minimum: minTtl,
|
|
25
22
|
maximum: policy.maxTtl
|
|
@@ -49,21 +46,26 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
49
46
|
secret: subscription.secret,
|
|
50
47
|
expiresAt: subscription.expiresAt,
|
|
51
48
|
watermark: subscription.watermark,
|
|
52
|
-
status: subscription.
|
|
49
|
+
status: statusOf(subscription.health)
|
|
53
50
|
});
|
|
54
51
|
});
|
|
55
52
|
const dropped = (id) => Effect.sync(() => storage?.mark(id, void 0));
|
|
56
53
|
const verified = /* @__PURE__ */ new Map();
|
|
57
54
|
const locks = yield* RcMap.make({ lookup: (_id) => Semaphore.make(1) });
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
|
|
55
|
+
const health = deliveryHealth(Duration.toMillis(policy.retryFor));
|
|
56
|
+
const transitioned = (subscription, event) => Effect.suspend(() => {
|
|
57
|
+
const next = health.transition(subscription.health, event);
|
|
58
|
+
if (next === subscription.health) return Effect.void;
|
|
59
|
+
subscription.health = next;
|
|
60
|
+
return kept(subscription);
|
|
61
|
+
});
|
|
62
|
+
const waitingAsLongAsFailing = (subscription) => Schedule.modifyDelay(Schedule.forever, () => Effect.map(Clock.currentTimeMillis, (now) => Duration.clamp(Duration.millis(failingForMs(subscription.health, now)), {
|
|
61
63
|
minimum: Duration.seconds(1),
|
|
62
64
|
maximum: Duration.minutes(5)
|
|
63
65
|
})));
|
|
64
66
|
const retrying = (subscription) => ({
|
|
65
67
|
schedule: waitingAsLongAsFailing(subscription),
|
|
66
|
-
while: (
|
|
68
|
+
while: () => subscription.health.value === "Failing"
|
|
67
69
|
});
|
|
68
70
|
const locked = (id) => (effect) => Effect.scoped(Effect.flatMap(RcMap.get(locks, id), (lock) => lock.withPermits(1)(effect)));
|
|
69
71
|
const asSubscriber = (subscription, effect) => Effect.updateContext(effect, () => subscription.context);
|
|
@@ -74,31 +76,17 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
74
76
|
body,
|
|
75
77
|
keys: subscription.previous !== void 0 && now < subscription.previous.until ? [subscription.secret.key, subscription.previous.key] : [subscription.secret.key]
|
|
76
78
|
}, trusted(subscription.url, policy.allowedCallbacks) ? Effect.void : checkedHost(subscription.url, policy.dns)), built));
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return failure !== void 0 && status.lastError === failure.category && status.failedSince !== void 0 ? Effect.void : kept(subscription);
|
|
89
|
-
}));
|
|
90
|
-
const suspended = (subscription) => Effect.andThen(Effect.andThen(Effect.sync(() => {
|
|
91
|
-
subscription.status = {
|
|
92
|
-
...subscription.status,
|
|
93
|
-
active: false
|
|
94
|
-
};
|
|
95
|
-
}), kept(subscription)), Effect.never);
|
|
96
|
-
const abandonedResettingBudget = (subscription) => Effect.andThen(Effect.sync(() => {
|
|
97
|
-
subscription.status = Struct.omit(subscription.status, ["failedSince"]);
|
|
98
|
-
}), kept(subscription));
|
|
99
|
-
const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError((failure) => recorded(subscription, failure)), Effect.retry(retrying(subscription)), Effect.matchEffect({
|
|
100
|
-
onSuccess: () => Effect.as(recorded(subscription, void 0), true),
|
|
101
|
-
onFailure: (failure) => failure.final ? Effect.as(abandonedResettingBudget(subscription), false) : suspended(subscription)
|
|
79
|
+
const delivered = (subscription, webhookId, body) => post(subscription, webhookId, body).pipe(Effect.tapError(({ category, final }) => Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
|
|
80
|
+
type: "AttemptFailed",
|
|
81
|
+
category,
|
|
82
|
+
final,
|
|
83
|
+
at
|
|
84
|
+
}))), Effect.retry(retrying(subscription)), Effect.matchEffect({
|
|
85
|
+
onSuccess: () => Effect.as(Effect.flatMap(Clock.currentTimeMillis, (at) => transitioned(subscription, {
|
|
86
|
+
type: "Delivered",
|
|
87
|
+
at
|
|
88
|
+
})), true),
|
|
89
|
+
onFailure: () => subscription.health.value === "Suspended" ? Effect.never : Effect.succeed(false)
|
|
102
90
|
}));
|
|
103
91
|
const gapped = (subscription, cursor) => Effect.flatMap(randomToken, (token) => delivered(subscription, `msg_gap_${token}`, JSON.stringify({
|
|
104
92
|
type: "gap",
|
|
@@ -146,7 +134,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
146
134
|
});
|
|
147
135
|
const finished = (subscription) => Effect.suspend(() => holds(subscription) ? Effect.andThen(ended(subscription), dropped(subscription.id)) : Effect.void);
|
|
148
136
|
const workerOf = (subscription, input, cursor, confirmation) => Effect.raceFirst(pushed((from) => Stream.unwrap(Effect.map(subscription.feed.stream(input), (read) => read(from))), cursor, deliverTo(subscription, input, confirmation), {
|
|
149
|
-
|
|
137
|
+
positions: "watermark",
|
|
150
138
|
resumesUnconfirmed: Deferred.isDoneUnsafe(confirmation)
|
|
151
139
|
}), expired(subscription)).pipe(Effect.exit, Effect.tap(() => finished(subscription)), Effect.flatMap((exit) => {
|
|
152
140
|
if (Deferred.isDoneUnsafe(confirmation)) return Exit.isFailure(exit) ? terminated(subscription, exit.cause) : Effect.void;
|
|
@@ -185,7 +173,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
185
173
|
}));
|
|
186
174
|
}));
|
|
187
175
|
const refreshed = (subscription, granted, input, now) => Effect.gen(function* () {
|
|
188
|
-
const {
|
|
176
|
+
const { health: before, watermark } = subscription;
|
|
189
177
|
const renewed = {
|
|
190
178
|
...subscription,
|
|
191
179
|
...granted,
|
|
@@ -193,7 +181,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
193
181
|
key: subscription.secret.key,
|
|
194
182
|
until: now + Duration.toMillis(rotationGrace)
|
|
195
183
|
} },
|
|
196
|
-
|
|
184
|
+
health: health.transition(before, { type: "Refreshed" })
|
|
197
185
|
};
|
|
198
186
|
const confirmation = yield* confirmedAt(watermark);
|
|
199
187
|
yield* swapHeldWorker(renewed.id, renewed, workerOf(renewed, input, watermark, confirmation));
|
|
@@ -204,7 +192,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
204
192
|
refreshBefore: iso(renewed.expiresAt),
|
|
205
193
|
cursor: watermark,
|
|
206
194
|
truncated: false,
|
|
207
|
-
deliveryStatus:
|
|
195
|
+
deliveryStatus: statusOf(before)
|
|
208
196
|
};
|
|
209
197
|
});
|
|
210
198
|
const heldOf = (fields) => ({
|
|
@@ -233,6 +221,10 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
233
221
|
if (expiresAt <= (yield* Clock.currentTimeMillis)) return yield* dropped(id);
|
|
234
222
|
const input = yield* Schema.decodeEffect(Schema.toCodecJson(feed.event.input))(record.input);
|
|
235
223
|
const identity = yield* Schema.decodeEffect(Schema.toCodecJson(schema))(record.identity);
|
|
224
|
+
const restoredHealth = yield* Option.match(healthOf(record.status), {
|
|
225
|
+
onNone: () => Effect.die(/* @__PURE__ */ new Error(`The kept webhook subscription ${id} has a delivery status no subscription reaches, ${JSON.stringify(record.status)} (unsubscribe it to remove the record, then subscribe again)`)),
|
|
226
|
+
onSome: Effect.succeed
|
|
227
|
+
});
|
|
236
228
|
const principal = keyed.principal(identity);
|
|
237
229
|
const current = yield* idOf({
|
|
238
230
|
feed,
|
|
@@ -254,11 +246,11 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
254
246
|
secret,
|
|
255
247
|
context: Context.add(built, feed.event.caller, identity),
|
|
256
248
|
expiresAt,
|
|
257
|
-
|
|
249
|
+
health: restoredHealth,
|
|
258
250
|
watermark: record.watermark
|
|
259
251
|
});
|
|
260
252
|
const confirmation = yield* confirmedAt(record.watermark);
|
|
261
|
-
yield* swapHeldWorker(current, subscription,
|
|
253
|
+
yield* swapHeldWorker(current, subscription, restoredHealth.value === "Suspended" ? Effect.andThen(expired(subscription), finished(subscription)) : workerOf(subscription, input, record.watermark, confirmation));
|
|
262
254
|
if (current !== id) yield* kept(subscription);
|
|
263
255
|
}).pipe(Effect.catchCause(reported));
|
|
264
256
|
const serve = (feeds, keyed) => Effect.gen(function* () {
|
|
@@ -303,11 +295,7 @@ const makeWebhooks = (policy) => Effect.gen(function* () {
|
|
|
303
295
|
url,
|
|
304
296
|
feed,
|
|
305
297
|
principal,
|
|
306
|
-
|
|
307
|
-
active: true,
|
|
308
|
-
lastDeliveryAt: null,
|
|
309
|
-
lastError: null
|
|
310
|
-
},
|
|
298
|
+
health: health.initialState,
|
|
311
299
|
watermark: cursor
|
|
312
300
|
});
|
|
313
301
|
yield* verify(subscription, now);
|
package/docs/Action-failures.md
CHANGED
|
@@ -23,7 +23,7 @@ What you see when something is wrong, and the fix. Search for a fragment of the
|
|
|
23
23
|
|
|
24
24
|
## Where an implementation is served
|
|
25
25
|
|
|
26
|
-
- `Type 'CurrentUser' is not assignable to type 'never'`, or `Request<"Requires", CurrentUser>` still owed,
|
|
26
|
+
- `Type 'CurrentUser' is not assignable to type 'never'`, or `Request<"Requires", CurrentUser>` still owed, where a public action's handler reads one, alone on its layer or beside protected actions: authentication provides the identity to protected requests only. Make the action protected.
|
|
27
27
|
- `Type '{ readonly "A builder yields the caller, which a server has per request: yield it in a handler or an authorizer": { readonly caller: CurrentUser; readonly builderOf: "createNote" | ...; }; }' is not assignable to type 'never'` where a server is launched: the builder of the `implement` call whose actions `builderOf` names, or the Effect building its authorizer, yields the caller, which a builder would resolve once at startup. Move the `yield*` into the handler or the authorizer.
|
|
28
28
|
- `is missing the following properties from type 'Scope'` at each `it.effect` that runs the routes: a builder, or the Effect building an authorizer, yields the caller or another per-request service, which a builder would resolve once at startup. Move the `yield*` into the handler or the authorizer.
|
|
29
29
|
- `HttpRouter.Request<"Requires", X>` still owed, or `Type 'X' is not assignable to type 'never'` at `runMain`, although `X`, a store the authorizer reads, is provided at startup: what a plain authorizer yields is a request-time requirement, and this one yields `X` on every call. Make `authorize` an Effect that yields `X` once and returns the function ([Authorize calls](Action.md#authorize-calls)).
|
package/docs/ActionCli.md
CHANGED
|
@@ -42,7 +42,7 @@ The aggregate is [assistant/src/commands.ts](../examples/assistant/src/commands.
|
|
|
42
42
|
|
|
43
43
|
## Call a server from commands
|
|
44
44
|
|
|
45
|
-
Pass the HTTP binding to `remote`. The program imports the binding alone, never a handler. The connection is the `client` option, an `ActionHttp.client` ([ActionHttp.md](ActionHttp.md#call-the-api-from-effect)), its rules on `ActionCli.Calling`'s `client`, shared by `remote` and `remoteCommand`: [notes-service/src/commands.ts](../examples/notes-service/src/commands.ts) requires a token, mapping its absence to an error that says what to do, and [kitchen-sink/src/cli.ts](../examples/kitchen-sink/src/cli.ts) adds
|
|
45
|
+
Pass the HTTP binding to `remote`. The program imports the binding alone, never a handler. The connection is the `client` option, an `ActionHttp.client` ([ActionHttp.md](ActionHttp.md#call-the-api-from-effect)), its rules on `ActionCli.Calling`'s `client`, shared by `remote` and `remoteCommand`: [notes-service/src/commands.ts](../examples/notes-service/src/commands.ts) requires a token, mapping its absence to an error that says what to do, and [kitchen-sink/src/cli.ts](../examples/kitchen-sink/src/cli.ts) adds the `X-Workspace` header, reads an optional token for a public command. The host provides `HttpClient` (`NodeHttpClient.layerUndici`) in [notes-service/src/cli.ts](../examples/notes-service/src/cli.ts).
|
|
46
46
|
|
|
47
47
|
- **Split one binding into groups of commands**, one `remote` per group with its own `actions`; what each group's `client` needs is on `ActionCli.Calling`'s `client`.
|
|
48
48
|
- **Test a remote command the same way** as a local one, with `Testing.layer(routes)` provided as its `HttpClient` ([Testing.md](Testing.md#test-routes-in-memory)). Export the command from a module apart from the entrypoint that runs it ([notes-service/test/commands.test.ts](../examples/notes-service/test/commands.test.ts)).
|
package/docs/ActionHttp.md
CHANGED
|
@@ -108,7 +108,7 @@ const server = Layer.unwrap(
|
|
|
108
108
|
Layer.launch(server).pipe(NodeRuntime.runMain());
|
|
109
109
|
```
|
|
110
110
|
|
|
111
|
-
- A service a verifier, handler or authorizer reads per request is provided by router middleware around the layer ([kitchen-sink/src/
|
|
111
|
+
- A service a verifier, handler or authorizer reads per request is provided by router middleware around the layer ([kitchen-sink/src/identity/workspace-header.ts](../examples/kitchen-sink/src/identity/workspace-header.ts), read by the verifier, provided in [kitchen-sink/src/routes.ts](../examples/kitchen-sink/src/routes.ts)), or, for a handler or authorizer, by `ActionHttp.LayerOptions.middleware`; declaring it, and why not `HttpRouter.provideRequest`, are on `ActionHttp.layer`.
|
|
112
112
|
|
|
113
113
|
### Split a binding across layers, and add middleware
|
|
114
114
|
|
package/docs/ActionRpc.md
CHANGED
|
@@ -185,10 +185,6 @@ import { RpcMiddleware } from "effect/rpc";
|
|
|
185
185
|
|
|
186
186
|
import { defaultRoom, roomHeader } from "./Chat.js";
|
|
187
187
|
|
|
188
|
-
/**
|
|
189
|
-
* The room a message is about. A request-time service: handlers and `authorize` read it per
|
|
190
|
-
* call, and it has no Layer, because no one value of it is right for a whole server.
|
|
191
|
-
*/
|
|
192
188
|
export class CurrentRoom extends Context.Service<CurrentRoom, string>()(
|
|
193
189
|
"live-rpc/CurrentRoom"
|
|
194
190
|
) {}
|
|
@@ -6,30 +6,27 @@ A message the library throws says its fix; for a compiler diagnostic or Effect's
|
|
|
6
6
|
|
|
7
7
|
## Read request context in a verifier
|
|
8
8
|
|
|
9
|
-
A verifier may read per-request services: the request, or one of your own, such as the
|
|
9
|
+
A verifier may read per-request services: the request, or one of your own, such as the workspace a request's header names, which native router middleware provides:
|
|
10
10
|
|
|
11
|
-
```ts example=kitchen-sink/src/
|
|
11
|
+
```ts example=kitchen-sink/src/identity/workspace-header.ts
|
|
12
12
|
import { Context, Effect, Option } from "effect";
|
|
13
13
|
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
export
|
|
21
|
-
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
route,
|
|
29
|
-
Tenant,
|
|
30
|
-
Option.fromNullishOr(request.headers["x-workspace"])
|
|
31
|
-
)
|
|
15
|
+
export class WorkspaceHeader extends Context.Service<
|
|
16
|
+
WorkspaceHeader,
|
|
17
|
+
Option.Option<string>
|
|
18
|
+
>()("tracker/WorkspaceHeader") {}
|
|
19
|
+
|
|
20
|
+
export const readWorkspaceHeader = HttpRouter.middleware<{
|
|
21
|
+
provides: WorkspaceHeader;
|
|
22
|
+
}>()((route) =>
|
|
23
|
+
Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) =>
|
|
24
|
+
Effect.provideService(
|
|
25
|
+
route,
|
|
26
|
+
WorkspaceHeader,
|
|
27
|
+
Option.fromNullishOr(request.headers["x-workspace"])
|
|
32
28
|
)
|
|
29
|
+
)
|
|
33
30
|
);
|
|
34
31
|
```
|
|
35
32
|
|
|
@@ -8,7 +8,7 @@ What you see when something is wrong, and the fix: compiler diagnostics and erro
|
|
|
8
8
|
- `Property 'authentication' is missing`, or `No overload matches this call` with `"Protected actions take options naming their authentication"` or `"Authentication descriptor does not cover every protected action"`, at `ActionHttp.make`, `ActionRpc.make` or `ActionMcp.layerHttp`: a protected action is served and no descriptor is named. Give `{ authentication: Login }` ([Declare how callers sign in](Authentication.md#declare-how-callers-sign-in)).
|
|
9
9
|
- `Type 'Other' is not assignable to type 'CurrentUser'` under `Descriptor<…>`, at `authentication`: the descriptor authenticates another identity than the action's `caller`. Name the descriptor made for the caller's identity service.
|
|
10
10
|
- `is not assignable to type 'Forbidden | Unauthenticated'`, or `Property '…' is missing in type`, at `layer`'s verifier: it fails with an error that is neither a refusal nor one its descriptor declares, or succeeds with a value that is not the identity. Declare the error in the descriptor's `error`, or map it to a refusal where it is the caller's.
|
|
11
|
-
- `Request<"Requires",
|
|
11
|
+
- `Request<"Requires", WorkspaceHeader>` still owed although its middleware's layer is provided: it is in one `Layer.provide([...])` array with the provider, and an array's layers provide to the routes, not to one another. Provide it in a later `Layer.provide` of its own ([Read request context in a verifier](Authentication-advanced.md#read-request-context-in-a-verifier)).
|
|
12
12
|
|
|
13
13
|
## Signing in
|
|
14
14
|
|
package/docs/Authentication.md
CHANGED
|
@@ -22,10 +22,6 @@ export interface User {
|
|
|
22
22
|
readonly scopes: ReadonlyArray<typeof Scope.Type>;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
/**
|
|
26
|
-
* Who is calling. A protected action declares it, `caller: CurrentUser`; authentication
|
|
27
|
-
* provides it per request, and a local host, such as the stdio server, provides it itself.
|
|
28
|
-
*/
|
|
29
25
|
export class CurrentUser extends Context.Service<CurrentUser, User>()(
|
|
30
26
|
"notes-service/CurrentUser"
|
|
31
27
|
) {}
|
package/docs/Webhook.md
CHANGED
|
@@ -218,23 +218,21 @@ import { Http } from "../Api.js";
|
|
|
218
218
|
import { BuildFinished } from "../builds/Builds.js";
|
|
219
219
|
import { Notices } from "./Notices.js";
|
|
220
220
|
|
|
221
|
-
/** Where build-events is, who the notifier signs in as there, and where it is reached itself. */
|
|
222
221
|
export interface NotifierOptions {
|
|
223
|
-
readonly
|
|
222
|
+
readonly buildEventsUrl: string;
|
|
224
223
|
readonly token: string | Redacted.Redacted;
|
|
225
|
-
/** This process's public https origin, which build-events POSTs to. */
|
|
226
224
|
readonly publicUrl: string;
|
|
227
225
|
}
|
|
228
226
|
|
|
229
227
|
const receiver = Webhook.layerReceiver({ path: "/hooks/builds" });
|
|
230
228
|
|
|
231
|
-
const watcher = ({
|
|
229
|
+
const watcher = ({ buildEventsUrl, token, publicUrl }: NotifierOptions) =>
|
|
232
230
|
Layer.effectDiscard(
|
|
233
231
|
Effect.gen(function* () {
|
|
234
232
|
const notices = yield* Notices;
|
|
235
233
|
|
|
236
234
|
const builds = yield* ActionHttp.client(Http, {
|
|
237
|
-
baseUrl:
|
|
235
|
+
baseUrl: buildEventsUrl,
|
|
238
236
|
transformClient: HttpClient.mapRequest(
|
|
239
237
|
HttpClientRequest.bearerToken(token)
|
|
240
238
|
),
|
|
@@ -265,7 +263,6 @@ const watcher = ({ buildEvents, token, publicUrl }: NotifierOptions) =>
|
|
|
265
263
|
})
|
|
266
264
|
);
|
|
267
265
|
|
|
268
|
-
/** The notifier's routes: the receiver, and the watch reading from that same receiver. */
|
|
269
266
|
export const notifier = (options: NotifierOptions) =>
|
|
270
267
|
watcher(options).pipe(Layer.provideMerge(receiver));
|
|
271
268
|
```
|
|
@@ -9,23 +9,21 @@ import { Http } from "../Api.js";
|
|
|
9
9
|
import { BuildFinished } from "../builds/Builds.js";
|
|
10
10
|
import { Notices } from "./Notices.js";
|
|
11
11
|
|
|
12
|
-
/** Where build-events is, who the notifier signs in as there, and where it is reached itself. */
|
|
13
12
|
export interface NotifierOptions {
|
|
14
|
-
readonly
|
|
13
|
+
readonly buildEventsUrl: string;
|
|
15
14
|
readonly token: string | Redacted.Redacted;
|
|
16
|
-
/** This process's public https origin, which build-events POSTs to. */
|
|
17
15
|
readonly publicUrl: string;
|
|
18
16
|
}
|
|
19
17
|
|
|
20
18
|
const receiver = Webhook.layerReceiver({ path: "/hooks/builds" });
|
|
21
19
|
|
|
22
|
-
const watcher = ({
|
|
20
|
+
const watcher = ({ buildEventsUrl, token, publicUrl }: NotifierOptions) =>
|
|
23
21
|
Layer.effectDiscard(
|
|
24
22
|
Effect.gen(function* () {
|
|
25
23
|
const notices = yield* Notices;
|
|
26
24
|
|
|
27
25
|
const builds = yield* ActionHttp.client(Http, {
|
|
28
|
-
baseUrl:
|
|
26
|
+
baseUrl: buildEventsUrl,
|
|
29
27
|
transformClient: HttpClient.mapRequest(
|
|
30
28
|
HttpClientRequest.bearerToken(token)
|
|
31
29
|
),
|
|
@@ -56,6 +54,5 @@ const watcher = ({ buildEvents, token, publicUrl }: NotifierOptions) =>
|
|
|
56
54
|
})
|
|
57
55
|
);
|
|
58
56
|
|
|
59
|
-
/** The notifier's routes: the receiver, and the watch reading from that same receiver. */
|
|
60
57
|
export const notifier = (options: NotifierOptions) =>
|
|
61
58
|
watcher(options).pipe(Layer.provideMerge(receiver));
|
|
@@ -10,7 +10,7 @@ import { notifier } from "./notifier/routes.js";
|
|
|
10
10
|
|
|
11
11
|
const server = Layer.unwrap(
|
|
12
12
|
Effect.gen(function* () {
|
|
13
|
-
const
|
|
13
|
+
const buildEventsUrl = yield* Config.String("BUILDS_URL").pipe(
|
|
14
14
|
Config.withDefault("http://127.0.0.1:3000")
|
|
15
15
|
);
|
|
16
16
|
|
|
@@ -23,7 +23,9 @@ const server = Layer.unwrap(
|
|
|
23
23
|
|
|
24
24
|
const port = yield* Config.Port("PORT").pipe(Config.withDefault(3001));
|
|
25
25
|
|
|
26
|
-
return HttpRouter.serve(
|
|
26
|
+
return HttpRouter.serve(
|
|
27
|
+
notifier({ buildEventsUrl, token, publicUrl })
|
|
28
|
+
).pipe(
|
|
27
29
|
Layer.provide(NodeHttpServer.layer(createServer, { host, port })),
|
|
28
30
|
Layer.provide(
|
|
29
31
|
Layer.succeed(HttpServerRequest.MaxBodySize, ByteSize.kibibytes(256))
|
|
@@ -26,7 +26,7 @@ describe("the notifier, by webhook", () => {
|
|
|
26
26
|
);
|
|
27
27
|
|
|
28
28
|
const notifierRoutes = notifier({
|
|
29
|
-
|
|
29
|
+
buildEventsUrl: "http://build-events.internal",
|
|
30
30
|
token: "grace",
|
|
31
31
|
publicUrl: "https://hooks.example.com",
|
|
32
32
|
}).pipe(Layer.provide(handedOver));
|
|
@@ -56,11 +56,11 @@ src/
|
|
|
56
56
|
│ ├── authenticate.ts Authentication.layer for both descriptors, OAuth discovery
|
|
57
57
|
│ ├── authorize.ts the members' rule: readOnly to a scope
|
|
58
58
|
│ ├── quota.ts the request quota, as HTTP and as RPC middleware
|
|
59
|
+
│ ├── workspace-header.ts WorkspaceHeader, the X-Workspace header the bearer verifier reads, and its router middleware
|
|
59
60
|
│ └── handlers.ts
|
|
60
61
|
├── workspaces/ the tenants
|
|
61
62
|
│ ├── Workspaces.ts contract: Workspace, the public getStatus
|
|
62
63
|
│ ├── registry.ts WorkspaceRegistry: the workspaces and their suspension
|
|
63
|
-
│ ├── tenant.ts Tenant, and the router middleware that resolves it per request
|
|
64
64
|
│ └── handlers.ts
|
|
65
65
|
├── issues/
|
|
66
66
|
│ ├── Issues.ts contract: schemas, errors, five actions, exportIssues, issue.changed
|
|
@@ -119,7 +119,7 @@ test/
|
|
|
119
119
|
|
|
120
120
|
| To see | Read |
|
|
121
121
|
| --- | --- |
|
|
122
|
-
| How one request is authenticated, placed in a tenant, authorized | `src/identity/authenticate.ts`, `src/
|
|
122
|
+
| How one request is authenticated, placed in a tenant, authorized | `src/identity/authenticate.ts`, `src/identity/workspace-header.ts`, `src/identity/authorize.ts`, `src/routes.ts` |
|
|
123
123
|
| Two audiences on two ports over one set of services | `src/server.ts`, `src/routes.ts`, `test/routes.test.ts` |
|
|
124
124
|
| Which actions each surface serves, and why one is no tool | `src/Actions.ts` |
|
|
125
125
|
| A limit before decoding and a limit in the handlers | `src/identity/quota.ts`, `src/issues/write-limit.ts` |
|
|
@@ -176,7 +176,7 @@ Each export and option the example uses, and where. A symbol in parentheses is t
|
|
|
176
176
|
| `layer`, a plain verifier | `src/admin/authenticate.ts` |
|
|
177
177
|
| `layer`: `protectedResource`, an Effect over `Config` | `src/identity/authenticate.ts` (`protectedResource`) |
|
|
178
178
|
| `ProtectedResource` | `src/identity/authenticate.ts` |
|
|
179
|
-
| A request service the verifier reads, and its order | `src/
|
|
179
|
+
| A request service the verifier reads, and its order | `src/identity/workspace-header.ts`, `src/routes.ts` (`publicRoutes`) |
|
|
180
180
|
| `protect`, a route of the host's own, by the cookie descriptor | `src/attachments/download.ts` |
|
|
181
181
|
| A trusted identity no verifier returns | `src/admin/Admin.ts`, `src/admin/authenticate.ts`, `src/ops.ts` |
|
|
182
182
|
| A verifier's declared error over MCP | `test/identity/identity.test.ts` |
|
|
@@ -5,10 +5,10 @@ import type { Redacted } from "effect";
|
|
|
5
5
|
|
|
6
6
|
import { publicUrl } from "../config.js";
|
|
7
7
|
import { WorkspaceRegistry } from "../workspaces/registry.js";
|
|
8
|
-
import { Tenant } from "../workspaces/tenant.js";
|
|
9
8
|
import { Directory } from "./directory.js";
|
|
10
9
|
import { Login, scopes, Session } from "./Identity.js";
|
|
11
10
|
import type { Member } from "./Identity.js";
|
|
11
|
+
import { WorkspaceHeader } from "./workspace-header.js";
|
|
12
12
|
|
|
13
13
|
const inService = Effect.gen(function* () {
|
|
14
14
|
const registry = yield* WorkspaceRegistry;
|
|
@@ -53,7 +53,7 @@ export const authenticateBearer = Authentication.layer(
|
|
|
53
53
|
Effect.gen(function* () {
|
|
54
54
|
const memberships = yield* directory.ofToken(token);
|
|
55
55
|
|
|
56
|
-
const member = Option.flatMap(yield*
|
|
56
|
+
const member = Option.flatMap(yield* WorkspaceHeader, (slug) =>
|
|
57
57
|
Array.findFirst(memberships, ({ workspace }) => workspace === slug)
|
|
58
58
|
);
|
|
59
59
|
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Context, Effect, Option } from "effect";
|
|
2
|
+
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
3
|
+
|
|
4
|
+
export class WorkspaceHeader extends Context.Service<
|
|
5
|
+
WorkspaceHeader,
|
|
6
|
+
Option.Option<string>
|
|
7
|
+
>()("tracker/WorkspaceHeader") {}
|
|
8
|
+
|
|
9
|
+
export const readWorkspaceHeader = HttpRouter.middleware<{
|
|
10
|
+
provides: WorkspaceHeader;
|
|
11
|
+
}>()((route) =>
|
|
12
|
+
Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) =>
|
|
13
|
+
Effect.provideService(
|
|
14
|
+
route,
|
|
15
|
+
WorkspaceHeader,
|
|
16
|
+
Option.fromNullishOr(request.headers["x-workspace"])
|
|
17
|
+
)
|
|
18
|
+
)
|
|
19
|
+
);
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
import { identity } from "./identity/handlers.js";
|
|
23
23
|
import { Login } from "./identity/Identity.js";
|
|
24
24
|
import { HttpQuota, quota, RpcQuota } from "./identity/quota.js";
|
|
25
|
+
import { readWorkspaceHeader } from "./identity/workspace-header.js";
|
|
25
26
|
import { layer as assistantTools } from "./issues/assistant.js";
|
|
26
27
|
import { issueEvents } from "./issues/events.js";
|
|
27
28
|
import { exports } from "./issues/export.js";
|
|
@@ -31,7 +32,6 @@ import { IssueChanged } from "./issues/Issues.js";
|
|
|
31
32
|
import { cors, requestPolicy } from "./request-policy.js";
|
|
32
33
|
import { Rpc } from "./Rpc.js";
|
|
33
34
|
import { status } from "./workspaces/handlers.js";
|
|
34
|
-
import { resolveTenant } from "./workspaces/tenant.js";
|
|
35
35
|
import { GetStatus } from "./workspaces/Workspaces.js";
|
|
36
36
|
|
|
37
37
|
const implementations = [
|
|
@@ -91,7 +91,7 @@ export const publicRoutes = Layer.mergeAll(
|
|
|
91
91
|
Layer.provide(Webhook.layer()),
|
|
92
92
|
Layer.provide(assistantTools),
|
|
93
93
|
Layer.provide([authenticateBearer, authenticateSession, quota]),
|
|
94
|
-
Layer.provide(
|
|
94
|
+
Layer.provide(readWorkspaceHeader.layer),
|
|
95
95
|
Layer.provide(cors),
|
|
96
96
|
Layer.provide(requestPolicy)
|
|
97
97
|
);
|
|
@@ -3,10 +3,6 @@ import { RpcMiddleware } from "effect/rpc";
|
|
|
3
3
|
|
|
4
4
|
import { defaultRoom, roomHeader } from "./Chat.js";
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
* The room a message is about. A request-time service: handlers and `authorize` read it per
|
|
8
|
-
* call, and it has no Layer, because no one value of it is right for a whole server.
|
|
9
|
-
*/
|
|
10
6
|
export class CurrentRoom extends Context.Service<CurrentRoom, string>()(
|
|
11
7
|
"live-rpc/CurrentRoom"
|
|
12
8
|
) {}
|
|
@@ -11,10 +11,6 @@ export interface User {
|
|
|
11
11
|
readonly scopes: ReadonlyArray<typeof Scope.Type>;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
/**
|
|
15
|
-
* Who is calling. A protected action declares it, `caller: CurrentUser`; authentication
|
|
16
|
-
* provides it per request, and a local host, such as the stdio server, provides it itself.
|
|
17
|
-
*/
|
|
18
14
|
export class CurrentUser extends Context.Service<CurrentUser, User>()(
|
|
19
15
|
"notes-service/CurrentUser"
|
|
20
16
|
) {}
|
package/package.json
CHANGED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { Context, Effect, Option } from "effect";
|
|
2
|
-
import { HttpRouter, HttpServerRequest } from "effect/http";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* The workspace a request addresses, from its `X-Workspace` header. It is request context, not
|
|
6
|
-
* an identity: the verifier reads it to decide which of an account's memberships the caller
|
|
7
|
-
* acts in. Handlers never read it; they read the workspace of the authenticated member.
|
|
8
|
-
*/
|
|
9
|
-
export class Tenant extends Context.Service<Tenant, Option.Option<string>>()(
|
|
10
|
-
"tracker/Tenant"
|
|
11
|
-
) {}
|
|
12
|
-
|
|
13
|
-
export const resolveTenant = HttpRouter.middleware<{ provides: Tenant }>()(
|
|
14
|
-
(route) =>
|
|
15
|
-
Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) =>
|
|
16
|
-
Effect.provideService(
|
|
17
|
-
route,
|
|
18
|
-
Tenant,
|
|
19
|
-
Option.fromNullishOr(request.headers["x-workspace"])
|
|
20
|
-
)
|
|
21
|
-
)
|
|
22
|
-
);
|