@shivaedev/test-kits 0.5.0 → 0.8.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/CHANGELOG.md +19 -0
- package/README.md +20 -0
- package/dist/contract/settledQueries.d.ts +13 -0
- package/dist/contract/settledQueries.d.ts.map +1 -0
- package/dist/contract/settledQueries.js +20 -0
- package/dist/contract/settledQueries.js.map +1 -0
- package/dist/host/ProcessError.d.ts +10 -0
- package/dist/host/ProcessError.d.ts.map +1 -0
- package/dist/host/ProcessError.js +4 -0
- package/dist/host/ProcessError.js.map +1 -0
- package/dist/host/adapters/process.d.ts +24 -0
- package/dist/host/adapters/process.d.ts.map +1 -0
- package/dist/host/adapters/process.js +111 -0
- package/dist/host/adapters/process.js.map +1 -0
- package/dist/host/adapters/processReadouts.d.ts +10 -0
- package/dist/host/adapters/processReadouts.d.ts.map +1 -0
- package/dist/host/adapters/processReadouts.js +26 -0
- package/dist/host/adapters/processReadouts.js.map +1 -0
- package/dist/host/process.d.ts +26 -0
- package/dist/host/process.d.ts.map +1 -0
- package/dist/host/process.js +56 -0
- package/dist/host/process.js.map +1 -0
- package/dist/host/processChild.d.ts +7 -0
- package/dist/host/processChild.d.ts.map +1 -0
- package/dist/host/processChild.js +19 -0
- package/dist/host/processChild.js.map +1 -0
- package/dist/host/processProtocol.d.ts +20 -0
- package/dist/host/processProtocol.d.ts.map +1 -0
- package/dist/host/processProtocol.js +11 -0
- package/dist/host/processProtocol.js.map +1 -0
- package/dist/host/processReadouts.d.ts +7 -0
- package/dist/host/processReadouts.d.ts.map +1 -0
- package/dist/host/processReadouts.js +37 -0
- package/dist/host/processReadouts.js.map +1 -0
- package/dist/host/time.d.ts +9 -0
- package/dist/host/time.d.ts.map +1 -0
- package/dist/host/time.js +27 -0
- package/dist/host/time.js.map +1 -0
- package/dist/identity/adapters/oauthAuthorization.d.ts +20 -0
- package/dist/identity/adapters/oauthAuthorization.d.ts.map +1 -0
- package/dist/identity/adapters/oauthAuthorization.js +39 -0
- package/dist/identity/adapters/oauthAuthorization.js.map +1 -0
- package/dist/identity/adapters/oauthProtocol.d.ts +9 -0
- package/dist/identity/adapters/oauthProtocol.d.ts.map +1 -0
- package/dist/identity/adapters/oauthProtocol.js +105 -0
- package/dist/identity/adapters/oauthProtocol.js.map +1 -0
- package/dist/identity/adapters/oidcTokens.d.ts +39 -0
- package/dist/identity/adapters/oidcTokens.d.ts.map +1 -0
- package/dist/identity/adapters/oidcTokens.js +39 -0
- package/dist/identity/adapters/oidcTokens.js.map +1 -0
- package/dist/identity/oauth.d.ts +43 -0
- package/dist/identity/oauth.d.ts.map +1 -0
- package/dist/identity/oauth.js +20 -0
- package/dist/identity/oauth.js.map +1 -0
- package/dist/jobs/adapters/testingClient.d.ts +1 -1
- package/dist/jobs/adapters/testingClient.d.ts.map +1 -1
- package/dist/jobs/adapters/testingController.d.ts.map +1 -1
- package/dist/jobs/adapters/testingController.js +5 -5
- package/dist/jobs/adapters/testingController.js.map +1 -1
- package/dist/jobs/adapters/testingDueNow.js +1 -1
- package/dist/jobs/adapters/testingDueNow.js.map +1 -1
- package/dist/jobs/adapters/testingFetches.d.ts.map +1 -0
- package/dist/jobs/adapters/testingFetches.js.map +1 -0
- package/dist/jobs/adapters/testingInspectionClient.d.ts +1 -1
- package/dist/jobs/adapters/testingInspectionClient.d.ts.map +1 -1
- package/dist/jobs/adapters/testingTime.js +1 -1
- package/dist/jobs/adapters/testingTime.js.map +1 -1
- package/dist/jobs/testingIdle.d.ts.map +1 -0
- package/dist/jobs/{internal/testingIdle.js → testingIdle.js} +1 -1
- package/dist/jobs/testingIdle.js.map +1 -0
- package/dist/jobs/testingOperation.d.ts.map +1 -0
- package/dist/jobs/testingOperation.js.map +1 -0
- package/dist/jobs/testingSchedules.d.ts.map +1 -0
- package/dist/jobs/{internal/testingSchedules.js → testingSchedules.js} +1 -1
- package/dist/jobs/testingSchedules.js.map +1 -0
- package/dist/jobs/{internal/testingWaits.d.ts → testingWaits.d.ts} +1 -1
- package/dist/jobs/testingWaits.d.ts.map +1 -0
- package/dist/jobs/{internal/testingWaits.js → testingWaits.js} +1 -1
- package/dist/jobs/testingWaits.js.map +1 -0
- package/dist/webhooks/adapters/githubHeaders.d.ts +5 -0
- package/dist/webhooks/adapters/githubHeaders.d.ts.map +1 -0
- package/dist/webhooks/adapters/githubHeaders.js +6 -0
- package/dist/webhooks/adapters/githubHeaders.js.map +1 -0
- package/dist/webhooks/deliver.d.ts +13 -0
- package/dist/webhooks/deliver.d.ts.map +1 -0
- package/dist/webhooks/deliver.js +20 -0
- package/dist/webhooks/deliver.js.map +1 -0
- package/package.json +15 -14
- package/src/contract/settledQueries.ts +39 -0
- package/src/host/ProcessError.ts +6 -0
- package/src/host/adapters/process.ts +122 -0
- package/src/host/adapters/processReadouts.ts +29 -0
- package/src/host/process.ts +69 -0
- package/src/host/processChild.ts +25 -0
- package/src/host/processProtocol.ts +11 -0
- package/src/host/processReadouts.ts +46 -0
- package/src/host/time.ts +33 -0
- package/src/identity/adapters/oauthAuthorization.ts +54 -0
- package/src/identity/adapters/oauthProtocol.ts +111 -0
- package/src/identity/adapters/oidcTokens.ts +42 -0
- package/src/identity/oauth.ts +35 -0
- package/src/jobs/adapters/testingClient.ts +1 -1
- package/src/jobs/adapters/testingController.ts +5 -5
- package/src/jobs/adapters/testingDueNow.ts +1 -1
- package/src/jobs/adapters/testingInspectionClient.ts +1 -1
- package/src/jobs/adapters/testingTime.ts +1 -1
- package/src/jobs/{internal/testingIdle.ts → testingIdle.ts} +1 -1
- package/src/jobs/{internal/testingSchedules.ts → testingSchedules.ts} +1 -1
- package/src/jobs/{internal/testingWaits.ts → testingWaits.ts} +2 -2
- package/src/webhooks/adapters/githubHeaders.ts +6 -0
- package/src/webhooks/deliver.ts +33 -0
- package/dist/jobs/internal/adapters/testingFetches.d.ts.map +0 -1
- package/dist/jobs/internal/adapters/testingFetches.js.map +0 -1
- package/dist/jobs/internal/testingIdle.d.ts.map +0 -1
- package/dist/jobs/internal/testingIdle.js.map +0 -1
- package/dist/jobs/internal/testingOperation.d.ts.map +0 -1
- package/dist/jobs/internal/testingOperation.js.map +0 -1
- package/dist/jobs/internal/testingSchedules.d.ts.map +0 -1
- package/dist/jobs/internal/testingSchedules.js.map +0 -1
- package/dist/jobs/internal/testingWaits.d.ts.map +0 -1
- package/dist/jobs/internal/testingWaits.js.map +0 -1
- /package/dist/jobs/{internal/adapters → adapters}/testingFetches.d.ts +0 -0
- /package/dist/jobs/{internal/adapters → adapters}/testingFetches.js +0 -0
- /package/dist/jobs/{internal/testingIdle.d.ts → testingIdle.d.ts} +0 -0
- /package/dist/jobs/{internal/testingOperation.d.ts → testingOperation.d.ts} +0 -0
- /package/dist/jobs/{internal/testingOperation.js → testingOperation.js} +0 -0
- /package/dist/jobs/{internal/testingSchedules.d.ts → testingSchedules.d.ts} +0 -0
- /package/src/jobs/{internal/adapters → adapters}/testingFetches.ts +0 -0
- /package/src/jobs/{internal/testingOperation.ts → testingOperation.ts} +0 -0
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { Effect, Redacted } from "effect";
|
|
3
|
+
export function githubHeaders(body, key) {
|
|
4
|
+
return Effect.sync(() => ({ "x-hub-signature-256": `sha256=${createHmac("sha256", Redacted.value(key)).update(body).digest("hex")}` }));
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=githubHeaders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"githubHeaders.js","sourceRoot":"","sources":["../../../src/webhooks/adapters/githubHeaders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAE1C,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,GAA8B;IACzE,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,qBAAqB,EAAE,UAAU,UAAU,CAAC,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AACzI,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Effect, type Redacted } from "effect";
|
|
2
|
+
import { HttpClient } from "effect/http";
|
|
3
|
+
import type { WebhookSource } from "@shivaedev/webhooks/server/registration.ts";
|
|
4
|
+
export type WebhookSigner<E = never, R = never> = (body: string, key: Redacted.Redacted<string>) => Effect.Effect<Readonly<Record<string, string>>, E, R>;
|
|
5
|
+
export interface WebhookDeliveryOptions<E = never, R = never> {
|
|
6
|
+
readonly body: string;
|
|
7
|
+
readonly headers?: Readonly<Record<string, string | null>>;
|
|
8
|
+
readonly sign?: WebhookSigner<E, R>;
|
|
9
|
+
readonly source: Pick<WebhookSource, "key">;
|
|
10
|
+
readonly url: string;
|
|
11
|
+
}
|
|
12
|
+
export declare const deliverWebhook: <E = never, R = never>(options: WebhookDeliveryOptions<E, R>) => Effect.Effect<import("effect/http/HttpClientResponse").HttpClientResponse, E | import("effect/Config").ConfigError | import("effect/http/HttpClientError").HttpClientError, R | HttpClient.HttpClient>;
|
|
13
|
+
//# sourceMappingURL=deliver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deliver.d.ts","sourceRoot":"","sources":["../../src/webhooks/deliver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAY,UAAU,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4CAA4C,CAAC;AAGhF,MAAM,MAAM,aAAa,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,KAAK,IAAI,CACjD,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,KAC1B,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AAE3D,MAAM,WAAW,sBAAsB,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,GAAG,KAAK;IAC3D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC;IAC3D,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IAC5C,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,cAAc,GAAgC,CAAC,UAAU,CAAC,0PAcrE,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { HttpBody, HttpClient } from "effect/http";
|
|
3
|
+
import { githubHeaders } from "#webhooks/adapters/githubHeaders.ts";
|
|
4
|
+
export const deliverWebhook = Effect.fnUntraced(function* (options) {
|
|
5
|
+
const key = yield* options.source.key;
|
|
6
|
+
const signed = yield* (options.sign ?? githubHeaders)(options.body, key);
|
|
7
|
+
const headers = {};
|
|
8
|
+
for (const [name, value] of [...Object.entries(signed), ...Object.entries(options.headers ?? {})]) {
|
|
9
|
+
const lower = name.toLowerCase();
|
|
10
|
+
if (value === null) {
|
|
11
|
+
delete headers[lower];
|
|
12
|
+
}
|
|
13
|
+
else {
|
|
14
|
+
headers[lower] = value;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const client = yield* HttpClient.HttpClient;
|
|
18
|
+
return yield* client.post(options.url, { body: HttpBody.text(options.body, "application/json"), headers });
|
|
19
|
+
});
|
|
20
|
+
//# sourceMappingURL=deliver.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deliver.js","sourceRoot":"","sources":["../../src/webhooks/deliver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEnD,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAepE,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAwB,OAAqC;IACrH,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC;IACtC,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,IAAI,aAAa,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACzE,MAAM,OAAO,GAA2B,EAAE,CAAC;IAC3C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC;QACnG,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACjC,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACpB,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;aAAM,CAAC;YACP,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;QACxB,CAAC;IACF,CAAC;IACD,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC;IAC5C,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,kBAAkB,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;AAC5G,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shivaedev/test-kits",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Reusable story building blocks for Platform applications",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"effect"
|
|
@@ -43,28 +43,29 @@
|
|
|
43
43
|
"README.md"
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@shivaedev/test-sql": "0.
|
|
47
|
-
"@shivaedev/test-story": "0.
|
|
46
|
+
"@shivaedev/test-sql": "0.24.0",
|
|
47
|
+
"@shivaedev/test-story": "0.42.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
|
-
"@shivaedev/github": "0.
|
|
51
|
-
"@shivaedev/quality": "0.
|
|
50
|
+
"@shivaedev/github": "0.14.0",
|
|
51
|
+
"@shivaedev/quality": "0.65.0",
|
|
52
52
|
"@types/node": "24.19.2",
|
|
53
53
|
"better-auth": "1.7.14",
|
|
54
|
-
"effect": "4.0
|
|
54
|
+
"effect": "4.1.0",
|
|
55
55
|
"typescript": "7.0.2",
|
|
56
56
|
"vitest": "5.0.5"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
|
-
"@shivaedev/changes": "0.
|
|
60
|
-
"@shivaedev/contract": "0.
|
|
61
|
-
"@shivaedev/discord": "0.
|
|
62
|
-
"@shivaedev/email": "0.
|
|
63
|
-
"@shivaedev/identity": "0.
|
|
64
|
-
"@shivaedev/jobs": "0.
|
|
65
|
-
"@shivaedev/sql": "0.
|
|
59
|
+
"@shivaedev/changes": "0.11.0",
|
|
60
|
+
"@shivaedev/contract": "0.39.0",
|
|
61
|
+
"@shivaedev/discord": "0.3.0",
|
|
62
|
+
"@shivaedev/email": "0.6.0",
|
|
63
|
+
"@shivaedev/identity": "0.27.0",
|
|
64
|
+
"@shivaedev/jobs": "0.39.0",
|
|
65
|
+
"@shivaedev/sql": "0.42.0",
|
|
66
|
+
"@shivaedev/webhooks": "0.11.0",
|
|
66
67
|
"better-auth": "1.7.14",
|
|
67
|
-
"effect": "4.0
|
|
68
|
+
"effect": "4.1.0",
|
|
68
69
|
"pg-boss": "12.38.0"
|
|
69
70
|
},
|
|
70
71
|
"engines": {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Effect, Queue } from "effect";
|
|
2
|
+
import type * as AsyncResult from "effect/reactivity/AsyncResult";
|
|
3
|
+
import type * as Atom from "effect/reactivity/Atom";
|
|
4
|
+
import * as AtomRegistry from "effect/reactivity/AtomRegistry";
|
|
5
|
+
import { querySignals } from "@shivaedev/contract/querySignals.ts";
|
|
6
|
+
|
|
7
|
+
export interface SettledQueries<A, E> {
|
|
8
|
+
readonly latest: Effect.Effect<AsyncResult.AsyncResult<A, E>>;
|
|
9
|
+
readonly next: Effect.Effect<AsyncResult.AsyncResult<A, E>>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const settledQueries = Effect.fn("Contract.settledQueries")(function* <A, E>(query: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
|
|
13
|
+
const registry = yield* AtomRegistry.AtomRegistry;
|
|
14
|
+
const results = yield* Queue.unbounded<AsyncResult.AsyncResult<A, E>>();
|
|
15
|
+
let completed = 0;
|
|
16
|
+
yield* Effect.acquireRelease(
|
|
17
|
+
Effect.sync(() => registry.mount(query)),
|
|
18
|
+
(stop) => Effect.sync(stop),
|
|
19
|
+
);
|
|
20
|
+
yield* Effect.acquireRelease(
|
|
21
|
+
Effect.sync(() =>
|
|
22
|
+
registry.subscribe(
|
|
23
|
+
querySignals(query),
|
|
24
|
+
(state) => {
|
|
25
|
+
if (!state.pending && state.completed > completed) {
|
|
26
|
+
completed = state.completed;
|
|
27
|
+
Queue.offerUnsafe(results, registry.get(query));
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
{ immediate: true },
|
|
31
|
+
),
|
|
32
|
+
),
|
|
33
|
+
(stop) => Effect.sync(stop),
|
|
34
|
+
);
|
|
35
|
+
return {
|
|
36
|
+
latest: Effect.sync(() => registry.get(query)),
|
|
37
|
+
next: Queue.take(results),
|
|
38
|
+
} satisfies SettledQueries<A, E>;
|
|
39
|
+
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { type ChildProcess, type ForkOptions, fork } from "node:child_process";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { Option, type Redacted, Schema } from "effect";
|
|
5
|
+
|
|
6
|
+
export interface HostProcessOptions {
|
|
7
|
+
readonly args?: readonly string[];
|
|
8
|
+
readonly cwd?: string;
|
|
9
|
+
readonly databaseUrl?: Redacted.Redacted<string>;
|
|
10
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
11
|
+
readonly execArgv?: readonly string[];
|
|
12
|
+
readonly module: string | URL;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function forkHost(options: HostProcessOptions, databaseUrl?: string) {
|
|
16
|
+
const settings: ForkOptions = {
|
|
17
|
+
cwd: options.cwd,
|
|
18
|
+
env: databaseUrl === undefined ? options.env : { ...options.env, "DATABASE_URL": databaseUrl },
|
|
19
|
+
execArgv: [...(options.execArgv ?? [])],
|
|
20
|
+
stdio: ["ignore", "ignore", "inherit", "ipc"],
|
|
21
|
+
};
|
|
22
|
+
return fork(typeof options.module === "string" ? options.module : fileURLToPath(options.module), [...(options.args ?? [])], settings);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function receiveHostMessage<A>(child: ChildProcess, schema: Schema.Codec<A>, signal: AbortSignal, action?: () => void) {
|
|
26
|
+
return new Promise<A>((resolve, reject) => {
|
|
27
|
+
function cleanup() {
|
|
28
|
+
child.off("message", message);
|
|
29
|
+
child.off("exit", exited);
|
|
30
|
+
child.off("error", failed);
|
|
31
|
+
signal.removeEventListener("abort", aborted);
|
|
32
|
+
}
|
|
33
|
+
function failed(cause: unknown) {
|
|
34
|
+
cleanup();
|
|
35
|
+
reject(cause);
|
|
36
|
+
}
|
|
37
|
+
function exited(code: number | null, delivered: NodeJS.Signals | null) {
|
|
38
|
+
failed(new Error(`Host exited (${delivered ?? code}) before IPC acknowledgement`));
|
|
39
|
+
}
|
|
40
|
+
function aborted() {
|
|
41
|
+
failed(signal.reason);
|
|
42
|
+
}
|
|
43
|
+
function message(value: unknown) {
|
|
44
|
+
const decoded = Schema.decodeUnknownOption(schema)(value);
|
|
45
|
+
if (Option.isSome(decoded)) {
|
|
46
|
+
cleanup();
|
|
47
|
+
resolve(decoded.value);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
child.on("message", message);
|
|
51
|
+
child.once("exit", exited);
|
|
52
|
+
child.once("error", failed);
|
|
53
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
54
|
+
if (signal.aborted) {
|
|
55
|
+
aborted();
|
|
56
|
+
} else if (child.exitCode !== null || child.signalCode !== null) {
|
|
57
|
+
exited(child.exitCode, child.signalCode);
|
|
58
|
+
} else {
|
|
59
|
+
try {
|
|
60
|
+
action?.();
|
|
61
|
+
} catch (cause) {
|
|
62
|
+
failed(cause);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function stopHost(child: ChildProcess) {
|
|
69
|
+
if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) {
|
|
70
|
+
return Promise.resolve();
|
|
71
|
+
}
|
|
72
|
+
return new Promise<void>((resolve) => {
|
|
73
|
+
child.once("exit", () => resolve());
|
|
74
|
+
child.kill("SIGKILL");
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function sendHostMessage(message: unknown) {
|
|
79
|
+
return new Promise<void>((resolve, reject) => {
|
|
80
|
+
if (process.send === undefined) {
|
|
81
|
+
reject(new Error("Host process needs a parent IPC channel"));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
process.send(message, (error) => (error === null ? resolve() : reject(error)));
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function sendHostReady(url: string) {
|
|
89
|
+
return sendHostMessage({ pid: process.pid, type: "host-ready", url });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function waitForHostStart(signal: AbortSignal) {
|
|
93
|
+
return new Promise<void>((resolve, reject) => {
|
|
94
|
+
function cleanup() {
|
|
95
|
+
process.off("SIGUSR2", start);
|
|
96
|
+
signal.removeEventListener("abort", aborted);
|
|
97
|
+
}
|
|
98
|
+
function failed(cause: unknown) {
|
|
99
|
+
cleanup();
|
|
100
|
+
reject(cause);
|
|
101
|
+
}
|
|
102
|
+
function start() {
|
|
103
|
+
cleanup();
|
|
104
|
+
resolve();
|
|
105
|
+
}
|
|
106
|
+
function aborted() {
|
|
107
|
+
failed(signal.reason);
|
|
108
|
+
}
|
|
109
|
+
process.once("SIGUSR2", start);
|
|
110
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
111
|
+
if (signal.aborted) {
|
|
112
|
+
aborted();
|
|
113
|
+
} else {
|
|
114
|
+
void sendHostMessage({ type: "host-prepared" }).catch(failed);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function hostResponse(url: string, path: string, signal: AbortSignal) {
|
|
120
|
+
const response = await fetch(new URL(path, url), { redirect: "manual", signal });
|
|
121
|
+
return { body: await response.text(), headers: Object.fromEntries(response.headers), status: response.status };
|
|
122
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ChildProcess } from "node:child_process";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { Option, Predicate, Schema } from "effect";
|
|
4
|
+
import { HostReadouts } from "#host/processProtocol.ts";
|
|
5
|
+
import { receiveHostMessage } from "./process.ts";
|
|
6
|
+
|
|
7
|
+
export function listenHostReadouts(read: () => typeof HostReadouts.Type) {
|
|
8
|
+
function requested(message: unknown) {
|
|
9
|
+
if (Predicate.hasProperty(message, "type") && message.type === "host-readouts") {
|
|
10
|
+
process.send?.(read());
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
process.on("message", requested);
|
|
14
|
+
return () => process.off("message", requested);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function collectHostReadouts(child: ChildProcess) {
|
|
18
|
+
let completed: typeof HostReadouts.Type | undefined;
|
|
19
|
+
child.on("message", (message: unknown) => {
|
|
20
|
+
const decoded = Schema.decodeUnknownOption(HostReadouts)(message);
|
|
21
|
+
if (Option.isSome(decoded) && decoded.value.shutdownDuration !== null) {
|
|
22
|
+
completed = decoded.value;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
return (signal: AbortSignal) =>
|
|
26
|
+
completed === undefined
|
|
27
|
+
? receiveHostMessage(child, HostReadouts, signal, () => child.send({ type: "host-readouts" }))
|
|
28
|
+
: Promise.resolve(completed);
|
|
29
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Effect, Redacted, Schema } from "effect";
|
|
2
|
+
import { forkHost, type HostProcessOptions, hostResponse, receiveHostMessage, stopHost } from "#host/adapters/process.ts";
|
|
3
|
+
import { collectHostReadouts } from "#host/adapters/processReadouts.ts";
|
|
4
|
+
import { HostProcessError } from "./ProcessError.ts";
|
|
5
|
+
import { HostPrepared, HostReady, HostSignal } from "./processProtocol.ts";
|
|
6
|
+
|
|
7
|
+
export const hostProcess = Effect.fn("HostProcess.hostProcess")(function* <E = never, R = never>(
|
|
8
|
+
options: HostProcessOptions & { readonly beforeStart?: Effect.Effect<void, E, R> },
|
|
9
|
+
) {
|
|
10
|
+
const databaseUrl = options.databaseUrl;
|
|
11
|
+
const database =
|
|
12
|
+
databaseUrl === undefined
|
|
13
|
+
? undefined
|
|
14
|
+
: yield* Effect.promise(() => import("@shivaedev/test-sql/server/disconnectProxy.ts")).pipe(
|
|
15
|
+
Effect.flatMap(({ disconnectProxy }) => disconnectProxy(Redacted.value(databaseUrl))),
|
|
16
|
+
);
|
|
17
|
+
const child = yield* Effect.acquireRelease(
|
|
18
|
+
Effect.try({ catch: (cause) => new HostProcessError({ cause, operation: "launch" }), try: () => forkHost(options, database?.url) }),
|
|
19
|
+
(acquired) => Effect.promise(() => stopHost(acquired)),
|
|
20
|
+
);
|
|
21
|
+
const read = collectHostReadouts(child);
|
|
22
|
+
if (options.beforeStart !== undefined) {
|
|
23
|
+
yield* Effect.tryPromise({
|
|
24
|
+
catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
|
|
25
|
+
try: (signal) => receiveHostMessage(child, HostPrepared, signal),
|
|
26
|
+
});
|
|
27
|
+
yield* options.beforeStart;
|
|
28
|
+
}
|
|
29
|
+
const { pid, url } = yield* Effect.tryPromise({
|
|
30
|
+
catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
|
|
31
|
+
try: (signal) => receiveHostMessage(child, HostReady, signal, options.beforeStart === undefined ? undefined : () => child.kill("SIGUSR2")),
|
|
32
|
+
});
|
|
33
|
+
function response(path: string) {
|
|
34
|
+
return Effect.tryPromise({
|
|
35
|
+
catch: (cause) => new HostProcessError({ cause, operation: "request" }),
|
|
36
|
+
try: (signal) => hostResponse(url, path, signal),
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function readouts() {
|
|
40
|
+
return Effect.tryPromise({
|
|
41
|
+
catch: (cause) => new HostProcessError({ cause, operation: "readout" }),
|
|
42
|
+
try: read,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
activeWork: () => readouts().pipe(Effect.map((state) => state.activeWork)),
|
|
47
|
+
disconnectIdlePostgres: () =>
|
|
48
|
+
Effect.suspend(() =>
|
|
49
|
+
database === undefined
|
|
50
|
+
? Effect.die(new Error("Launch the host with databaseUrl before disconnecting PostgreSQL"))
|
|
51
|
+
: Effect.sync(database.disconnect),
|
|
52
|
+
),
|
|
53
|
+
finalizers: () => readouts().pipe(Effect.map((state) => state.finalizers)),
|
|
54
|
+
headers: (path: string) => response(path).pipe(Effect.map((answer) => answer.headers)),
|
|
55
|
+
health: () => response("/health"),
|
|
56
|
+
pid,
|
|
57
|
+
shutdownDuration: () => readouts().pipe(Effect.map((state) => state.shutdownDuration)),
|
|
58
|
+
signal: (delivered: NodeJS.Signals) =>
|
|
59
|
+
Effect.tryPromise({
|
|
60
|
+
catch: (cause) => new HostProcessError({ cause, operation: "signal" }),
|
|
61
|
+
try: (signal) =>
|
|
62
|
+
receiveHostMessage(child, HostSignal.pipe(Schema.check(Schema.makeFilter((ack) => ack.signal === delivered))), signal, () => {
|
|
63
|
+
child.kill(delivered);
|
|
64
|
+
}),
|
|
65
|
+
}).pipe(Effect.asVoid),
|
|
66
|
+
stop: () => Effect.promise(() => stopHost(child)),
|
|
67
|
+
url,
|
|
68
|
+
};
|
|
69
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { HttpServer } from "effect/http";
|
|
3
|
+
import { sendHostMessage, sendHostReady, waitForHostStart } from "#host/adapters/process.ts";
|
|
4
|
+
import { HostProcessError } from "#host/ProcessError.ts";
|
|
5
|
+
|
|
6
|
+
export const awaitHostStart = Effect.tryPromise({
|
|
7
|
+
catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
|
|
8
|
+
try: waitForHostStart,
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
export const reportHostReady = HttpServer.HttpServer.pipe(
|
|
12
|
+
Effect.flatMap((server) =>
|
|
13
|
+
Effect.tryPromise({
|
|
14
|
+
catch: (cause) => new HostProcessError({ cause, operation: "launch" }),
|
|
15
|
+
try: () => sendHostReady(HttpServer.formatAddress(server.address)),
|
|
16
|
+
}),
|
|
17
|
+
),
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
export function acknowledgeHostSignal(signal: NodeJS.Signals) {
|
|
21
|
+
return Effect.tryPromise({
|
|
22
|
+
catch: (cause) => new HostProcessError({ cause, operation: "signal" }),
|
|
23
|
+
try: () => sendHostMessage({ signal, type: "host-signal" }),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
|
|
3
|
+
export const HostReady = Schema.Struct({ pid: Schema.Number, type: Schema.Literal("host-ready"), url: Schema.String });
|
|
4
|
+
export const HostPrepared = Schema.Struct({ type: Schema.Literal("host-prepared") });
|
|
5
|
+
export const HostSignal = Schema.Struct({ signal: Schema.String, type: Schema.Literal("host-signal") });
|
|
6
|
+
export const HostReadouts = Schema.Struct({
|
|
7
|
+
activeWork: Schema.Array(Schema.String),
|
|
8
|
+
finalizers: Schema.Array(Schema.String),
|
|
9
|
+
shutdownDuration: Schema.NullOr(Schema.Number),
|
|
10
|
+
type: Schema.Literal("host-readouts"),
|
|
11
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Clock, Duration, Effect } from "effect";
|
|
2
|
+
import { sendHostMessage } from "#host/adapters/process.ts";
|
|
3
|
+
import { listenHostReadouts } from "#host/adapters/processReadouts.ts";
|
|
4
|
+
import { HostProcessError } from "./ProcessError.ts";
|
|
5
|
+
|
|
6
|
+
export const hostProcessReadouts = Effect.gen(function* () {
|
|
7
|
+
const active = new Map<symbol, string>();
|
|
8
|
+
const finalizers: string[] = [];
|
|
9
|
+
let shutdownDuration: number | null = null;
|
|
10
|
+
let shutdownWork: readonly string[] | undefined;
|
|
11
|
+
function read() {
|
|
12
|
+
return { activeWork: shutdownWork ?? [...active.values()], finalizers: [...finalizers], shutdownDuration, type: "host-readouts" as const };
|
|
13
|
+
}
|
|
14
|
+
function finishShutdown(started: bigint) {
|
|
15
|
+
return Effect.gen(function* () {
|
|
16
|
+
shutdownDuration = Duration.toMillis(Duration.nanos((yield* Clock.currentTimeNanos) - started));
|
|
17
|
+
yield* Effect.tryPromise({
|
|
18
|
+
catch: (cause) => new HostProcessError({ cause, operation: "readout" }),
|
|
19
|
+
try: () => sendHostMessage(read()),
|
|
20
|
+
}).pipe(Effect.orDie);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
yield* Effect.acquireRelease(
|
|
24
|
+
Effect.sync(() => listenHostReadouts(read)),
|
|
25
|
+
(close) => Effect.sync(close),
|
|
26
|
+
);
|
|
27
|
+
return {
|
|
28
|
+
finalizer: <A, E, R>(name: string, effect: Effect.Effect<A, E, R>) => effect.pipe(Effect.ensuring(Effect.sync(() => finalizers.push(name)))),
|
|
29
|
+
shutdown: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
|
30
|
+
Effect.gen(function* () {
|
|
31
|
+
shutdownWork = [...active.values()];
|
|
32
|
+
const started = yield* Clock.currentTimeNanos;
|
|
33
|
+
return yield* effect.pipe(Effect.ensuring(finishShutdown(started)));
|
|
34
|
+
}),
|
|
35
|
+
work: <A, E, R>(name: string, effect: Effect.Effect<A, E, R>) =>
|
|
36
|
+
Effect.acquireUseRelease(
|
|
37
|
+
Effect.sync(() => {
|
|
38
|
+
const id = Symbol(name);
|
|
39
|
+
active.set(id, name);
|
|
40
|
+
return id;
|
|
41
|
+
}),
|
|
42
|
+
() => effect,
|
|
43
|
+
(id) => Effect.sync(() => active.delete(id)),
|
|
44
|
+
),
|
|
45
|
+
};
|
|
46
|
+
});
|
package/src/host/time.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Duration, Effect, Layer } from "effect";
|
|
2
|
+
import { TestClock } from "effect/testing";
|
|
3
|
+
import { WorkerReleaseClock } from "@shivaedev/sql/WorkerReleaseClock.ts";
|
|
4
|
+
|
|
5
|
+
export const hostTime = Effect.fn("HostTime.hostTime")(function* () {
|
|
6
|
+
const clock = yield* TestClock.testClockWith(Effect.succeed);
|
|
7
|
+
const ticks = new Set<Parameters<typeof WorkerReleaseClock.Service.register>[0]>();
|
|
8
|
+
return {
|
|
9
|
+
layer: Layer.succeed(WorkerReleaseClock, {
|
|
10
|
+
clock,
|
|
11
|
+
register: (tick) =>
|
|
12
|
+
Effect.acquireRelease(
|
|
13
|
+
Effect.sync(() => {
|
|
14
|
+
ticks.add(tick);
|
|
15
|
+
}),
|
|
16
|
+
() =>
|
|
17
|
+
Effect.sync(() => {
|
|
18
|
+
ticks.delete(tick);
|
|
19
|
+
}),
|
|
20
|
+
).pipe(Effect.asVoid),
|
|
21
|
+
}),
|
|
22
|
+
timePasses: (duration: Duration.Input, options?: { readonly poll?: boolean }) =>
|
|
23
|
+
Effect.gen(function* () {
|
|
24
|
+
yield* clock.adjust(duration);
|
|
25
|
+
for (const tick of ticks) {
|
|
26
|
+
yield* tick.heartbeat;
|
|
27
|
+
if (options?.poll !== false) {
|
|
28
|
+
yield* tick.poll;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}),
|
|
32
|
+
};
|
|
33
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { FakeHttpReply, FakeHttpRequest } from "@shivaedev/test-story/server/fakeHttpService.ts";
|
|
3
|
+
import type { OauthProfile } from "#identity/oauth.ts";
|
|
4
|
+
|
|
5
|
+
export interface OauthCode {
|
|
6
|
+
readonly expires: number;
|
|
7
|
+
readonly profile: OauthProfile;
|
|
8
|
+
readonly query: URLSearchParams;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface OauthProtocolOptions {
|
|
12
|
+
readonly clientId: string;
|
|
13
|
+
readonly clientSecret: string;
|
|
14
|
+
readonly codeLifetime: number;
|
|
15
|
+
readonly now: () => number;
|
|
16
|
+
readonly profile: OauthProfile | ((request: FakeHttpRequest) => OauthProfile);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function oauthAuthorization(options: OauthProtocolOptions) {
|
|
20
|
+
const codes = new Map<string, OauthCode>();
|
|
21
|
+
let consent = true;
|
|
22
|
+
return {
|
|
23
|
+
authorize: (request: FakeHttpRequest): FakeHttpReply => {
|
|
24
|
+
const { query } = request;
|
|
25
|
+
if (query.get("client_id") !== options.clientId) {
|
|
26
|
+
return { body: { error: "invalid_client" }, status: 400 };
|
|
27
|
+
}
|
|
28
|
+
if (query.get("response_type") !== "code") {
|
|
29
|
+
return { body: { error: "unsupported_response_type" }, status: 400 };
|
|
30
|
+
}
|
|
31
|
+
const callback = new URL(query.get("redirect_uri") ?? "");
|
|
32
|
+
const state = query.get("state");
|
|
33
|
+
if (state !== null) {
|
|
34
|
+
callback.searchParams.set("state", state);
|
|
35
|
+
}
|
|
36
|
+
if (consent) {
|
|
37
|
+
const value = randomUUID();
|
|
38
|
+
codes.set(value, {
|
|
39
|
+
expires: options.now() + options.codeLifetime,
|
|
40
|
+
profile: typeof options.profile === "function" ? options.profile(request) : options.profile,
|
|
41
|
+
query,
|
|
42
|
+
});
|
|
43
|
+
callback.searchParams.set("code", value);
|
|
44
|
+
} else {
|
|
45
|
+
callback.searchParams.set("error", "access_denied");
|
|
46
|
+
}
|
|
47
|
+
return { headers: { location: callback.href }, status: 302 };
|
|
48
|
+
},
|
|
49
|
+
codes,
|
|
50
|
+
consent: (allowed: boolean) => {
|
|
51
|
+
consent = allowed;
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { Clock, Effect } from "effect";
|
|
3
|
+
import type { FakeHttpReply, FakeHttpRequest, FakeHttpRoute } from "@shivaedev/test-story/server/fakeHttpService.ts";
|
|
4
|
+
import type { OauthProfile } from "#identity/oauth.ts";
|
|
5
|
+
import { type OauthProtocolOptions, oauthAuthorization } from "./oauthAuthorization.ts";
|
|
6
|
+
import { oidcTokens } from "./oidcTokens.ts";
|
|
7
|
+
|
|
8
|
+
function validVerifier(query: URLSearchParams, form: URLSearchParams) {
|
|
9
|
+
return (
|
|
10
|
+
query.get("code_challenge_method") === "S256"
|
|
11
|
+
&& createHash("sha256")
|
|
12
|
+
.update(form.get("code_verifier") ?? "")
|
|
13
|
+
.digest("base64url") === query.get("code_challenge")
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function clientCredentials(authorization: string | undefined, form: URLSearchParams) {
|
|
18
|
+
if (authorization?.startsWith("Basic ")) {
|
|
19
|
+
const [clientId, clientSecret] = Buffer.from(authorization.slice(6), "base64").toString().split(":");
|
|
20
|
+
return { clientId, clientSecret };
|
|
21
|
+
}
|
|
22
|
+
return { clientId: form.get("client_id"), clientSecret: form.get("client_secret") };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const oauthProtocol = Effect.fnUntraced(function* (options: Omit<OauthProtocolOptions, "now">) {
|
|
26
|
+
const clock = yield* Clock.Clock;
|
|
27
|
+
const authorization = oauthAuthorization({ ...options, now: () => clock.currentTimeMillisUnsafe() });
|
|
28
|
+
const { codes } = authorization;
|
|
29
|
+
const tokens = new Map<string, { readonly profile: OauthProfile; readonly expires: number }>();
|
|
30
|
+
const signing = oidcTokens();
|
|
31
|
+
let issuer = "";
|
|
32
|
+
function refused(error: string, status = 400): FakeHttpReply {
|
|
33
|
+
return { body: { error }, status };
|
|
34
|
+
}
|
|
35
|
+
function profileOf({ headers }: FakeHttpRequest) {
|
|
36
|
+
const token = tokens.get(headers.authorization?.replace(/^Bearer /iu, "") ?? "");
|
|
37
|
+
return token !== undefined && token.expires > clock.currentTimeMillisUnsafe() ? token.profile : undefined;
|
|
38
|
+
}
|
|
39
|
+
function exchange({ body, headers }: FakeHttpRequest): FakeHttpReply {
|
|
40
|
+
const form = new URLSearchParams(body.toString());
|
|
41
|
+
const credentials = clientCredentials(headers.authorization, form);
|
|
42
|
+
if (credentials.clientId !== options.clientId || credentials.clientSecret !== options.clientSecret) {
|
|
43
|
+
return refused("invalid_client", 401);
|
|
44
|
+
}
|
|
45
|
+
if (form.get("grant_type") !== "authorization_code") {
|
|
46
|
+
return refused("unsupported_grant_type");
|
|
47
|
+
}
|
|
48
|
+
const value = form.get("code") ?? "";
|
|
49
|
+
const code = codes.get(value);
|
|
50
|
+
if (code === undefined || code.expires <= clock.currentTimeMillisUnsafe() || code.query.get("redirect_uri") !== form.get("redirect_uri")) {
|
|
51
|
+
return refused("invalid_grant");
|
|
52
|
+
}
|
|
53
|
+
const challenge = code.query.get("code_challenge");
|
|
54
|
+
if (challenge !== null && !validVerifier(code.query, form)) {
|
|
55
|
+
return refused("invalid_grant");
|
|
56
|
+
}
|
|
57
|
+
codes.delete(value);
|
|
58
|
+
const accessToken = randomUUID();
|
|
59
|
+
tokens.set(accessToken, { expires: clock.currentTimeMillisUnsafe() + 3_600_000, profile: code.profile });
|
|
60
|
+
return {
|
|
61
|
+
body: {
|
|
62
|
+
"access_token": accessToken,
|
|
63
|
+
"expires_in": 3600,
|
|
64
|
+
"id_token": signing.sign(code.profile, issuer, options.clientId, clock.currentTimeMillisUnsafe(), code.query.get("nonce")),
|
|
65
|
+
"refresh_token": randomUUID(),
|
|
66
|
+
scope: code.query.get("scope") ?? "",
|
|
67
|
+
"token_type": "Bearer",
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const routes: Record<string, FakeHttpRoute> = {
|
|
72
|
+
authorize: { path: "/login/oauth/authorize", reply: authorization.authorize },
|
|
73
|
+
discovery: { path: "/.well-known/openid-configuration", reply: () => ({ body: signing.discovery(issuer) }) },
|
|
74
|
+
emails: {
|
|
75
|
+
path: "/user/emails",
|
|
76
|
+
reply: (request) => {
|
|
77
|
+
const profile = profileOf(request);
|
|
78
|
+
return profile === undefined
|
|
79
|
+
? refused("invalid_token", 401)
|
|
80
|
+
: { body: [{ email: profile.email, primary: true, verified: profile.emailVerified ?? true }] };
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
jwks: { path: "/jwks", reply: () => ({ body: signing.jwks }) },
|
|
84
|
+
token: { method: "POST", path: "/login/oauth/access_token", reply: exchange },
|
|
85
|
+
user: {
|
|
86
|
+
path: "/user",
|
|
87
|
+
reply: (request) => {
|
|
88
|
+
const profile = profileOf(request);
|
|
89
|
+
return profile === undefined
|
|
90
|
+
? refused("invalid_token", 401)
|
|
91
|
+
: { body: { "avatar_url": null, email: profile.email, id: profile.sub, login: profile.name, name: profile.name } };
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
userinfo: {
|
|
95
|
+
path: "/userinfo",
|
|
96
|
+
reply: (request) => {
|
|
97
|
+
const profile = profileOf(request);
|
|
98
|
+
return profile === undefined
|
|
99
|
+
? refused("invalid_token", 401)
|
|
100
|
+
: { body: { email: profile.email, "email_verified": profile.emailVerified ?? true, name: profile.name, sub: profile.sub } };
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
consent: authorization.consent,
|
|
106
|
+
issuer: (url: string) => {
|
|
107
|
+
issuer = url;
|
|
108
|
+
},
|
|
109
|
+
routes,
|
|
110
|
+
};
|
|
111
|
+
});
|