Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

replayMarkers.ts

71 lines2.7 KB

1import * as Clock from "effect/Clock";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Path from "effect/Path";
8import * as Schedule from "effect/Schedule";
9​
10import { CLOUD_REPLAY_MARKER_PREFIXES } from "../cloud/CloudLink.ts";
11import * as ServerConfig from "../config.ts";
12import { forkParked } from "../serverActivation.ts";
13import { DPOP_REPLAY_MARKER_PREFIX } from "./dpop.ts";
14​
15const REPLAY_MARKER_PREFIXES = [DPOP_REPLAY_MARKER_PREFIX, ...CLOUD_REPLAY_MARKER_PREFIXES];
16​
17/**
18 * A marker only matters while its proof can pass the time check (about 10 minutes
19 * for DPoP, 7 for cloud proofs). After that, the time check rejects a replay by
20 * itself.
21 */
22export const REPLAY_MARKER_MAX_AGE = Duration.days(1);
23​
24/**
25 * `ServerSecretStore` saves each secret as `<name>.bin`, so only
26 * `<marker prefix>*.bin` names match. Other secrets and the `*.bin.<uuid>.tmp`
27 * files that `set` writes are never touched.
28 */
29export const pruneExpiredReplayMarkers = Effect.fn("replayMarkers.pruneExpired")(function* () {
30 const fileSystem = yield* FileSystem.FileSystem;
31 const path = yield* Path.Path;
32 const { secretsDir } = yield* ServerConfig.ServerConfig;
33 const cutoff = (yield* Clock.currentTimeMillis) - Duration.toMillis(REPLAY_MARKER_MAX_AGE);
34 const markers = (yield* fileSystem.readDirectory(secretsDir)).filter(
35 (name) =>
36 name.endsWith(".bin") && REPLAY_MARKER_PREFIXES.some((prefix) => name.startsWith(prefix)),
37 );
38 const [removed, failures] = yield* Effect.partition(markers, (name) => {
39 const markerPath = path.join(secretsDir, name);
40 return fileSystem.stat(markerPath).pipe(
41 Effect.flatMap((info) =>
42 Option.exists(info.mtime, (mtime) => mtime.getTime() < cutoff)
43 ? fileSystem.remove(markerPath).pipe(Effect.as(true))
44 : Effect.succeed(false),
45 ),
46 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
47 );
48 });
49 yield* Effect.annotateCurrentSpan({
50 "replay_markers.matched": markers.length,
51 "replay_markers.removed": removed.filter(Boolean).length,
52 "replay_markers.failed": failures.length,
53 });
54 if (failures.length > 0) {
55 yield* Effect.logWarning("Failed to prune some replay markers", {
56 failed: failures.length,
57 cause: failures[0],
58 });
59 }
60});
61​
62export const layer = Layer.effectDiscard(
63 forkParked(
64 pruneExpiredReplayMarkers().pipe(
65 Effect.catch((cause) =>
66 Effect.logWarning("Failed to prune expired replay markers", { cause }),
67 ),
68 Effect.repeat(Schedule.spaced(Duration.hours(1))),
69 ),
70 ),
71);