refactor relay/
This commit is contained in:
1 parent
556e893df0
commit
b65e22c765
63 files changed
+1990
-2332
No files matched your search
Vendored
+1
@@ -6,6 +6,7 @@
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib",
|
||||
"typescript.native-preview.tsdk": "node_modules/@typescript/native-preview",
|
||||
"typescript.preferences.autoImportFileExcludePatterns": [".repos/**"],
|
||||
"javascript.preferences.autoImportFileExcludePatterns": [".repos/**"],
|
||||
"files.watcherExclude": {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// @effect-diagnostics anyUnknownInErrorContext:off layerMergeAllWithDependencies:off - Alchemy provider helpers expose framework-owned any requirements.
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as Axiom from "alchemy/Axiom";
|
||||
import * as Cloudflare from "alchemy/Cloudflare";
|
||||
@@ -13,7 +14,6 @@ import Api from "./src/worker.ts";
|
||||
export default Alchemy.Stack(
|
||||
"T3CodeRelay",
|
||||
{
|
||||
// @effect-diagnostics-next-line anyUnknownInErrorContext:off layerMergeAllWithDependencies:off - Alchemy provider helpers expose framework-owned any requirements.
|
||||
providers: Layer.mergeAll(
|
||||
Axiom.providers(),
|
||||
Cloudflare.providers(),
|
||||
|
||||
@@ -6,27 +6,24 @@
|
||||
"deploy": "alchemy deploy",
|
||||
"destroy": "alchemy destroy",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsgo --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clerk/backend": "^3.4.14",
|
||||
"@distilled.cloud/cloudflare": "^0.21.5",
|
||||
"@clerk/backend": "3.4.14",
|
||||
"@effect/sql-pg": "catalog:",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"alchemy": "2.0.0-beta.45",
|
||||
"drizzle-orm": "^1.0.0-rc.1",
|
||||
"alchemy": "2.0.0-beta.47",
|
||||
"drizzle-orm": "1.0.0-rc.3",
|
||||
"effect": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20260520.0",
|
||||
"@cloudflare/workers-types": "^4.20260601.1",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/pg": "^8.15.6",
|
||||
"drizzle-kit": "^1.0.0-rc.1",
|
||||
"typescript": "catalog:",
|
||||
"drizzle-kit": "1.0.0-rc.3",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -29,4 +29,4 @@ export interface RelayConfigurationShape {
|
||||
export class RelayConfiguration extends Context.Service<
|
||||
RelayConfiguration,
|
||||
RelayConfigurationShape
|
||||
>()("RelayConfiguration") {}
|
||||
>()("t3code-relay/Config/RelayConfiguration") {}
|
||||
@@ -1,16 +0,0 @@
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export const layer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)),
|
||||
digest: (algorithm, data) =>
|
||||
Effect.promise(async () => {
|
||||
const input = new Uint8Array(data.length);
|
||||
input.set(data);
|
||||
return new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, input.buffer));
|
||||
}),
|
||||
}),
|
||||
);
|
||||
+1
-1
@@ -2,7 +2,7 @@ import type {
|
||||
RelayAgentActivityAggregateRow,
|
||||
RelayAgentActivityAggregateState,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
|
||||
import type { ApnsNotificationPayload } from "./ApnsDeliveryJobs.ts";
|
||||
|
||||
const MAX_SUMMARY_TEXT_LENGTH = 120;
|
||||
const MAX_STATUS_TEXT_LENGTH = 40;
|
||||
+3
-3
@@ -3,9 +3,9 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as AgentActivityRows from "../persistence/AgentActivityRows.ts";
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "../persistence/LiveActivities.ts";
|
||||
import * as AgentActivityRows from "./AgentActivityRows.ts";
|
||||
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
|
||||
import * as ApnsDeliveries from "./ApnsDeliveries.ts";
|
||||
|
||||
+25
-29
@@ -9,11 +9,10 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { sanitizeAgentActivityAggregateState } from "../agentActivityPayloads.ts";
|
||||
import * as AgentActivityRows from "../persistence/AgentActivityRows.ts";
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "../persistence/LiveActivities.ts";
|
||||
import { withUserId } from "../telemetry.ts";
|
||||
import { sanitizeAgentActivityAggregateState } from "./AgentActivityPayloads.ts";
|
||||
import * as AgentActivityRows from "./AgentActivityRows.ts";
|
||||
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
import * as ApnsDeliveries from "./ApnsDeliveries.ts";
|
||||
|
||||
export type AgentActivityPublishError =
|
||||
@@ -40,7 +39,7 @@ export interface AgentActivityPublisherShape {
|
||||
export class AgentActivityPublisher extends Context.Service<
|
||||
AgentActivityPublisher,
|
||||
AgentActivityPublisherShape
|
||||
>()("AgentActivityPublisher") {}
|
||||
>()("t3code-relay/agentActivity/AgentActivityPublisher") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const rows = yield* AgentActivityRows.AgentActivityRows;
|
||||
@@ -97,28 +96,25 @@ const make = Effect.gen(function* () {
|
||||
return AgentActivityPublisher.of({
|
||||
replayForLiveActivityRegistration: Effect.fn(
|
||||
"relay.agent_activity_publisher.replay_for_live_activity_registration",
|
||||
)(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
"relay.operation": "replayForLiveActivityRegistration",
|
||||
});
|
||||
const activeStates = yield* rows.listForUser({ userId: input.userId });
|
||||
const targets = yield* liveActivities.listTargets({ userId: input.userId });
|
||||
const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
|
||||
if (target === null) {
|
||||
return null;
|
||||
}
|
||||
const aggregate = makeAggregateState({ activeStates, terminalState: null });
|
||||
const now = yield* DateTime.now;
|
||||
return yield* apnsDeliveries.sendForTarget({
|
||||
target,
|
||||
aggregate,
|
||||
nowMs: now.epochMilliseconds,
|
||||
});
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
"relay.operation": "replayForLiveActivityRegistration",
|
||||
});
|
||||
const activeStates = yield* rows.listForUser({ userId: input.userId });
|
||||
const targets = yield* liveActivities.listTargets({ userId: input.userId });
|
||||
const target = targets.find((row) => row.device_id === input.deviceId) ?? null;
|
||||
if (target === null) {
|
||||
return null;
|
||||
}
|
||||
const aggregate = makeAggregateState({ activeStates, terminalState: null });
|
||||
const now = yield* DateTime.now;
|
||||
return yield* apnsDeliveries.sendForTarget({
|
||||
target,
|
||||
aggregate,
|
||||
nowMs: now.epochMilliseconds,
|
||||
});
|
||||
}),
|
||||
publish: Effect.fn("relay.agent_activity_publisher.publish")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
@@ -150,7 +146,7 @@ const make = Effect.gen(function* () {
|
||||
deliveryUser,
|
||||
state: input.state,
|
||||
nowMs: now.epochMilliseconds,
|
||||
}).pipe(withUserId(deliveryUser.userId)),
|
||||
}),
|
||||
{ concurrency: 4 },
|
||||
);
|
||||
const deliveries = deliveriesByUser.flat();
|
||||
+10
-7
@@ -4,14 +4,14 @@ import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { cast } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayAgentActivityRows, relayEnvironmentLinks } from "../schema.ts";
|
||||
import { parseJsonString, stringifyJsonValue } from "./json.ts";
|
||||
import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
|
||||
export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError(
|
||||
"AgentActivityRowUpsertPersistenceError",
|
||||
@@ -47,9 +47,12 @@ export interface AgentActivityRowsShape {
|
||||
}
|
||||
|
||||
export class AgentActivityRows extends Context.Service<AgentActivityRows, AgentActivityRowsShape>()(
|
||||
"AgentActivityRows",
|
||||
"t3code-relay/agentActivity/AgentActivityRows",
|
||||
) {}
|
||||
|
||||
const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString);
|
||||
const encodeJsonValue = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
const encodeRelayAgentActivityStateJson = Schema.encodeEffect(
|
||||
Schema.fromJsonString(RelayAgentActivityStateSchema),
|
||||
);
|
||||
@@ -69,8 +72,9 @@ const make = Effect.gen(function* () {
|
||||
"relay.thread_id": input.state.threadId,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const stateJson = yield* parseJsonString<RelayAgentActivityState>(
|
||||
yield* encodeRelayAgentActivityStateJson(input.state),
|
||||
const stateJson = yield* encodeRelayAgentActivityStateJson(input.state).pipe(
|
||||
Effect.flatMap(decodeJsonString),
|
||||
Effect.map(cast<unknown, RelayAgentActivityState>),
|
||||
);
|
||||
yield* db
|
||||
.insert(relayAgentActivityRows)
|
||||
@@ -115,7 +119,6 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
|
||||
listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "user.id": input.userId });
|
||||
return yield* db
|
||||
.select({ stateJson: relayAgentActivityRows.stateJson })
|
||||
.from(relayAgentActivityRows)
|
||||
@@ -139,7 +142,7 @@ const make = Effect.gen(function* () {
|
||||
.orderBy(desc(relayAgentActivityRows.updatedAt))
|
||||
.pipe(
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) => stringifyJsonValue(row.stateJson), {
|
||||
Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
|
||||
concurrency: "unbounded",
|
||||
}),
|
||||
),
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as ApnsClient from "./ApnsClient.ts";
|
||||
|
||||
const TestLayer = ApnsClient.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("ApnsClient", () => {
|
||||
const now = DateTime.makeUnsafe(0);
|
||||
const state: RelayAgentActivityAggregateState = {
|
||||
title: "T3 Code",
|
||||
subtitle: "Agent work in progress",
|
||||
activeCount: 1,
|
||||
updatedAt: DateTime.formatIso(now),
|
||||
activities: [
|
||||
{
|
||||
environmentId: EnvironmentId.make("env"),
|
||||
threadId: ThreadId.make("thread"),
|
||||
projectTitle: "Project",
|
||||
threadTitle: "Thread",
|
||||
modelTitle: "gpt-5.4",
|
||||
phase: "running" as const,
|
||||
status: "Working",
|
||||
updatedAt: DateTime.formatIso(now),
|
||||
deepLink: "/",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it.effect("requests an update push token when remotely starting a Live Activity", () =>
|
||||
Effect.gen(function* () {
|
||||
const apns = yield* ApnsClient.ApnsClient;
|
||||
const request = apns.makeLiveActivityRequest({
|
||||
event: "start",
|
||||
token: "token",
|
||||
state,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
nowIso: DateTime.formatIso(now),
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("10");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
event: "start",
|
||||
"attributes-type": "LiveActivityAttributes",
|
||||
"input-push-token": 1,
|
||||
"content-state": {
|
||||
name: "AgentActivity",
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("builds a low-priority update payload", () =>
|
||||
Effect.gen(function* () {
|
||||
const apns = yield* ApnsClient.ApnsClient;
|
||||
const request = apns.makeLiveActivityRequest({
|
||||
event: "update",
|
||||
token: "token",
|
||||
state,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
nowIso: DateTime.formatIso(now),
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("5");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
event: "update",
|
||||
"content-state": {
|
||||
name: "AgentActivity",
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("builds an end payload with a dismissal date", () =>
|
||||
Effect.gen(function* () {
|
||||
const apns = yield* ApnsClient.ApnsClient;
|
||||
const request = apns.makeLiveActivityRequest({
|
||||
event: "end",
|
||||
token: "token",
|
||||
state,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
nowIso: DateTime.formatIso(now),
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("10");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
event: "end",
|
||||
"dismissal-date": 300,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("builds a standard APNs alert payload with routing metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const apns = yield* ApnsClient.ApnsClient;
|
||||
const request = apns.makePushNotificationRequest({
|
||||
token: "push-token",
|
||||
notification: {
|
||||
title: "Thread",
|
||||
body: "Input: Project",
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/threads/env/thread",
|
||||
},
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("10");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
alert: {
|
||||
title: "Thread",
|
||||
body: "Input: Project",
|
||||
},
|
||||
sound: "default",
|
||||
},
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/threads/env/thread",
|
||||
});
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -14,8 +16,8 @@ import {
|
||||
type HttpBody,
|
||||
type HttpClientError,
|
||||
} from "effect/unstable/http";
|
||||
import type { ApnsCredentials } from "./Config.ts";
|
||||
import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
|
||||
import type { ApnsCredentials } from "../Config.ts";
|
||||
import type { ApnsNotificationPayload } from "./ApnsDeliveryJobs.ts";
|
||||
|
||||
const LIVE_ACTIVITY_NAME = "AgentActivity";
|
||||
const STALE_AFTER_SECONDS = 2 * 60;
|
||||
@@ -23,14 +25,14 @@ const DISMISS_AFTER_SECONDS = 5 * 60;
|
||||
|
||||
export type ApnsLiveActivityEvent = "start" | "update" | "end";
|
||||
|
||||
export interface ApnsLiveActivityRequest {
|
||||
interface ApnsLiveActivityRequest {
|
||||
readonly token: string;
|
||||
readonly event: ApnsLiveActivityEvent;
|
||||
readonly priority: "5" | "10";
|
||||
readonly payload: unknown;
|
||||
}
|
||||
|
||||
export interface ApnsPushNotificationRequest {
|
||||
interface ApnsPushNotificationRequest {
|
||||
readonly token: string;
|
||||
readonly priority: "10";
|
||||
readonly payload: unknown;
|
||||
@@ -44,6 +46,7 @@ export interface ApnsDeliveryResult {
|
||||
}
|
||||
|
||||
export class ApnsSigningError extends Data.TaggedError("ApnsSigningError")<{
|
||||
readonly phase: "encoding" | "signing";
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
@@ -64,21 +67,44 @@ const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
|
||||
}),
|
||||
),
|
||||
);
|
||||
const encodeApnsJwtHeaderJson = Schema.encodeEffect(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
alg: Schema.Literal("ES256"),
|
||||
kid: Schema.String,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const encodeApnsJwtPayloadJson = Schema.encodeEffect(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
iss: Schema.String,
|
||||
iat: Schema.Number,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
function makeApnsJwt(input: {
|
||||
const makeApnsJwt = Effect.fn("relay.apns.make_jwt")(function* (input: {
|
||||
readonly teamId: ApnsCredentials["teamId"];
|
||||
readonly keyId: ApnsCredentials["keyId"];
|
||||
readonly privateKey: ApnsCredentials["privateKey"];
|
||||
readonly issuedAtUnixSeconds: number;
|
||||
}): Effect.Effect<string, ApnsSigningError> {
|
||||
return Effect.try({
|
||||
}) {
|
||||
const headerJson = yield* encodeApnsJwtHeaderJson({ alg: "ES256", kid: input.keyId }).pipe(
|
||||
Effect.mapError((cause) => new ApnsSigningError({ cause, phase: "encoding" })),
|
||||
);
|
||||
const payloadJson = yield* encodeApnsJwtPayloadJson({
|
||||
iss: input.teamId,
|
||||
iat: input.issuedAtUnixSeconds,
|
||||
}).pipe(Effect.mapError((cause) => new ApnsSigningError({ cause, phase: "encoding" })));
|
||||
|
||||
const privateKey = Redacted.value(input.privateKey);
|
||||
const header = Encoding.encodeBase64Url(headerJson);
|
||||
const payload = Encoding.encodeBase64Url(payloadJson);
|
||||
const signingInput = `${header}.${payload}`;
|
||||
|
||||
return yield* Effect.try({
|
||||
try: () => {
|
||||
const privateKey = Redacted.value(input.privateKey);
|
||||
const header = Encoding.encodeBase64Url(JSON.stringify({ alg: "ES256", kid: input.keyId }));
|
||||
const payload = Encoding.encodeBase64Url(
|
||||
JSON.stringify({ iss: input.teamId, iat: input.issuedAtUnixSeconds }),
|
||||
);
|
||||
const signingInput = `${header}.${payload}`;
|
||||
const signature = NodeCrypto.createSign("sha256")
|
||||
.update(signingInput)
|
||||
.sign({
|
||||
@@ -87,9 +113,9 @@ function makeApnsJwt(input: {
|
||||
});
|
||||
return `${signingInput}.${Encoding.encodeBase64Url(signature)}`;
|
||||
},
|
||||
catch: (cause) => new ApnsSigningError({ cause }),
|
||||
catch: (cause) => new ApnsSigningError({ cause, phase: "signing" }),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function contentState(state: RelayAgentActivityAggregateState) {
|
||||
return {
|
||||
@@ -104,7 +130,7 @@ interface LiveActivityRequestBase {
|
||||
readonly nowIso: string;
|
||||
}
|
||||
|
||||
export type MakeLiveActivityRequestInput =
|
||||
type MakeLiveActivityRequestInput =
|
||||
| (LiveActivityRequestBase & {
|
||||
readonly event: "end";
|
||||
readonly state: RelayAgentActivityAggregateState | null;
|
||||
@@ -114,9 +140,7 @@ export type MakeLiveActivityRequestInput =
|
||||
readonly state: RelayAgentActivityAggregateState;
|
||||
});
|
||||
|
||||
export function makeLiveActivityRequest(
|
||||
input: MakeLiveActivityRequestInput,
|
||||
): ApnsLiveActivityRequest {
|
||||
function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
|
||||
const timestamp = input.nowEpochSeconds;
|
||||
if (input.event === "end") {
|
||||
return {
|
||||
@@ -161,7 +185,7 @@ export function makeLiveActivityRequest(
|
||||
};
|
||||
}
|
||||
|
||||
export function makePushNotificationRequest(input: {
|
||||
function makePushNotificationRequest(input: {
|
||||
readonly token: string;
|
||||
readonly notification: ApnsNotificationPayload;
|
||||
}): ApnsPushNotificationRequest {
|
||||
@@ -193,12 +217,31 @@ function apnsReasonFromBody(body: string): string | undefined {
|
||||
});
|
||||
}
|
||||
|
||||
export const sendLiveActivityRequest = Effect.fn("relay.apns.send_live_activity_request")(
|
||||
function* (input: {
|
||||
export interface ApnsClientShape {
|
||||
readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
|
||||
readonly makePushNotificationRequest: typeof makePushNotificationRequest;
|
||||
readonly sendLiveActivityRequest: (input: {
|
||||
readonly credentials: ApnsCredentials;
|
||||
readonly request: ApnsLiveActivityRequest;
|
||||
readonly issuedAtUnixSeconds: number;
|
||||
}) {
|
||||
}) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
|
||||
readonly sendPushNotificationRequest: (input: {
|
||||
readonly credentials: ApnsCredentials;
|
||||
readonly request: ApnsPushNotificationRequest;
|
||||
readonly issuedAtUnixSeconds: number;
|
||||
}) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
|
||||
}
|
||||
|
||||
export class ApnsClient extends Context.Service<ApnsClient, ApnsClientShape>()(
|
||||
"t3code-relay/agentActivity/ApnsClient",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
|
||||
const sendLiveActivityRequest: ApnsClientShape["sendLiveActivityRequest"] = Effect.fn(
|
||||
"relay.apns.send_live_activity_request",
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
|
||||
const jwt = yield* makeApnsJwt({
|
||||
...input.credentials,
|
||||
@@ -208,7 +251,6 @@ export const sendLiveActivityRequest = Effect.fn("relay.apns.send_live_activity_
|
||||
input.credentials.environment === "production"
|
||||
? "https://api.push.apple.com"
|
||||
: "https://api.sandbox.push.apple.com";
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
|
||||
HttpClientRequest.setHeaders({
|
||||
authorization: `bearer ${jwt}`,
|
||||
@@ -230,15 +272,11 @@ export const sendLiveActivityRequest = Effect.fn("relay.apns.send_live_activity_
|
||||
...(reason === undefined ? {} : { reason }),
|
||||
apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
|
||||
};
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
export const sendPushNotificationRequest = Effect.fn("relay.apns.send_push_notification_request")(
|
||||
function* (input: {
|
||||
readonly credentials: ApnsCredentials;
|
||||
readonly request: ApnsPushNotificationRequest;
|
||||
readonly issuedAtUnixSeconds: number;
|
||||
}) {
|
||||
const sendPushNotificationRequest: ApnsClientShape["sendPushNotificationRequest"] = Effect.fn(
|
||||
"relay.apns.send_push_notification_request",
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
|
||||
const jwt = yield* makeApnsJwt({
|
||||
...input.credentials,
|
||||
@@ -248,7 +286,6 @@ export const sendPushNotificationRequest = Effect.fn("relay.apns.send_push_notif
|
||||
input.credentials.environment === "production"
|
||||
? "https://api.push.apple.com"
|
||||
: "https://api.sandbox.push.apple.com";
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
|
||||
HttpClientRequest.setHeaders({
|
||||
authorization: `bearer ${jwt}`,
|
||||
@@ -270,5 +307,14 @@ export const sendPushNotificationRequest = Effect.fn("relay.apns.send_push_notif
|
||||
...(reason === undefined ? {} : { reason }),
|
||||
apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
|
||||
};
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
return ApnsClient.of({
|
||||
makeLiveActivityRequest,
|
||||
makePushNotificationRequest,
|
||||
sendLiveActivityRequest,
|
||||
sendPushNotificationRequest,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ApnsClient, make);
|
||||
+5
-3
@@ -19,12 +19,13 @@ import {
|
||||
makeApnsDeliveryJobPayload,
|
||||
signApnsDeliveryJob,
|
||||
type SignedApnsDeliveryJob,
|
||||
} from "../apnsDeliveryJobs.ts";
|
||||
import * as DeliveryAttempts from "../persistence/DeliveryAttempts.ts";
|
||||
import * as LiveActivities from "../persistence/LiveActivities.ts";
|
||||
} from "./ApnsDeliveryJobs.ts";
|
||||
import * as DeliveryAttempts from "./DeliveryAttempts.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
|
||||
import * as ApnsDeliveries from "./ApnsDeliveries.ts";
|
||||
import * as ApnsClient from "./ApnsClient.ts";
|
||||
|
||||
const config = RelayConfiguration.RelayConfiguration.of({
|
||||
relayIssuer: "https://relay.example.test",
|
||||
@@ -158,6 +159,7 @@ function makeLayer(input: {
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
|
||||
}) {
|
||||
return ApnsDeliveries.layer.pipe(
|
||||
Layer.provide(ApnsClient.layer),
|
||||
Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
+231
-229
@@ -15,25 +15,24 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
sanitizeAgentActivityAggregateState,
|
||||
sanitizeApnsNotificationPayload,
|
||||
} from "../agentActivityPayloads.ts";
|
||||
import * as Apns from "../apns.ts";
|
||||
} from "./AgentActivityPayloads.ts";
|
||||
import * as Apns from "./ApnsClient.ts";
|
||||
import {
|
||||
ApnsDeliveryJobInvalid,
|
||||
type ApnsNotificationPayload,
|
||||
SignedApnsDeliveryJob,
|
||||
verifySignedApnsDeliveryJob,
|
||||
type ApnsDeliveryJobVerificationError,
|
||||
} from "../apnsDeliveryJobs.ts";
|
||||
import * as DeliveryAttempts from "../persistence/DeliveryAttempts.ts";
|
||||
import * as LiveActivities from "../persistence/LiveActivities.ts";
|
||||
} from "./ApnsDeliveryJobs.ts";
|
||||
import * as DeliveryAttempts from "./DeliveryAttempts.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import { withUserId } from "../telemetry.ts";
|
||||
import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
|
||||
import { withSpanAttributes } from "../observability.ts";
|
||||
|
||||
const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000;
|
||||
const PERMANENT_APNS_TOKEN_REASONS = new Set([
|
||||
@@ -351,6 +350,7 @@ export type SendLiveActivityDeliveryInput =
|
||||
});
|
||||
|
||||
function makeLiveActivityDeliveryRequest(
|
||||
apns: Apns.ApnsClientShape,
|
||||
input: SendLiveActivityDeliveryInput,
|
||||
now: DateTime.DateTime,
|
||||
) {
|
||||
@@ -366,7 +366,7 @@ function makeLiveActivityDeliveryRequest(
|
||||
return {
|
||||
epochSeconds,
|
||||
iso: base.nowIso,
|
||||
request: Apns.makeLiveActivityRequest({
|
||||
request: apns.makeLiveActivityRequest({
|
||||
...base,
|
||||
event: deliveryEvent(input.kind),
|
||||
state: input.aggregate,
|
||||
@@ -376,7 +376,7 @@ function makeLiveActivityDeliveryRequest(
|
||||
return {
|
||||
epochSeconds,
|
||||
iso: base.nowIso,
|
||||
request: Apns.makeLiveActivityRequest({
|
||||
request: apns.makeLiveActivityRequest({
|
||||
...base,
|
||||
event: "end",
|
||||
state: input.aggregate,
|
||||
@@ -410,7 +410,7 @@ export interface ApnsDeliveriesShape {
|
||||
}
|
||||
|
||||
export class ApnsDeliveries extends Context.Service<ApnsDeliveries, ApnsDeliveriesShape>()(
|
||||
"ApnsDeliveries",
|
||||
"t3code-relay/agentActivity/ApnsDeliveries",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -418,7 +418,7 @@ const make = Effect.gen(function* () {
|
||||
const liveActivities = yield* LiveActivities.LiveActivities;
|
||||
const deliveryQueue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const apns = yield* Apns.ApnsClient;
|
||||
|
||||
const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {
|
||||
readonly target: LiveActivityDeliveryTarget;
|
||||
@@ -438,55 +438,56 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const sendLiveActivity: ApnsDeliveriesShape["sendLiveActivity"] = Effect.fn(
|
||||
"relay.apns_deliveries.send_live_activity",
|
||||
)(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.target.device_id,
|
||||
"relay.delivery.kind": input.kind,
|
||||
...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.target.device_id,
|
||||
"relay.delivery.kind": input.kind,
|
||||
...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const aggregate =
|
||||
input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate);
|
||||
const { epochSeconds, iso, request } = makeLiveActivityDeliveryRequest(
|
||||
apns,
|
||||
{ ...input, aggregate } as SendLiveActivityDeliveryInput,
|
||||
now,
|
||||
);
|
||||
if (input.sourceJobId) {
|
||||
const claim = yield* attempts.claimSourceJob({
|
||||
userId: input.target.user_id,
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
sourceJobId: input.sourceJobId,
|
||||
token: input.token,
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const aggregate =
|
||||
input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate);
|
||||
const { epochSeconds, iso, request } = makeLiveActivityDeliveryRequest(
|
||||
{ ...input, aggregate } as SendLiveActivityDeliveryInput,
|
||||
now,
|
||||
);
|
||||
if (input.sourceJobId) {
|
||||
const claim = yield* attempts.claimSourceJob({
|
||||
userId: input.target.user_id,
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
sourceJobId: input.sourceJobId,
|
||||
token: input.token,
|
||||
});
|
||||
if (claim === "completed") {
|
||||
return duplicateJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
if (claim === "in_flight") {
|
||||
return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });
|
||||
}
|
||||
const tokenIsCurrent = yield* isCurrentSignedJobToken({
|
||||
target: input.target,
|
||||
kind: input.kind,
|
||||
token: input.token,
|
||||
});
|
||||
if (!tokenIsCurrent) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
if (claim === "completed") {
|
||||
return duplicateJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
const result = yield* Apns.sendLiveActivityRequest({
|
||||
if (claim === "in_flight") {
|
||||
return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });
|
||||
}
|
||||
const tokenIsCurrent = yield* isCurrentSignedJobToken({
|
||||
target: input.target,
|
||||
kind: input.kind,
|
||||
token: input.token,
|
||||
});
|
||||
if (!tokenIsCurrent) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
|
||||
}
|
||||
}
|
||||
const result = yield* apns
|
||||
.sendLiveActivityRequest({
|
||||
credentials: config.apns,
|
||||
request,
|
||||
issuedAtUnixSeconds: epochSeconds,
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
@@ -496,116 +497,114 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (result.ok) {
|
||||
yield* liveActivities.markDelivery({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
aggregate,
|
||||
deliveredAt: iso,
|
||||
});
|
||||
} else if (isPermanentApnsTokenFailure(result)) {
|
||||
yield* liveActivities.invalidateDeliveryToken({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
invalidatedAt: iso,
|
||||
});
|
||||
} else if (input.kind === "live_activity_start") {
|
||||
yield* liveActivities.clearStartQueued({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
});
|
||||
}
|
||||
if (input.sourceJobId) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
} else {
|
||||
yield* attempts.record({
|
||||
userId: input.target.user_id,
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
token: input.token,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
}
|
||||
return {
|
||||
if (result.ok) {
|
||||
yield* liveActivities.markDelivery({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
ok: result.ok,
|
||||
apnsStatus: result.status === 0 ? null : result.status,
|
||||
apnsReason: result.reason ?? null,
|
||||
apnsId: result.apnsId,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.target.user_id)),
|
||||
);
|
||||
aggregate,
|
||||
deliveredAt: iso,
|
||||
});
|
||||
} else if (isPermanentApnsTokenFailure(result)) {
|
||||
yield* liveActivities.invalidateDeliveryToken({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
invalidatedAt: iso,
|
||||
});
|
||||
} else if (input.kind === "live_activity_start") {
|
||||
yield* liveActivities.clearStartQueued({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
});
|
||||
}
|
||||
if (input.sourceJobId) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
} else {
|
||||
yield* attempts.record({
|
||||
userId: input.target.user_id,
|
||||
environmentId: null,
|
||||
threadId: null,
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
token: input.token,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
}
|
||||
return {
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
ok: result.ok,
|
||||
apnsStatus: result.status === 0 ? null : result.status,
|
||||
apnsReason: result.reason ?? null,
|
||||
apnsId: result.apnsId,
|
||||
};
|
||||
});
|
||||
|
||||
const sendPushNotification: ApnsDeliveriesShape["sendPushNotification"] = Effect.fn(
|
||||
"relay.apns_deliveries.send_push_notification",
|
||||
)(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.target.device_id,
|
||||
"relay.delivery.kind": "push_notification",
|
||||
...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const epochSeconds = Math.floor(now.epochMilliseconds / 1_000);
|
||||
const notification = sanitizeApnsNotificationPayload(input.notification);
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": notification.environmentId,
|
||||
"relay.thread_id": notification.threadId,
|
||||
});
|
||||
const request = Apns.makePushNotificationRequest({
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.target.device_id,
|
||||
"relay.delivery.kind": "push_notification",
|
||||
...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const epochSeconds = Math.floor(now.epochMilliseconds / 1_000);
|
||||
const notification = sanitizeApnsNotificationPayload(input.notification);
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": notification.environmentId,
|
||||
"relay.thread_id": notification.threadId,
|
||||
});
|
||||
const request = apns.makePushNotificationRequest({
|
||||
token: input.token,
|
||||
notification,
|
||||
});
|
||||
if (input.sourceJobId) {
|
||||
const claim = yield* attempts.claimSourceJob({
|
||||
userId: input.target.user_id,
|
||||
environmentId: notification.environmentId,
|
||||
threadId: notification.threadId,
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
sourceJobId: input.sourceJobId,
|
||||
token: input.token,
|
||||
notification,
|
||||
});
|
||||
if (input.sourceJobId) {
|
||||
const claim = yield* attempts.claimSourceJob({
|
||||
userId: input.target.user_id,
|
||||
environmentId: notification.environmentId,
|
||||
threadId: notification.threadId,
|
||||
if (claim === "completed") {
|
||||
return duplicateJobResult({
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
sourceJobId: input.sourceJobId,
|
||||
token: input.token,
|
||||
});
|
||||
if (claim === "completed") {
|
||||
return duplicateJobResult({
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
if (claim === "in_flight") {
|
||||
return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });
|
||||
}
|
||||
const tokenIsCurrent = yield* isCurrentSignedJobToken({
|
||||
target: input.target,
|
||||
kind: "push_notification",
|
||||
token: input.token,
|
||||
});
|
||||
if (!tokenIsCurrent) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
return staleJobResult({
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
}
|
||||
const result = yield* Apns.sendPushNotificationRequest({
|
||||
if (claim === "in_flight") {
|
||||
return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });
|
||||
}
|
||||
const tokenIsCurrent = yield* isCurrentSignedJobToken({
|
||||
target: input.target,
|
||||
kind: "push_notification",
|
||||
token: input.token,
|
||||
});
|
||||
if (!tokenIsCurrent) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsReason: "Stale APNs delivery job skipped.",
|
||||
});
|
||||
return staleJobResult({
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
});
|
||||
}
|
||||
}
|
||||
const result = yield* apns
|
||||
.sendPushNotificationRequest({
|
||||
credentials: config.apns,
|
||||
request,
|
||||
issuedAtUnixSeconds: epochSeconds,
|
||||
}).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
@@ -615,41 +614,39 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (isPermanentApnsTokenFailure(result)) {
|
||||
yield* liveActivities.invalidateDeliveryToken({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
invalidatedAt: DateTime.formatIso(now),
|
||||
});
|
||||
}
|
||||
if (input.sourceJobId) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
} else {
|
||||
yield* attempts.record({
|
||||
userId: input.target.user_id,
|
||||
environmentId: notification.environmentId,
|
||||
threadId: notification.threadId,
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
token: input.token,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
}
|
||||
return {
|
||||
if (isPermanentApnsTokenFailure(result)) {
|
||||
yield* liveActivities.invalidateDeliveryToken({
|
||||
userId: input.target.user_id,
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification" as const,
|
||||
ok: result.ok,
|
||||
apnsStatus: result.status === 0 ? null : result.status,
|
||||
apnsReason: result.reason ?? null,
|
||||
apnsId: result.apnsId,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.target.user_id)),
|
||||
);
|
||||
kind: "push_notification",
|
||||
invalidatedAt: DateTime.formatIso(now),
|
||||
});
|
||||
}
|
||||
if (input.sourceJobId) {
|
||||
yield* attempts.completeSourceJob({
|
||||
sourceJobId: input.sourceJobId,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
} else {
|
||||
yield* attempts.record({
|
||||
userId: input.target.user_id,
|
||||
environmentId: notification.environmentId,
|
||||
threadId: notification.threadId,
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
token: input.token,
|
||||
...deliveryAttemptOutcome(result),
|
||||
});
|
||||
}
|
||||
return {
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification" as const,
|
||||
ok: result.ok,
|
||||
apnsStatus: result.status === 0 ? null : result.status,
|
||||
apnsReason: result.reason ?? null,
|
||||
apnsId: result.apnsId,
|
||||
};
|
||||
});
|
||||
|
||||
const processSignedJob: ApnsDeliveriesShape["processSignedJob"] = Effect.fn(
|
||||
"relay.apns_deliveries.process_signed_job",
|
||||
@@ -672,56 +669,61 @@ const make = Effect.gen(function* () {
|
||||
return yield* payload;
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": payload.target.userId,
|
||||
"relay.mobile.device_id": payload.target.deviceId,
|
||||
"relay.delivery.kind": payload.kind,
|
||||
"relay.delivery.job_id": payload.jobId,
|
||||
});
|
||||
switch (payload.kind) {
|
||||
case "live_activity_start":
|
||||
case "live_activity_update":
|
||||
if (payload.aggregate === null) {
|
||||
return yield* new ApnsDeliveryJobInvalid({
|
||||
message: "Live Activity start/update jobs require an aggregate.",
|
||||
return yield* Effect.suspend(() => {
|
||||
switch (payload.kind) {
|
||||
case "live_activity_start":
|
||||
case "live_activity_update":
|
||||
if (payload.aggregate === null) {
|
||||
return Effect.fail(
|
||||
new ApnsDeliveryJobInvalid({
|
||||
message: "Live Activity start/update jobs require an aggregate.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return sendLiveActivity({
|
||||
target: {
|
||||
user_id: payload.target.userId,
|
||||
device_id: payload.target.deviceId,
|
||||
},
|
||||
token: payload.target.token,
|
||||
sourceJobId: payload.jobId,
|
||||
kind: payload.kind,
|
||||
aggregate: payload.aggregate,
|
||||
});
|
||||
}
|
||||
return yield* sendLiveActivity({
|
||||
target: {
|
||||
user_id: payload.target.userId,
|
||||
device_id: payload.target.deviceId,
|
||||
},
|
||||
token: payload.target.token,
|
||||
sourceJobId: payload.jobId,
|
||||
kind: payload.kind,
|
||||
aggregate: payload.aggregate,
|
||||
});
|
||||
case "live_activity_end":
|
||||
return yield* sendLiveActivity({
|
||||
target: {
|
||||
user_id: payload.target.userId,
|
||||
device_id: payload.target.deviceId,
|
||||
},
|
||||
token: payload.target.token,
|
||||
sourceJobId: payload.jobId,
|
||||
kind: payload.kind,
|
||||
aggregate: payload.aggregate,
|
||||
});
|
||||
case "push_notification":
|
||||
if (payload.notification === null) {
|
||||
return yield* new ApnsDeliveryJobInvalid({
|
||||
message: "Push notification jobs require a notification payload.",
|
||||
case "live_activity_end":
|
||||
return sendLiveActivity({
|
||||
target: {
|
||||
user_id: payload.target.userId,
|
||||
device_id: payload.target.deviceId,
|
||||
},
|
||||
token: payload.target.token,
|
||||
sourceJobId: payload.jobId,
|
||||
kind: payload.kind,
|
||||
aggregate: payload.aggregate,
|
||||
});
|
||||
}
|
||||
return yield* sendPushNotification({
|
||||
target: {
|
||||
user_id: payload.target.userId,
|
||||
device_id: payload.target.deviceId,
|
||||
},
|
||||
token: payload.target.token,
|
||||
sourceJobId: payload.jobId,
|
||||
notification: payload.notification,
|
||||
});
|
||||
}
|
||||
case "push_notification":
|
||||
if (payload.notification === null) {
|
||||
return Effect.fail(
|
||||
new ApnsDeliveryJobInvalid({
|
||||
message: "Push notification jobs require a notification payload.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return sendPushNotification({
|
||||
target: {
|
||||
user_id: payload.target.userId,
|
||||
device_id: payload.target.deviceId,
|
||||
},
|
||||
token: payload.target.token,
|
||||
sourceJobId: payload.jobId,
|
||||
notification: payload.notification,
|
||||
});
|
||||
}
|
||||
}).pipe(withSpanAttributes({ "user.id": payload.target.userId }));
|
||||
});
|
||||
|
||||
return ApnsDeliveries.of({
|
||||
+1
-1
@@ -7,7 +7,7 @@ import {
|
||||
makeApnsDeliveryJobPayload,
|
||||
signApnsDeliveryJob,
|
||||
verifySignedApnsDeliveryJob,
|
||||
} from "./apnsDeliveryJobs.ts";
|
||||
} from "./ApnsDeliveryJobs.ts";
|
||||
|
||||
const secret = Redacted.make("queue-signing-secret");
|
||||
const aggregate: RelayAgentActivityAggregateState = {
|
||||
File renamed without changes.
+4
-7
@@ -9,16 +9,15 @@ import * as Layer from "effect/Layer";
|
||||
import {
|
||||
sanitizeAgentActivityAggregateState,
|
||||
sanitizeApnsNotificationPayload,
|
||||
} from "../agentActivityPayloads.ts";
|
||||
} from "./AgentActivityPayloads.ts";
|
||||
import {
|
||||
expiresAtForJob,
|
||||
makeApnsDeliveryJobPayload,
|
||||
signApnsDeliveryJob,
|
||||
type ApnsDeliveryJobPayload,
|
||||
type SignedApnsDeliveryJob,
|
||||
} from "../apnsDeliveryJobs.ts";
|
||||
} from "./ApnsDeliveryJobs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import { withUserId } from "../telemetry.ts";
|
||||
|
||||
export class ApnsDeliveryQueueSendError extends Data.TaggedError("ApnsDeliveryQueueSendError")<{
|
||||
readonly cause: unknown;
|
||||
@@ -33,7 +32,7 @@ export interface ApnsDeliveryQueueSenderShape {
|
||||
export class ApnsDeliveryQueueSender extends Context.Service<
|
||||
ApnsDeliveryQueueSender,
|
||||
ApnsDeliveryQueueSenderShape
|
||||
>()("ApnsDeliveryQueueSender") {}
|
||||
>()("t3code-relay/agentActivity/ApnsDeliveryQueue/ApnsDeliveryQueueSender") {}
|
||||
|
||||
export interface ApnsDeliveryQueueShape {
|
||||
readonly enqueueLiveActivity: (input: {
|
||||
@@ -52,7 +51,7 @@ export interface ApnsDeliveryQueueShape {
|
||||
}
|
||||
|
||||
export class ApnsDeliveryQueue extends Context.Service<ApnsDeliveryQueue, ApnsDeliveryQueueShape>()(
|
||||
"ApnsDeliveryQueue",
|
||||
"t3code-relay/agentActivity/ApnsDeliveryQueue",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
@@ -95,7 +94,6 @@ const make = Effect.gen(function* () {
|
||||
apnsId: null,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
enqueuePushNotification: Effect.fn("relay.apns_delivery_queue.enqueue_push_notification")(
|
||||
function* (input) {
|
||||
@@ -136,7 +134,6 @@ const make = Effect.gen(function* () {
|
||||
apnsId: null,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayDeliveryAttempts } from "../schema.ts";
|
||||
import { relayDeliveryAttempts } from "../persistence/schema.ts";
|
||||
import * as DeliveryAttempts from "./DeliveryAttempts.ts";
|
||||
|
||||
describe("DeliveryAttempts", () => {
|
||||
+2
-4
@@ -8,7 +8,7 @@ import { and, eq, isNull } from "drizzle-orm";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayDeliveryAttempts } from "../schema.ts";
|
||||
import { relayDeliveryAttempts } from "../persistence/schema.ts";
|
||||
|
||||
export class DeliveryAttemptRecordPersistenceError extends Data.TaggedError(
|
||||
"DeliveryAttemptRecordPersistenceError",
|
||||
@@ -53,7 +53,7 @@ export interface DeliveryAttemptsShape {
|
||||
}
|
||||
|
||||
export class DeliveryAttempts extends Context.Service<DeliveryAttempts, DeliveryAttemptsShape>()(
|
||||
"DeliveryAttempts",
|
||||
"t3code-relay/agentActivity/DeliveryAttempts",
|
||||
) {}
|
||||
|
||||
const SOURCE_JOB_CLAIM_LEASE_MINUTES = 10;
|
||||
@@ -105,7 +105,6 @@ const make = Effect.gen(function* () {
|
||||
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
|
||||
...(input.environmentId ? { "relay.environment_id": input.environmentId } : {}),
|
||||
...(input.threadId ? { "relay.thread_id": input.threadId } : {}),
|
||||
...(input.userId ? { "user.id": input.userId } : {}),
|
||||
});
|
||||
const id = yield* crypto.randomUUIDv4;
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -121,7 +120,6 @@ const make = Effect.gen(function* () {
|
||||
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
|
||||
...(input.environmentId ? { "relay.environment_id": input.environmentId } : {}),
|
||||
...(input.threadId ? { "relay.thread_id": input.threadId } : {}),
|
||||
...(input.userId ? { "user.id": input.userId } : {}),
|
||||
});
|
||||
const id = yield* crypto.randomUUIDv4;
|
||||
const now = yield* DateTime.now;
|
||||
+1
-1
@@ -6,7 +6,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../schema.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
|
||||
import * as Devices from "./Devices.ts";
|
||||
|
||||
const registration: RelayDeviceRegistrationRequest = {
|
||||
@@ -8,7 +8,7 @@ import { and, eq } from "drizzle-orm";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../schema.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
|
||||
|
||||
export class DeviceRegistrationPersistenceError extends Data.TaggedError(
|
||||
"DeviceRegistrationPersistenceError",
|
||||
@@ -33,7 +33,9 @@ export interface DevicesShape {
|
||||
}) => Effect.Effect<void, DeviceUnregistrationPersistenceError>;
|
||||
}
|
||||
|
||||
export class Devices extends Context.Service<Devices, DevicesShape>()("Devices") {}
|
||||
export class Devices extends Context.Service<Devices, DevicesShape>()(
|
||||
"t3code-relay/agentActivity/Devices",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const db = yield* RelayDb;
|
||||
@@ -42,7 +44,6 @@ const make = Effect.gen(function* () {
|
||||
register: Effect.fn("relay.devices.register")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.registration.deviceId,
|
||||
});
|
||||
const updatedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -101,7 +102,6 @@ const make = Effect.gen(function* () {
|
||||
unregister: Effect.fn("relay.devices.unregister")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
});
|
||||
yield* Effect.all(
|
||||
+1
-1
@@ -9,7 +9,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayLiveActivities } from "../schema.ts";
|
||||
import { relayLiveActivities } from "../persistence/schema.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
|
||||
const aggregate: RelayAgentActivityAggregateState = {
|
||||
+11
-13
@@ -8,13 +8,13 @@ import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { cast } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../schema.ts";
|
||||
import { parseJsonString, stringifyJsonValue } from "./json.ts";
|
||||
import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";
|
||||
|
||||
export class LiveActivityRegistrationPersistenceError extends Data.TaggedError(
|
||||
"LiveActivityRegistrationPersistenceError",
|
||||
@@ -89,9 +89,12 @@ export interface LiveActivitiesShape {
|
||||
}
|
||||
|
||||
export class LiveActivities extends Context.Service<LiveActivities, LiveActivitiesShape>()(
|
||||
"LiveActivities",
|
||||
"t3code-relay/agentActivity/LiveActivities",
|
||||
) {}
|
||||
|
||||
const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString);
|
||||
const encodeJsonValue = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
const encodeRelayAgentActivityAggregateStateJson = Schema.encodeEffect(
|
||||
Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),
|
||||
);
|
||||
@@ -103,7 +106,6 @@ const make = Effect.gen(function* () {
|
||||
register: Effect.fn("relay.live_activities.register")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.registration.deviceId,
|
||||
});
|
||||
const updatedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -151,7 +153,6 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
|
||||
listTargets: Effect.fn("relay.live_activities.list_targets")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "user.id": input.userId });
|
||||
return yield* db
|
||||
.select({
|
||||
device_id: relayMobileDevices.deviceId,
|
||||
@@ -184,11 +185,11 @@ const make = Effect.gen(function* () {
|
||||
rows,
|
||||
(row) =>
|
||||
Effect.all({
|
||||
preferences_json: stringifyJsonValue(row.preferences_json),
|
||||
preferences_json: encodeJsonValue(row.preferences_json),
|
||||
last_aggregate_json:
|
||||
row.last_aggregate_json === null
|
||||
? Effect.succeed(null)
|
||||
: stringifyJsonValue(row.last_aggregate_json),
|
||||
: encodeJsonValue(row.last_aggregate_json),
|
||||
}).pipe(
|
||||
Effect.map((json) => ({
|
||||
...row,
|
||||
@@ -206,15 +207,15 @@ const make = Effect.gen(function* () {
|
||||
markDelivery: Effect.fn("relay.live_activities.mark_delivery")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
"relay.delivery.kind": input.kind,
|
||||
});
|
||||
const aggregateJson =
|
||||
input.aggregate === null
|
||||
? null
|
||||
: yield* parseJsonString<RelayAgentActivityAggregateState>(
|
||||
yield* encodeRelayAgentActivityAggregateStateJson(input.aggregate),
|
||||
: yield* encodeRelayAgentActivityAggregateStateJson(input.aggregate).pipe(
|
||||
Effect.flatMap(decodeJsonString),
|
||||
Effect.map(cast<unknown, RelayAgentActivityAggregateState>),
|
||||
);
|
||||
|
||||
yield* db
|
||||
@@ -255,7 +256,6 @@ const make = Effect.gen(function* () {
|
||||
|
||||
markStartQueued: Effect.fn("relay.live_activities.mark_start_queued")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
});
|
||||
yield* db
|
||||
@@ -285,7 +285,6 @@ const make = Effect.gen(function* () {
|
||||
|
||||
clearStartQueued: Effect.fn("relay.live_activities.clear_start_queued")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
});
|
||||
yield* db
|
||||
@@ -303,7 +302,6 @@ const make = Effect.gen(function* () {
|
||||
invalidateDeliveryToken: Effect.fn("relay.live_activities.invalidate_delivery_token")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
"relay.delivery.kind": input.kind,
|
||||
});
|
||||
+8
-7
@@ -2,7 +2,7 @@ import type {
|
||||
RelayAgentActivityState,
|
||||
RelayDeviceRegistrationRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import type { SignedApnsDeliveryJob } from "../apnsDeliveryJobs.ts";
|
||||
import type { SignedApnsDeliveryJob } from "./ApnsDeliveryJobs.ts";
|
||||
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -10,14 +10,15 @@ import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as Devices from "../persistence/Devices.ts";
|
||||
import * as AgentActivityRows from "../persistence/AgentActivityRows.ts";
|
||||
import * as DeliveryAttempts from "../persistence/DeliveryAttempts.ts";
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "../persistence/LiveActivities.ts";
|
||||
import * as Devices from "./Devices.ts";
|
||||
import * as AgentActivityRows from "./AgentActivityRows.ts";
|
||||
import * as DeliveryAttempts from "./DeliveryAttempts.ts";
|
||||
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
|
||||
import * as ApnsDeliveries from "./ApnsDeliveries.ts";
|
||||
import * as ApnsClient from "./ApnsClient.ts";
|
||||
import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
|
||||
import * as MobileRegistrations from "./MobileRegistrations.ts";
|
||||
|
||||
@@ -141,7 +142,7 @@ function makeRegistrationReplayLayer(input: {
|
||||
}) {
|
||||
return MobileRegistrations.layer.pipe(
|
||||
Layer.provide(AgentActivityPublisher.layer),
|
||||
Layer.provide(ApnsDeliveries.layer),
|
||||
Layer.provide(ApnsDeliveries.layer.pipe(Layer.provide(ApnsClient.layer))),
|
||||
Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
+29
-37
@@ -6,9 +6,8 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Devices from "../persistence/Devices.ts";
|
||||
import * as LiveActivities from "../persistence/LiveActivities.ts";
|
||||
import { withUserId } from "../telemetry.ts";
|
||||
import * as Devices from "./Devices.ts";
|
||||
import * as LiveActivities from "./LiveActivities.ts";
|
||||
import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
|
||||
|
||||
export type MobileRegistrationError =
|
||||
@@ -34,7 +33,7 @@ export interface MobileRegistrationsShape {
|
||||
export class MobileRegistrations extends Context.Service<
|
||||
MobileRegistrations,
|
||||
MobileRegistrationsShape
|
||||
>()("MobileRegistrations") {}
|
||||
>()("t3code-relay/agentActivity/MobileRegistrations") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const devices = yield* Devices.Devices;
|
||||
@@ -42,28 +41,25 @@ const make = Effect.gen(function* () {
|
||||
const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
|
||||
|
||||
return MobileRegistrations.of({
|
||||
registerDevice: Effect.fn("relay.mobile_registrations.register_device")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.payload.deviceId,
|
||||
"relay.mobile.platform": input.payload.platform,
|
||||
});
|
||||
yield* devices.register({ userId: input.userId, registration: input.payload });
|
||||
yield* publisher
|
||||
.replayForLiveActivityRegistration({
|
||||
userId: input.userId,
|
||||
deviceId: input.payload.deviceId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("device registration activity replay failed", { cause }),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
return { ok: true as const };
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
registerDevice: Effect.fn("relay.mobile_registrations.register_device")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.payload.deviceId,
|
||||
"relay.mobile.platform": input.payload.platform,
|
||||
});
|
||||
yield* devices.register({ userId: input.userId, registration: input.payload });
|
||||
yield* publisher
|
||||
.replayForLiveActivityRegistration({
|
||||
userId: input.userId,
|
||||
deviceId: input.payload.deviceId,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logWarning("device registration activity replay failed", { cause }),
|
||||
),
|
||||
Effect.ignore,
|
||||
);
|
||||
return { ok: true as const };
|
||||
}),
|
||||
registerLiveActivity: Effect.fn("relay.mobile_registrations.register_live_activity")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
@@ -83,18 +79,14 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
return { ok: true as const };
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
unregisterDevice: Effect.fn("relay.mobile_registrations.unregister_device")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
});
|
||||
yield* devices.unregister(input);
|
||||
return { ok: true as const };
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
unregisterDevice: Effect.fn("relay.mobile_registrations.unregister_device")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.mobile.device_id": input.deviceId,
|
||||
});
|
||||
yield* devices.unregister(input);
|
||||
return { ok: true as const };
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
|
||||
import { makeLiveActivityRequest, makePushNotificationRequest } from "./apns.ts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
describe("makeLiveActivityRequest", () => {
|
||||
const now = DateTime.makeUnsafe(0);
|
||||
const state: RelayAgentActivityAggregateState = {
|
||||
title: "T3 Code",
|
||||
subtitle: "Agent work in progress",
|
||||
activeCount: 1,
|
||||
updatedAt: DateTime.formatIso(now),
|
||||
activities: [
|
||||
{
|
||||
environmentId: EnvironmentId.make("env"),
|
||||
threadId: ThreadId.make("thread"),
|
||||
projectTitle: "Project",
|
||||
threadTitle: "Thread",
|
||||
modelTitle: "gpt-5.4",
|
||||
phase: "running" as const,
|
||||
status: "Working",
|
||||
updatedAt: DateTime.formatIso(now),
|
||||
deepLink: "/",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
it("requests an update push token when remotely starting a Live Activity", () => {
|
||||
const request = makeLiveActivityRequest({
|
||||
event: "start",
|
||||
token: "token",
|
||||
state,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
nowIso: DateTime.formatIso(now),
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("10");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
event: "start",
|
||||
"attributes-type": "LiveActivityAttributes",
|
||||
"input-push-token": 1,
|
||||
"content-state": {
|
||||
name: "AgentActivity",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a low-priority update payload", () => {
|
||||
const request = makeLiveActivityRequest({
|
||||
event: "update",
|
||||
token: "token",
|
||||
state,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
nowIso: DateTime.formatIso(now),
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("5");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
event: "update",
|
||||
"content-state": {
|
||||
name: "AgentActivity",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("builds an end payload with a dismissal date", () => {
|
||||
const request = makeLiveActivityRequest({
|
||||
event: "end",
|
||||
token: "token",
|
||||
state,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
nowIso: DateTime.formatIso(now),
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("10");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
event: "end",
|
||||
"dismissal-date": 300,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a standard APNs alert payload with routing metadata", () => {
|
||||
const request = makePushNotificationRequest({
|
||||
token: "push-token",
|
||||
notification: {
|
||||
title: "Thread",
|
||||
body: "Input: Project",
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/threads/env/thread",
|
||||
},
|
||||
});
|
||||
|
||||
expect(request.priority).toBe("10");
|
||||
expect(request.payload).toMatchObject({
|
||||
aps: {
|
||||
alert: {
|
||||
title: "Thread",
|
||||
body: "Input: Project",
|
||||
},
|
||||
sound: "default",
|
||||
},
|
||||
environmentId: "env",
|
||||
threadId: "thread",
|
||||
deepLink: "/threads/env/thread",
|
||||
});
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayDpopProofs } from "../schema.ts";
|
||||
import { relayDpopProofs } from "../persistence/schema.ts";
|
||||
import * as DpopProofs from "./DpopProofs.ts";
|
||||
|
||||
describe("DpopProofReplay", () => {
|
||||
@@ -0,0 +1,128 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
|
||||
import { lt } from "drizzle-orm";
|
||||
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayDpopProofs } from "../persistence/schema.ts";
|
||||
|
||||
export class DpopProofReplayPersistenceError extends Data.TaggedError(
|
||||
"DpopProofReplayPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface DpopProofReplayShape {
|
||||
readonly verifyAndConsume: (input: {
|
||||
readonly proof: string | undefined;
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
readonly expectedThumbprint?: string;
|
||||
readonly expectedAccessToken?: string;
|
||||
readonly now: DateTime.DateTime;
|
||||
}) => Effect.Effect<string, HttpApiError.Unauthorized | DpopProofReplayPersistenceError>;
|
||||
|
||||
readonly consume: (input: {
|
||||
readonly thumbprint: string;
|
||||
readonly jti: string;
|
||||
readonly iat: number;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
}) => Effect.Effect<boolean, DpopProofReplayPersistenceError>;
|
||||
|
||||
readonly pruneExpired: Effect.Effect<void, DpopProofReplayPersistenceError>;
|
||||
}
|
||||
|
||||
export class DpopProofReplay extends Context.Service<DpopProofReplay, DpopProofReplayShape>()(
|
||||
"t3code-relay/auth/DpopProofs/DpopProofReplay",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const db = yield* RelayDb;
|
||||
|
||||
const consume: DpopProofReplayShape["consume"] = Effect.fn("relay.dpop_proofs.consume")(
|
||||
function* (input) {
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const inserted = yield* db
|
||||
.insert(relayDpopProofs)
|
||||
.values({
|
||||
thumbprint: input.thumbprint,
|
||||
jti: input.jti,
|
||||
iat: input.iat,
|
||||
expiresAt: DateTime.formatIso(input.expiresAt),
|
||||
createdAt,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ jti: relayDpopProofs.jti });
|
||||
return inserted.length > 0;
|
||||
},
|
||||
Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })),
|
||||
);
|
||||
|
||||
const verifyAndConsume: DpopProofReplayShape["verifyAndConsume"] = Effect.fn(
|
||||
"relay.dpop_proofs.verify_and_consume",
|
||||
)(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.dpop.method": input.method,
|
||||
"relay.dpop.expected_thumbprint_present": input.expectedThumbprint !== undefined,
|
||||
"relay.dpop.expected_access_token_present": input.expectedAccessToken !== undefined,
|
||||
});
|
||||
const result = verifyDpopProof({
|
||||
proof: input.proof,
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
});
|
||||
if (!result.ok) {
|
||||
yield* Effect.logWarning("relay dpop proof rejected", {
|
||||
reason: result.reason,
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
expectedThumbprintPresent: input.expectedThumbprint !== undefined,
|
||||
expectedAccessTokenPresent: input.expectedAccessToken !== undefined,
|
||||
});
|
||||
return yield* new HttpApiError.Unauthorized({});
|
||||
}
|
||||
const consumed = yield* consume({
|
||||
thumbprint: result.thumbprint,
|
||||
jti: result.jti,
|
||||
iat: result.iat,
|
||||
expiresAt: DateTime.add(input.now, { minutes: 5 }),
|
||||
});
|
||||
if (!consumed) {
|
||||
yield* Effect.logWarning("relay dpop proof replay rejected", {
|
||||
thumbprint: result.thumbprint,
|
||||
jti: result.jti,
|
||||
iat: result.iat,
|
||||
});
|
||||
return yield* new HttpApiError.Unauthorized({});
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.dpop.thumbprint": result.thumbprint,
|
||||
"relay.dpop.iat": result.iat,
|
||||
});
|
||||
return result.thumbprint;
|
||||
});
|
||||
|
||||
const pruneExpired: DpopProofReplayShape["pruneExpired"] = Effect.gen(function* () {
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* Effect.annotateCurrentSpan({ "relay.dpop_prune.before": now });
|
||||
yield* db.delete(relayDpopProofs).where(lt(relayDpopProofs.expiresAt, now));
|
||||
}).pipe(
|
||||
Effect.withSpan("relay.dpop_proofs.prune_expired"),
|
||||
Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })),
|
||||
);
|
||||
|
||||
return DpopProofReplay.of({
|
||||
verifyAndConsume,
|
||||
consume,
|
||||
pruneExpired,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DpopProofReplay, make);
|
||||
+70
-56
@@ -8,9 +8,19 @@ import {
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { verifyAndConsumeDpopProof } from "./dpop.ts";
|
||||
import * as DpopProofs from "./persistence/DpopProofs.ts";
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayDpopProofs } from "../persistence/schema.ts";
|
||||
import * as DpopProofs from "./DpopProofs.ts";
|
||||
|
||||
interface DpopProofInsertValues {
|
||||
readonly thumbprint: string;
|
||||
readonly jti: string;
|
||||
readonly iat: number;
|
||||
readonly expiresAt: string;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
function makeDpopProof(input: {
|
||||
readonly method: string;
|
||||
@@ -49,7 +59,43 @@ function makeDpopProof(input: {
|
||||
};
|
||||
}
|
||||
|
||||
describe("verifyAndConsumeDpopProof", () => {
|
||||
function layer(
|
||||
insert: (
|
||||
values: DpopProofInsertValues,
|
||||
) => Effect.Effect<ReadonlyArray<{ readonly jti: string }>, { _tag: string }>,
|
||||
) {
|
||||
const fakeDb = {
|
||||
insert: (table: unknown) => {
|
||||
expect(table).toBe(relayDpopProofs);
|
||||
return {
|
||||
values: (values: DpopProofInsertValues) => ({
|
||||
onConflictDoNothing: () => ({
|
||||
returning: (selection: unknown) => {
|
||||
expect(selection).toBeDefined();
|
||||
return insert(values);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as unknown as RelayDatabase;
|
||||
return DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb)));
|
||||
}
|
||||
|
||||
function consumeEachProofOnce() {
|
||||
const consumed = new Set<string>();
|
||||
return (values: DpopProofInsertValues) =>
|
||||
Effect.sync(() => {
|
||||
const key = `${values.thumbprint}:${values.jti}`;
|
||||
if (consumed.has(key)) {
|
||||
return [];
|
||||
}
|
||||
consumed.add(key);
|
||||
return [{ jti: values.jti }];
|
||||
});
|
||||
}
|
||||
|
||||
describe("DpopProofReplay.verifyAndConsume", () => {
|
||||
it.effect("rejects replayed proofs after persistence consumes the jti once", () => {
|
||||
const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z");
|
||||
const proof = makeDpopProof({
|
||||
@@ -58,30 +104,18 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
jti: "proof-1",
|
||||
});
|
||||
const consumed = new Set<string>();
|
||||
const dpopProofs: DpopProofs.DpopProofReplayShape = {
|
||||
consume: (input) =>
|
||||
Effect.sync(() => {
|
||||
const key = `${input.thumbprint}:${input.jti}`;
|
||||
if (consumed.has(key)) {
|
||||
return false;
|
||||
}
|
||||
consumed.add(key);
|
||||
return true;
|
||||
}),
|
||||
pruneExpired: Effect.void,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const first = yield* verifyAndConsumeDpopProof({
|
||||
const replay = yield* DpopProofs.DpopProofReplay;
|
||||
const first = yield* replay.verifyAndConsume({
|
||||
proof: proof.proof,
|
||||
method: "POST",
|
||||
url: "https://relay.example.com/v1/environments/env/connect",
|
||||
expectedThumbprint: proof.thumbprint,
|
||||
now,
|
||||
});
|
||||
const replay = yield* Effect.exit(
|
||||
verifyAndConsumeDpopProof({
|
||||
const second = yield* Effect.exit(
|
||||
replay.verifyAndConsume({
|
||||
proof: proof.proof,
|
||||
method: "POST",
|
||||
url: "https://relay.example.com/v1/environments/env/connect",
|
||||
@@ -91,8 +125,8 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
);
|
||||
|
||||
expect(first).toBe(proof.thumbprint);
|
||||
expect(replay._tag).toBe("Failure");
|
||||
}).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
|
||||
expect(second._tag).toBe("Failure");
|
||||
}).pipe(Effect.provide(layer(consumeEachProofOnce())));
|
||||
});
|
||||
|
||||
it.effect("rejects proofs missing the expected access token hash", () => {
|
||||
@@ -103,14 +137,11 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
jti: "proof-1",
|
||||
});
|
||||
const dpopProofs: DpopProofs.DpopProofReplayShape = {
|
||||
consume: () => Effect.succeed(true),
|
||||
pruneExpired: Effect.void,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const replay = yield* DpopProofs.DpopProofReplay;
|
||||
const result = yield* Effect.exit(
|
||||
verifyAndConsumeDpopProof({
|
||||
replay.verifyAndConsume({
|
||||
proof: proof.proof,
|
||||
method: "POST",
|
||||
url: "https://relay.example.com/v1/environments/env/connect",
|
||||
@@ -121,7 +152,7 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
);
|
||||
|
||||
expect(result._tag).toBe("Failure");
|
||||
}).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
|
||||
}).pipe(Effect.provide(layer(() => Effect.die("unexpected DPoP replay persistence"))));
|
||||
});
|
||||
|
||||
it.effect("preserves replay persistence failures", () => {
|
||||
@@ -132,17 +163,12 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
jti: "proof-persistence-failure",
|
||||
});
|
||||
const failure = new DpopProofs.DpopProofReplayPersistenceError({
|
||||
cause: "database unavailable",
|
||||
});
|
||||
const dpopProofs: DpopProofs.DpopProofReplayShape = {
|
||||
consume: () => Effect.fail(failure),
|
||||
pruneExpired: Effect.void,
|
||||
};
|
||||
const cause = "database unavailable";
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const replay = yield* DpopProofs.DpopProofReplay;
|
||||
const error = yield* Effect.flip(
|
||||
verifyAndConsumeDpopProof({
|
||||
replay.verifyAndConsume({
|
||||
proof: proof.proof,
|
||||
method: "POST",
|
||||
url: "https://relay.example.com/v1/environments/env/connect",
|
||||
@@ -151,11 +177,11 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toBe(failure);
|
||||
}).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
|
||||
expect(error).toEqual(new DpopProofs.DpopProofReplayPersistenceError({ cause }));
|
||||
}).pipe(Effect.provide(layer(() => Effect.fail({ _tag: cause }))));
|
||||
});
|
||||
|
||||
it.effect("accepts unbound DPoP proofs when they are bound to the access token hash", () => {
|
||||
it.effect("accepts proofs bound to the access token hash", () => {
|
||||
const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z");
|
||||
const proof = makeDpopProof({
|
||||
method: "POST",
|
||||
@@ -164,30 +190,18 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
jti: "proof-status-1",
|
||||
accessToken: "clerk-access-token",
|
||||
});
|
||||
const consumed = new Set<string>();
|
||||
const dpopProofs: DpopProofs.DpopProofReplayShape = {
|
||||
consume: (input) =>
|
||||
Effect.sync(() => {
|
||||
const key = `${input.thumbprint}:${input.jti}`;
|
||||
if (consumed.has(key)) {
|
||||
return false;
|
||||
}
|
||||
consumed.add(key);
|
||||
return true;
|
||||
}),
|
||||
pruneExpired: Effect.void,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const thumbprint = yield* verifyAndConsumeDpopProof({
|
||||
const replay = yield* DpopProofs.DpopProofReplay;
|
||||
const thumbprint = yield* replay.verifyAndConsume({
|
||||
proof: proof.proof,
|
||||
method: "POST",
|
||||
url: "https://relay.example.com/v1/environments/env/status",
|
||||
expectedAccessToken: "clerk-access-token",
|
||||
now,
|
||||
});
|
||||
const replay = yield* Effect.exit(
|
||||
verifyAndConsumeDpopProof({
|
||||
const second = yield* Effect.exit(
|
||||
replay.verifyAndConsume({
|
||||
proof: proof.proof,
|
||||
method: "POST",
|
||||
url: "https://relay.example.com/v1/environments/env/status",
|
||||
@@ -197,7 +211,7 @@ describe("verifyAndConsumeDpopProof", () => {
|
||||
);
|
||||
|
||||
expect(thumbprint).toBe(proof.thumbprint);
|
||||
expect(replay._tag).toBe("Failure");
|
||||
}).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));
|
||||
expect(second._tag).toBe("Failure");
|
||||
}).pipe(Effect.provide(layer(consumeEachProofOnce())));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { signRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as RelayTokens from "./RelayTokens.ts";
|
||||
|
||||
const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
|
||||
privateKeyEncoding: { format: "pem", type: "pkcs8" },
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
|
||||
const config = RelayConfiguration.RelayConfiguration.of({
|
||||
relayIssuer: "https://relay.example.test/",
|
||||
apns: {
|
||||
environment: "sandbox",
|
||||
teamId: "team-id",
|
||||
keyId: "key-id",
|
||||
privateKey: Redacted.make("private-key"),
|
||||
bundleId: "com.t3tools.t3code.dev",
|
||||
},
|
||||
apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),
|
||||
clerkSecretKey: Redacted.make("clerk-secret"),
|
||||
cloudMintPrivateKey: Redacted.make(keyPair.privateKey),
|
||||
cloudMintPublicKey: keyPair.publicKey,
|
||||
managedEndpointBaseDomain: undefined,
|
||||
cloudflareAccountId: undefined,
|
||||
cloudflareZoneId: undefined,
|
||||
cloudflareApiToken: undefined,
|
||||
});
|
||||
|
||||
const layer = RelayTokens.layer.pipe(
|
||||
Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, config)),
|
||||
);
|
||||
|
||||
describe("RelayTokens", () => {
|
||||
it.effect("issues a user-bound environment link challenge", () =>
|
||||
Effect.gen(function* () {
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const token = yield* relayTokens.issueLinkChallenge({
|
||||
userId: "user_123",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
},
|
||||
jti: "challenge-1",
|
||||
issuedAtEpochSeconds: 100,
|
||||
expiresAtEpochSeconds: 200,
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* relayTokens.verifyLinkChallenge({
|
||||
token,
|
||||
userId: "user_123",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
},
|
||||
nowEpochSeconds: 150,
|
||||
}),
|
||||
).toMatchObject({ sub: "user_123", jti: "challenge-1" });
|
||||
expect(
|
||||
yield* relayTokens.verifyLinkChallenge({
|
||||
token,
|
||||
userId: "attacker",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
},
|
||||
nowEpochSeconds: 150,
|
||||
}),
|
||||
).toBeNull();
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("issues and verifies DPoP access tokens bound to one proof-key thumbprint", () =>
|
||||
Effect.gen(function* () {
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const token = yield* relayTokens.issueDpopAccessToken({
|
||||
userId: "user_123",
|
||||
proofKeyThumbprint: "proof-key-thumbprint",
|
||||
jti: "access-token-1",
|
||||
issuedAtEpochSeconds: 100,
|
||||
expiresAtEpochSeconds: 200,
|
||||
clientId: "t3-mobile",
|
||||
scopes: ["environment:connect", "environment:status", "mobile:registration"],
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 }),
|
||||
).toMatchObject({
|
||||
sub: "user_123",
|
||||
cnf: { jkt: "proof-key-thumbprint" },
|
||||
client_id: "t3-mobile",
|
||||
scope: ["environment:connect", "environment:status", "mobile:registration"],
|
||||
});
|
||||
expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 261 })).toBeNull();
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("issues tunnel-only DPoP access tokens to web public clients", () =>
|
||||
Effect.gen(function* () {
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const token = yield* relayTokens.issueDpopAccessToken({
|
||||
userId: "user_123",
|
||||
proofKeyThumbprint: "web-proof-key-thumbprint",
|
||||
jti: "web-access-token-1",
|
||||
issuedAtEpochSeconds: 100,
|
||||
expiresAtEpochSeconds: 200,
|
||||
clientId: "t3-web",
|
||||
scopes: ["environment:connect", "environment:status"],
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 }),
|
||||
).toMatchObject({
|
||||
client_id: "t3-web",
|
||||
scope: ["environment:connect", "environment:status"],
|
||||
cnf: { jkt: "web-proof-key-thumbprint" },
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("treats requested scope as an order-independent set", () =>
|
||||
Effect.gen(function* () {
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
expect(
|
||||
relayTokens.resolveDpopAccessTokenScopes({
|
||||
clientId: "t3-mobile",
|
||||
scope: "environment:status environment:connect environment:status",
|
||||
}),
|
||||
).toEqual(["environment:status", "environment:connect"]);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("rejects signed DPoP tokens whose scope is outside the relay policy", () =>
|
||||
Effect.gen(function* () {
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const token = yield* signRelayJwt({
|
||||
privateKey: keyPair.privateKey,
|
||||
typ: "t3-relay-dpop-access+jwt",
|
||||
payload: {
|
||||
iss: "https://relay.example.test",
|
||||
aud: "https://relay.example.test",
|
||||
sub: "user_123",
|
||||
jti: "access-token-invalid-scope",
|
||||
iat: 100,
|
||||
exp: 200,
|
||||
client_id: "t3-mobile",
|
||||
scope: "environment:admin",
|
||||
cnf: { jkt: "proof-key-thumbprint" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("rejects mobile registration scope on a web public client token", () =>
|
||||
Effect.gen(function* () {
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const token = yield* signRelayJwt({
|
||||
privateKey: keyPair.privateKey,
|
||||
typ: "t3-relay-dpop-access+jwt",
|
||||
payload: {
|
||||
iss: "https://relay.example.test",
|
||||
aud: "https://relay.example.test",
|
||||
sub: "user_123",
|
||||
jti: "web-token-invalid-mobile-scope",
|
||||
iat: 100,
|
||||
exp: 200,
|
||||
client_id: "t3-web",
|
||||
scope: "environment:connect mobile:registration",
|
||||
cnf: { jkt: "proof-key-thumbprint" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import {
|
||||
RelayDpopAccessTokenScope,
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
RelayMobileClientId,
|
||||
RelayMobileRegistrationScope,
|
||||
RelayWebClientId,
|
||||
type RelayPublicClientId,
|
||||
type RelayEnvironmentLinkChallengeRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import {
|
||||
normalizeRelayIssuer,
|
||||
signRelayJwt,
|
||||
verifyRelayJwt,
|
||||
type RelayJwtError,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt";
|
||||
const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt";
|
||||
const LINK_CHALLENGE_KIND = "environment_link_challenge";
|
||||
|
||||
const LinkChallengeClaims = Schema.Struct({
|
||||
kind: Schema.Literal(LINK_CHALLENGE_KIND),
|
||||
iss: Schema.String,
|
||||
aud: Schema.String,
|
||||
sub: Schema.String,
|
||||
jti: Schema.String,
|
||||
iat: Schema.Int,
|
||||
exp: Schema.Int,
|
||||
notificationsEnabled: Schema.Boolean,
|
||||
liveActivitiesEnabled: Schema.Boolean,
|
||||
managedTunnelsEnabled: Schema.Boolean,
|
||||
});
|
||||
export type LinkChallengeClaims = typeof LinkChallengeClaims.Type;
|
||||
|
||||
const RelayDpopAccessTokenClaims = Schema.Struct({
|
||||
iss: Schema.String,
|
||||
aud: Schema.String,
|
||||
sub: Schema.String,
|
||||
jti: Schema.String,
|
||||
iat: Schema.Int,
|
||||
exp: Schema.Int,
|
||||
client_id: Schema.Literals([RelayMobileClientId, RelayWebClientId]),
|
||||
scope: Schema.String,
|
||||
cnf: Schema.Struct({ jkt: Schema.String }),
|
||||
});
|
||||
export type RelayDpopAccessTokenClaims = Omit<typeof RelayDpopAccessTokenClaims.Type, "scope"> & {
|
||||
readonly scope: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
};
|
||||
|
||||
const decodeLinkChallengeClaims = Schema.decodeUnknownEffect(LinkChallengeClaims);
|
||||
const decodeDpopAccessTokenClaims = Schema.decodeUnknownEffect(RelayDpopAccessTokenClaims);
|
||||
|
||||
const allowedScopesByClientId: Record<
|
||||
RelayPublicClientId,
|
||||
ReadonlySet<RelayDpopAccessTokenScope>
|
||||
> = {
|
||||
[RelayMobileClientId]: new Set([
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
RelayMobileRegistrationScope,
|
||||
]),
|
||||
[RelayWebClientId]: new Set([RelayEnvironmentConnectScope, RelayEnvironmentStatusScope]),
|
||||
};
|
||||
|
||||
function resolveDpopAccessTokenScopes(input: {
|
||||
readonly clientId: RelayPublicClientId;
|
||||
readonly scope: string;
|
||||
}): ReadonlyArray<RelayDpopAccessTokenScope> | null {
|
||||
return parseAllowedOAuthScope({
|
||||
value: input.scope,
|
||||
allowedScopes: allowedScopesByClientId[input.clientId],
|
||||
});
|
||||
}
|
||||
|
||||
export interface RelayTokensShape {
|
||||
readonly resolveDpopAccessTokenScopes: typeof resolveDpopAccessTokenScopes;
|
||||
readonly issueLinkChallenge: (input: {
|
||||
readonly userId: string;
|
||||
readonly request: RelayEnvironmentLinkChallengeRequest;
|
||||
readonly jti: string;
|
||||
readonly issuedAtEpochSeconds: number;
|
||||
readonly expiresAtEpochSeconds: number;
|
||||
}) => Effect.Effect<string, RelayJwtError>;
|
||||
readonly verifyLinkChallenge: (input: {
|
||||
readonly token: string;
|
||||
readonly userId: string;
|
||||
readonly request: RelayEnvironmentLinkChallengeRequest;
|
||||
readonly nowEpochSeconds: number;
|
||||
}) => Effect.Effect<LinkChallengeClaims | null>;
|
||||
readonly issueDpopAccessToken: (input: {
|
||||
readonly userId: string;
|
||||
readonly proofKeyThumbprint: string;
|
||||
readonly jti: string;
|
||||
readonly issuedAtEpochSeconds: number;
|
||||
readonly expiresAtEpochSeconds: number;
|
||||
readonly clientId: RelayPublicClientId;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
}) => Effect.Effect<string, RelayJwtError>;
|
||||
readonly verifyDpopAccessToken: (input: {
|
||||
readonly token: string;
|
||||
readonly nowEpochSeconds: number;
|
||||
}) => Effect.Effect<RelayDpopAccessTokenClaims | null>;
|
||||
}
|
||||
|
||||
export class RelayTokens extends Context.Service<RelayTokens, RelayTokensShape>()(
|
||||
"t3code-relay/auth/RelayTokens",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
const issuer = normalizeRelayIssuer(config.relayIssuer);
|
||||
|
||||
const issueLinkChallenge: RelayTokensShape["issueLinkChallenge"] = Effect.fn(
|
||||
"relay.tokens.issue_link_challenge",
|
||||
)(function* (input) {
|
||||
return yield* signRelayJwt({
|
||||
privateKey: Redacted.value(config.cloudMintPrivateKey),
|
||||
typ: LINK_CHALLENGE_TYP,
|
||||
payload: {
|
||||
kind: LINK_CHALLENGE_KIND,
|
||||
iss: issuer,
|
||||
aud: issuer,
|
||||
sub: input.userId,
|
||||
jti: input.jti,
|
||||
iat: input.issuedAtEpochSeconds,
|
||||
exp: input.expiresAtEpochSeconds,
|
||||
...input.request,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const verifyLinkChallenge: RelayTokensShape["verifyLinkChallenge"] = Effect.fn(
|
||||
"relay.tokens.verify_link_challenge",
|
||||
)((input) =>
|
||||
verifyRelayJwt({
|
||||
publicKey: config.cloudMintPublicKey,
|
||||
token: input.token,
|
||||
typ: LINK_CHALLENGE_TYP,
|
||||
issuer,
|
||||
audience: issuer,
|
||||
nowEpochSeconds: input.nowEpochSeconds,
|
||||
}).pipe(
|
||||
Effect.flatMap(decodeLinkChallengeClaims),
|
||||
Effect.map((claims) => {
|
||||
if (
|
||||
claims.sub !== input.userId ||
|
||||
(input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||
|
||||
(input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||
|
||||
(input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return claims;
|
||||
}),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
),
|
||||
);
|
||||
|
||||
const issueDpopAccessToken: RelayTokensShape["issueDpopAccessToken"] = Effect.fn(
|
||||
"relay.tokens.issue_dpop_access_token",
|
||||
)(function* (input) {
|
||||
return yield* signRelayJwt({
|
||||
privateKey: Redacted.value(config.cloudMintPrivateKey),
|
||||
typ: ACCESS_TOKEN_TYP,
|
||||
payload: {
|
||||
iss: issuer,
|
||||
aud: issuer,
|
||||
sub: input.userId,
|
||||
jti: input.jti,
|
||||
iat: input.issuedAtEpochSeconds,
|
||||
exp: input.expiresAtEpochSeconds,
|
||||
client_id: input.clientId,
|
||||
scope: encodeOAuthScope(input.scopes),
|
||||
cnf: { jkt: input.proofKeyThumbprint },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const verifyDpopAccessToken: RelayTokensShape["verifyDpopAccessToken"] = Effect.fn(
|
||||
"relay.tokens.verify_dpop_access_token",
|
||||
)((input) =>
|
||||
verifyRelayJwt({
|
||||
publicKey: config.cloudMintPublicKey,
|
||||
token: input.token,
|
||||
typ: ACCESS_TOKEN_TYP,
|
||||
issuer,
|
||||
audience: issuer,
|
||||
nowEpochSeconds: input.nowEpochSeconds,
|
||||
}).pipe(
|
||||
Effect.flatMap(decodeDpopAccessTokenClaims),
|
||||
Effect.map((claims): RelayDpopAccessTokenClaims | null => {
|
||||
const scopes = resolveDpopAccessTokenScopes({
|
||||
clientId: claims.client_id,
|
||||
scope: claims.scope,
|
||||
});
|
||||
return scopes === null ? null : { ...claims, scope: scopes };
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
),
|
||||
);
|
||||
|
||||
return RelayTokens.of({
|
||||
resolveDpopAccessTokenScopes,
|
||||
issueLinkChallenge,
|
||||
verifyLinkChallenge,
|
||||
issueDpopAccessToken,
|
||||
verifyDpopAccessToken,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(RelayTokens, make);
|
||||
@@ -1,182 +0,0 @@
|
||||
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
|
||||
import * as NodePath from "@effect/platform-node/NodePath";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { relayPostgresDatabaseRegion } from "./db.ts";
|
||||
import { parseJsonString } from "./persistence/json.ts";
|
||||
|
||||
const migrationsDir = "migrations/postgres";
|
||||
const schemaFile = "src/schema.ts";
|
||||
const NodeTestServices = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
|
||||
|
||||
class DbMigrationTestError extends Data.TaggedError("DbMigrationTestError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
interface DrizzleKitPostgresApi {
|
||||
readonly generateDrizzleJson: (
|
||||
imports: Record<string, unknown>,
|
||||
prevId?: string,
|
||||
schemaFilters?: ReadonlyArray<string>,
|
||||
) => Promise<unknown>;
|
||||
readonly generateMigration: (prev: unknown, cur: unknown) => Promise<ReadonlyArray<string>>;
|
||||
}
|
||||
|
||||
const readMigrationDirectories = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const entries = yield* fs.readDirectory(migrationsDir);
|
||||
const directories = yield* Effect.all(
|
||||
entries.map((entry) =>
|
||||
fs
|
||||
.stat(path.join(migrationsDir, entry))
|
||||
.pipe(Effect.map((stat) => (stat.type === "Directory" ? entry : null))),
|
||||
),
|
||||
);
|
||||
return directories.filter((entry): entry is string => entry !== null).sort();
|
||||
});
|
||||
|
||||
const readMigrationSqlFiles = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directories = yield* readMigrationDirectories;
|
||||
const files = yield* Effect.all(
|
||||
directories.map((directory) =>
|
||||
Effect.gen(function* () {
|
||||
const migrationPath = path.join(migrationsDir, directory, "migration.sql");
|
||||
const exists = yield* fs.exists(migrationPath);
|
||||
if (!exists) return null;
|
||||
const sql = yield* fs.readFileString(migrationPath);
|
||||
return { directory, sql };
|
||||
}),
|
||||
),
|
||||
);
|
||||
return files.filter(
|
||||
(file): file is { readonly directory: string; readonly sql: string } => file !== null,
|
||||
);
|
||||
});
|
||||
|
||||
const readLatestMigrationSnapshot = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directories = yield* readMigrationDirectories;
|
||||
const directoriesWithSnapshots = yield* Effect.all(
|
||||
directories.map((directory) =>
|
||||
fs
|
||||
.exists(path.join(migrationsDir, directory, "snapshot.json"))
|
||||
.pipe(Effect.map((exists) => (exists ? directory : null))),
|
||||
),
|
||||
);
|
||||
const latestDirectory = directoriesWithSnapshots.findLast(
|
||||
(directory): directory is string => directory !== null,
|
||||
);
|
||||
if (!latestDirectory) {
|
||||
return null;
|
||||
}
|
||||
const snapshotPath = path.join(migrationsDir, latestDirectory, "snapshot.json");
|
||||
const exists = yield* fs.exists(snapshotPath);
|
||||
if (!exists) {
|
||||
return {
|
||||
directory: latestDirectory,
|
||||
snapshot: null,
|
||||
};
|
||||
}
|
||||
const snapshot = yield* parseJsonString(yield* fs.readFileString(snapshotPath));
|
||||
return {
|
||||
directory: latestDirectory,
|
||||
snapshot,
|
||||
};
|
||||
});
|
||||
|
||||
const loadDrizzleKit = Effect.tryPromise({
|
||||
try: () => import("drizzle-kit/api-postgres") as Promise<DrizzleKitPostgresApi>,
|
||||
catch: (cause) =>
|
||||
new DbMigrationTestError({
|
||||
message: "failed to load drizzle-kit postgres api",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const loadRelaySchema = Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => import(path.resolve(schemaFile)) as Promise<Record<string, unknown>>,
|
||||
catch: (cause) =>
|
||||
new DbMigrationTestError({
|
||||
message: "failed to load relay schema",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay database migrations", () => {
|
||||
it("pins the PlanetScale database near west coast Worker traffic", () => {
|
||||
expect(relayPostgresDatabaseRegion).toEqual({ slug: "us-west" });
|
||||
});
|
||||
|
||||
it.effect("does not leave empty generated migration directories behind", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directories = yield* readMigrationDirectories;
|
||||
const emptyDirectories = yield* Effect.all(
|
||||
directories.map((directory) =>
|
||||
fs
|
||||
.readDirectory(path.join(migrationsDir, directory))
|
||||
.pipe(Effect.map((entries) => (entries.length === 0 ? directory : null))),
|
||||
),
|
||||
).pipe(Effect.map((entries) => entries.filter((entry): entry is string => entry !== null)));
|
||||
|
||||
expect(emptyDirectories).toEqual([]);
|
||||
}).pipe(Effect.provide(NodeTestServices)),
|
||||
);
|
||||
|
||||
it.effect("starts from a single baseline migration", () =>
|
||||
Effect.gen(function* () {
|
||||
const migrations = yield* readMigrationSqlFiles;
|
||||
|
||||
expect(migrations).toHaveLength(1);
|
||||
expect(migrations[0]?.directory).toContain("baseline");
|
||||
expect(migrations[0]?.sql).toContain('CREATE TABLE "relay_environment_credentials"');
|
||||
expect(migrations[0]?.sql).toContain('"environment_public_key" text NOT NULL');
|
||||
}).pipe(Effect.provide(NodeTestServices)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"keeps the latest migration snapshot aligned with the relay schema",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const latest = yield* readLatestMigrationSnapshot;
|
||||
expect(latest).not.toBeNull();
|
||||
expect(latest?.snapshot, `${latest?.directory} is missing snapshot.json`).not.toBeNull();
|
||||
|
||||
const kit = yield* loadDrizzleKit;
|
||||
const relaySchema = yield* loadRelaySchema;
|
||||
const currentSnapshot = yield* Effect.tryPromise({
|
||||
try: () => kit.generateDrizzleJson(relaySchema),
|
||||
catch: (cause) =>
|
||||
new DbMigrationTestError({
|
||||
message: "failed to generate current drizzle snapshot",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const statements = yield* Effect.tryPromise({
|
||||
try: () => kit.generateMigration(latest?.snapshot, currentSnapshot),
|
||||
catch: (cause) =>
|
||||
new DbMigrationTestError({
|
||||
message: "failed to diff relay schema",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(statements).toEqual([]);
|
||||
}).pipe(Effect.provide(NodeTestServices)),
|
||||
20_000,
|
||||
);
|
||||
});
|
||||
+8
-11
@@ -10,20 +10,17 @@ export interface RelayDatabase extends EffectPgDatabase {
|
||||
readonly $client: PgClient;
|
||||
}
|
||||
|
||||
export class RelayDb extends Context.Service<RelayDb, RelayDatabase>()("RelayDb") {}
|
||||
|
||||
export const relayPostgresDatabaseRegion = { slug: "us-west" } as const;
|
||||
|
||||
export const RelaySchema = Drizzle.Schema("RelaySchema", {
|
||||
schema: "./src/schema.ts",
|
||||
out: "./migrations/postgres",
|
||||
dialect: "postgres",
|
||||
});
|
||||
export class RelayDb extends Context.Service<RelayDb, RelayDatabase>()("t3code-relay/db/RelayDb") {}
|
||||
|
||||
export const PlanetscaleDatabase = Effect.gen(function* () {
|
||||
const schema = yield* RelaySchema;
|
||||
const schema = yield* Drizzle.Schema("RelaySchema", {
|
||||
schema: "./src/persistence/schema.ts",
|
||||
out: "./migrations/postgres",
|
||||
dialect: "postgres",
|
||||
});
|
||||
|
||||
const database = yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", {
|
||||
region: relayPostgresDatabaseRegion,
|
||||
region: { slug: "us-west" },
|
||||
clusterSize: "PS_5",
|
||||
migrationsDir: schema.out,
|
||||
migrationsTable: "relay_migrations",
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { verifyDpopProof } from "@t3tools/shared/dpop";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";
|
||||
|
||||
import * as DpopProofs from "./persistence/DpopProofs.ts";
|
||||
|
||||
export const verifyAndConsumeDpopProof = Effect.fn("relay.dpop.verify_and_consume")(
|
||||
function* (input: {
|
||||
readonly proof: string | undefined;
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
readonly expectedThumbprint?: string;
|
||||
readonly expectedAccessToken?: string;
|
||||
readonly now: DateTime.DateTime;
|
||||
}) {
|
||||
const dpopProofs = yield* DpopProofs.DpopProofReplay;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.dpop.method": input.method,
|
||||
"relay.dpop.expected_thumbprint_present": input.expectedThumbprint !== undefined,
|
||||
"relay.dpop.expected_access_token_present": input.expectedAccessToken !== undefined,
|
||||
});
|
||||
const result = verifyDpopProof({
|
||||
proof: input.proof,
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
});
|
||||
if (!result.ok) {
|
||||
yield* Effect.logWarning("relay dpop proof rejected", {
|
||||
reason: result.reason,
|
||||
method: input.method,
|
||||
url: input.url,
|
||||
expectedThumbprintPresent: input.expectedThumbprint !== undefined,
|
||||
expectedAccessTokenPresent: input.expectedAccessToken !== undefined,
|
||||
});
|
||||
return yield* new HttpApiError.Unauthorized({});
|
||||
}
|
||||
const consumed = yield* dpopProofs.consume({
|
||||
thumbprint: result.thumbprint,
|
||||
jti: result.jti,
|
||||
iat: result.iat,
|
||||
expiresAt: DateTime.add(input.now, { minutes: 5 }),
|
||||
});
|
||||
if (!consumed) {
|
||||
yield* Effect.logWarning("relay dpop proof replay rejected", {
|
||||
thumbprint: result.thumbprint,
|
||||
jti: result.jti,
|
||||
iat: result.iat,
|
||||
});
|
||||
return yield* new HttpApiError.Unauthorized({});
|
||||
}
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.dpop.thumbprint": result.thumbprint,
|
||||
"relay.dpop.iat": result.iat,
|
||||
});
|
||||
return result.thumbprint;
|
||||
},
|
||||
);
|
||||
+25
-31
@@ -1,11 +1,11 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
|
||||
|
||||
import type {
|
||||
RelayCloudEnvironmentHealthProofPayload,
|
||||
import {
|
||||
RelayCloudEnvironmentHealthRequest,
|
||||
RelayCloudMintCredentialProofPayload,
|
||||
RelayCloudMintCredentialRequest,
|
||||
RelayCloudEnvironmentHealthProofPayload,
|
||||
RelayCloudMintCredentialProofPayload,
|
||||
RelayEnvironmentHealthResponse,
|
||||
RelayEnvironmentHealthResponseProofPayload,
|
||||
RelayEnvironmentMintResponse,
|
||||
@@ -20,10 +20,11 @@ import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as EnvironmentConnector from "./EnvironmentConnector.ts";
|
||||
|
||||
@@ -42,6 +43,17 @@ const otherEnvironmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
|
||||
const decodeHealthRequestBody = Schema.decodeUnknownSync(
|
||||
Schema.fromJsonString(RelayCloudEnvironmentHealthRequest),
|
||||
);
|
||||
const decodeMintRequestBody = Schema.decodeUnknownSync(
|
||||
Schema.fromJsonString(RelayCloudMintCredentialRequest),
|
||||
);
|
||||
|
||||
function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
|
||||
return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";
|
||||
}
|
||||
|
||||
const settings = RelayConfiguration.RelayConfiguration.of({
|
||||
relayIssuer: "https://relay.example.test",
|
||||
apns: {
|
||||
@@ -185,9 +197,7 @@ describe("EnvironmentConnector", () => {
|
||||
const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const healthRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudEnvironmentHealthRequest;
|
||||
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
|
||||
seenUrls.push(request.url);
|
||||
seenProofs.push(decodeRequestProof(healthRequest.proof));
|
||||
return HttpClientResponse.fromWeb(
|
||||
@@ -225,9 +235,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("rejects signed health responses with stale checkedAt timestamps", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const healthRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudEnvironmentHealthRequest;
|
||||
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(
|
||||
@@ -293,9 +301,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("rejects health responses with a mismatched top-level environment id", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const healthRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudEnvironmentHealthRequest;
|
||||
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(
|
||||
@@ -326,9 +332,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("rejects health responses with an unsigned top-level descriptor mutation", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const healthRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudEnvironmentHealthRequest;
|
||||
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
|
||||
const response = signHealthResponse(healthRequest);
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
@@ -364,9 +368,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("rejects health responses when the linked environment public key is malformed", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const healthRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudEnvironmentHealthRequest;
|
||||
const healthRequest = decodeHealthRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(signHealthResponse(healthRequest), { status: 200 }),
|
||||
@@ -402,9 +404,7 @@ describe("EnvironmentConnector", () => {
|
||||
const seenProofs: Array<RelayCloudMintCredentialProofPayload> = [];
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const mintRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudMintCredentialRequest;
|
||||
const mintRequest = decodeMintRequestBody(requestBodyText(request));
|
||||
seenUrls.push(request.url);
|
||||
seenProofs.push(decodeRequestProof(mintRequest.proof));
|
||||
return HttpClientResponse.fromWeb(
|
||||
@@ -447,9 +447,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("only accepts mint responses signed by the user's linked environment key", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const mintRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudMintCredentialRequest;
|
||||
const mintRequest = decodeMintRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(signMintResponse(mintRequest, {}, otherEnvironmentKeyPair.privateKey), {
|
||||
@@ -478,9 +476,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("rejects mint responses when the linked environment public key is malformed", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const mintRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudMintCredentialRequest;
|
||||
const mintRequest = decodeMintRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(signMintResponse(mintRequest), { status: 200 }),
|
||||
@@ -515,9 +511,7 @@ describe("EnvironmentConnector", () => {
|
||||
it.effect("rejects environment mint responses with an overlong credential window", () => {
|
||||
const execute = (request: HttpClientRequest.HttpClientRequest) =>
|
||||
Effect.sync(() => {
|
||||
const mintRequest = JSON.parse(
|
||||
request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}",
|
||||
) as RelayCloudMintCredentialRequest;
|
||||
const mintRequest = decodeMintRequestBody(requestBodyText(request));
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json(
|
||||
+157
-166
@@ -38,9 +38,8 @@ import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import { withUserId } from "../telemetry.ts";
|
||||
|
||||
export class EnvironmentConnectNotAuthorized extends Data.TaggedError(
|
||||
"EnvironmentConnectNotAuthorized",
|
||||
@@ -91,7 +90,7 @@ export interface EnvironmentConnectorShape {
|
||||
export class EnvironmentConnector extends Context.Service<
|
||||
EnvironmentConnector,
|
||||
EnvironmentConnectorShape
|
||||
>()("EnvironmentConnector") {}
|
||||
>()("t3code-relay/environments/EnvironmentConnector") {}
|
||||
|
||||
const decodeMintResponseProof = Schema.decodeUnknownEffect(
|
||||
RelayEnvironmentMintResponseProofPayload,
|
||||
@@ -139,7 +138,7 @@ const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A, E>(input: {
|
||||
});
|
||||
|
||||
function verifyEnvironmentResponse(input: {
|
||||
readonly response: typeof RelayEnvironmentMintResponse.Type;
|
||||
readonly response: RelayEnvironmentMintResponse;
|
||||
readonly environmentId: string;
|
||||
readonly requestNonce: string;
|
||||
readonly clientProofKeyThumbprint: string;
|
||||
@@ -172,7 +171,7 @@ function verifyEnvironmentResponse(input: {
|
||||
}
|
||||
|
||||
function verifyEnvironmentHealthResponse(input: {
|
||||
readonly response: typeof RelayEnvironmentHealthResponse.Type;
|
||||
readonly response: RelayEnvironmentHealthResponse;
|
||||
readonly environmentId: string;
|
||||
readonly requestNonce: string;
|
||||
readonly requestIssuedAt: DateTime.DateTime;
|
||||
@@ -227,170 +226,162 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
return EnvironmentConnector.of({
|
||||
status: Effect.fn("relay.environment_connector.status")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
"relay.operation": "status",
|
||||
});
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
status: Effect.fn("relay.environment_connector.status")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
"relay.operation": "status",
|
||||
});
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
environmentId: link.environmentId,
|
||||
nonce,
|
||||
scope: ["environment:status"],
|
||||
} satisfies RelayCloudEnvironmentHealthProofPayload;
|
||||
const proof = yield* signRelayJwt({
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_HEALTH_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
const checkedAt = DateTime.formatIso(now);
|
||||
const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl);
|
||||
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
|
||||
Effect.match({
|
||||
onFailure: (cause) => ({ _tag: "Failure" as const, cause }),
|
||||
onSuccess: (response) => ({ _tag: "Success" as const, response }),
|
||||
}),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
);
|
||||
if (Option.isNone(responseOption)) {
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
nonce,
|
||||
scope: ["environment:status"],
|
||||
} satisfies typeof RelayCloudEnvironmentHealthProofPayload.Type;
|
||||
const proof = yield* signRelayJwt({
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_HEALTH_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
const checkedAt = DateTime.formatIso(now);
|
||||
const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl);
|
||||
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
|
||||
Effect.match({
|
||||
onFailure: (cause) => ({ _tag: "Failure" as const, cause }),
|
||||
onSuccess: (response) => ({ _tag: "Success" as const, response }),
|
||||
endpoint: link.endpoint,
|
||||
status: "offline" as const,
|
||||
checkedAt,
|
||||
error: "Managed endpoint health request timed out.",
|
||||
};
|
||||
}
|
||||
if (responseOption.value._tag === "Failure") {
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
status: "offline" as const,
|
||||
checkedAt,
|
||||
error: environmentHealthRequestFailureMessage(responseOption.value.cause),
|
||||
};
|
||||
}
|
||||
const decoded = responseOption.value.response;
|
||||
const verified = yield* verifyEnvironmentHealthResponse({
|
||||
response: decoded,
|
||||
environmentId: input.environmentId,
|
||||
requestNonce: nonce,
|
||||
requestIssuedAt: now,
|
||||
environmentPublicKeys: [link.environmentPublicKey],
|
||||
relayIssuer,
|
||||
now: yield* DateTime.now,
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
status: "online" as const,
|
||||
checkedAt: decoded.checkedAt,
|
||||
descriptor: decoded.descriptor,
|
||||
};
|
||||
}),
|
||||
connect: Effect.fn("relay.environment_connector.connect")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
"relay.operation": "connect",
|
||||
"relay.connect.has_device_id": input.deviceId !== undefined,
|
||||
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
|
||||
});
|
||||
if (input.clientProofKeyThumbprint.trim().length === 0) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
environmentId: link.environmentId,
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cnf: { jkt: input.clientProofKeyThumbprint },
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
nonce,
|
||||
scope: ["environment:connect"],
|
||||
} satisfies RelayCloudMintCredentialProofPayload;
|
||||
const proof = yield* signRelayJwt({
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_MINT_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl);
|
||||
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EnvironmentMintRequestTimedOut({
|
||||
environmentId: input.environmentId,
|
||||
timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
);
|
||||
if (Option.isNone(responseOption)) {
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
status: "offline" as const,
|
||||
checkedAt,
|
||||
error: "Managed endpoint health request timed out.",
|
||||
};
|
||||
}
|
||||
if (responseOption.value._tag === "Failure") {
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
status: "offline" as const,
|
||||
checkedAt,
|
||||
error: environmentHealthRequestFailureMessage(responseOption.value.cause),
|
||||
};
|
||||
}
|
||||
const decoded = responseOption.value.response;
|
||||
const verified = yield* verifyEnvironmentHealthResponse({
|
||||
response: decoded,
|
||||
environmentId: input.environmentId,
|
||||
requestNonce: nonce,
|
||||
requestIssuedAt: now,
|
||||
environmentPublicKeys: [link.environmentPublicKey],
|
||||
relayIssuer,
|
||||
now: yield* DateTime.now,
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
status: "online" as const,
|
||||
checkedAt: decoded.checkedAt,
|
||||
descriptor: decoded.descriptor,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
connect: Effect.fn("relay.environment_connector.connect")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": input.environmentId,
|
||||
"relay.operation": "connect",
|
||||
"relay.connect.has_device_id": input.deviceId !== undefined,
|
||||
...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),
|
||||
});
|
||||
if (input.clientProofKeyThumbprint.trim().length === 0) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const link = yield* links.getForUser(input);
|
||||
if (!link) {
|
||||
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 2 });
|
||||
const nonce = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
);
|
||||
const payload = {
|
||||
iss: relayIssuer,
|
||||
aud: `t3-env:${link.environmentId}`,
|
||||
sub: input.userId,
|
||||
jti: yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
),
|
||||
iat: Math.floor(now.epochMilliseconds / 1_000),
|
||||
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
environmentId: link.environmentId,
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
cnf: { jkt: input.clientProofKeyThumbprint },
|
||||
...(input.deviceId ? { deviceId: input.deviceId } : {}),
|
||||
nonce,
|
||||
scope: ["environment:connect"],
|
||||
} satisfies typeof RelayCloudMintCredentialProofPayload.Type;
|
||||
const proof = yield* signRelayJwt({
|
||||
privateKey: Redacted.value(settings.cloudMintPrivateKey),
|
||||
typ: RELAY_MINT_REQUEST_TYP,
|
||||
payload,
|
||||
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
|
||||
const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl);
|
||||
const decoded = yield* environmentClient.cloud
|
||||
.t3MintCredential({ payload: { proof } })
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
|
||||
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new EnvironmentMintRequestTimedOut({
|
||||
environmentId: input.environmentId,
|
||||
timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const verified = yield* verifyEnvironmentResponse({
|
||||
response: decoded,
|
||||
environmentId: input.environmentId,
|
||||
requestNonce: nonce,
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
environmentPublicKeys: [link.environmentPublicKey],
|
||||
relayIssuer,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
credential: decoded.credential,
|
||||
expiresAt: decoded.expiresAt,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const verified = yield* verifyEnvironmentResponse({
|
||||
response: decoded,
|
||||
environmentId: input.environmentId,
|
||||
requestNonce: nonce,
|
||||
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
|
||||
environmentPublicKeys: [link.environmentPublicKey],
|
||||
relayIssuer,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
if (!verified) {
|
||||
return yield* new EnvironmentMintResponseInvalid({ environmentId: input.environmentId });
|
||||
}
|
||||
return {
|
||||
environmentId: link.environmentId,
|
||||
endpoint: link.endpoint,
|
||||
credential: decoded.credential,
|
||||
expiresAt: decoded.expiresAt,
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayEnvironmentCredentials } from "../schema.ts";
|
||||
import { relayEnvironmentCredentials } from "../persistence/schema.ts";
|
||||
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
|
||||
|
||||
describe("EnvironmentCredentials", () => {
|
||||
+2
-2
@@ -9,7 +9,7 @@ import * as Option from "effect/Option";
|
||||
import { and, eq, isNull, ne } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayEnvironmentCredentials } from "../schema.ts";
|
||||
import { relayEnvironmentCredentials } from "../persistence/schema.ts";
|
||||
|
||||
export class EnvironmentCredentialCreatePersistenceError extends Data.TaggedError(
|
||||
"EnvironmentCredentialCreatePersistenceError",
|
||||
@@ -55,7 +55,7 @@ export interface EnvironmentCredentialsShape {
|
||||
export class EnvironmentCredentials extends Context.Service<
|
||||
EnvironmentCredentials,
|
||||
EnvironmentCredentialsShape
|
||||
>()("EnvironmentCredentials") {}
|
||||
>()("t3code-relay/environments/EnvironmentCredentials") {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const db = yield* RelayDb;
|
||||
+8
-6
@@ -11,13 +11,13 @@ import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Result from "effect/Result";
|
||||
|
||||
import * as DpopProofs from "../persistence/DpopProofs.ts";
|
||||
import * as EnvironmentCredentials from "../persistence/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayTokens from "../auth/RelayTokens.ts";
|
||||
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as EnvironmentLinker from "./EnvironmentLinker.ts";
|
||||
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
|
||||
import { issueLinkChallengeToken } from "../relayTokens.ts";
|
||||
|
||||
const relayKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
|
||||
privateKeyEncoding: { format: "pem", type: "pkcs8" },
|
||||
@@ -56,8 +56,8 @@ function signTestJwt(payload: object, typ: string, privateKey: string): string {
|
||||
const makeRequest = Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 5 });
|
||||
const challenge = yield* issueLinkChallengeToken({
|
||||
config,
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const challenge = yield* relayTokens.issueLinkChallenge({
|
||||
userId: "user_123",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
@@ -109,10 +109,12 @@ function testLayer(input?: {
|
||||
readonly consume?: DpopProofs.DpopProofReplayShape["consume"];
|
||||
}) {
|
||||
return EnvironmentLinker.layer.pipe(
|
||||
Layer.provideMerge(RelayTokens.layer),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(RelayConfiguration.RelayConfiguration, config),
|
||||
Layer.succeed(DpopProofs.DpopProofReplay, {
|
||||
verifyAndConsume: () => Effect.die("unexpected DPoP proof verification"),
|
||||
consume: input?.consume ?? (() => Effect.succeed(true)),
|
||||
pruneExpired: Effect.void,
|
||||
}),
|
||||
@@ -0,0 +1,263 @@
|
||||
import {
|
||||
RelayEnvironmentLinkProofPayload,
|
||||
type RelayEnvironmentLinkProofInvalidReason,
|
||||
type RelayEnvironmentLinkRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import {
|
||||
decodeRelayJwt,
|
||||
normalizeRelayIssuer,
|
||||
RELAY_LINK_PROOF_TYP,
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayTokens from "../auth/RelayTokens.ts";
|
||||
import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
|
||||
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{
|
||||
readonly environmentId: string;
|
||||
readonly reason: RelayEnvironmentLinkProofInvalidReason;
|
||||
}> {}
|
||||
|
||||
export type EnvironmentLinkError =
|
||||
| EnvironmentLinkProofExpired
|
||||
| EnvironmentLinkProofInvalid
|
||||
| DpopProofs.DpopProofReplayPersistenceError
|
||||
| EnvironmentLinks.EnvironmentLinkUpsertPersistenceError
|
||||
| EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError
|
||||
| ManagedEndpointProvider.ManagedEndpointProviderError;
|
||||
|
||||
export interface EnvironmentLinkerShape {
|
||||
readonly link: (input: {
|
||||
readonly userId: string;
|
||||
readonly request: RelayEnvironmentLinkRequest;
|
||||
}) => Effect.Effect<
|
||||
{
|
||||
readonly environmentId: RelayEnvironmentLinkProofPayload["environmentId"];
|
||||
readonly endpoint: RelayEnvironmentLinkProofPayload["endpoint"];
|
||||
readonly endpointRuntime:
|
||||
| ManagedEndpointProvider.ManagedEndpointProvisioningResult["runtime"]
|
||||
| null;
|
||||
readonly environmentCredential: string;
|
||||
},
|
||||
EnvironmentLinkError
|
||||
>;
|
||||
}
|
||||
|
||||
export class EnvironmentLinker extends Context.Service<EnvironmentLinker, EnvironmentLinkerShape>()(
|
||||
"t3code-relay/environments/EnvironmentLinker",
|
||||
) {}
|
||||
|
||||
const decodeProof = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);
|
||||
|
||||
function proofAuthorizesRequestedCapabilities(
|
||||
proof: RelayEnvironmentLinkProofPayload,
|
||||
request: RelayEnvironmentLinkRequest,
|
||||
): boolean {
|
||||
const scopes = new Set(proof.scopes);
|
||||
if (request.managedTunnelsEnabled && !scopes.has("managed_tunnels")) {
|
||||
return false;
|
||||
}
|
||||
return !(
|
||||
(request.notificationsEnabled || request.liveActivitiesEnabled) &&
|
||||
!scopes.has("agent_activity_notifications")
|
||||
);
|
||||
}
|
||||
|
||||
function isSecureManagedEndpoint(endpoint: RelayEnvironmentLinkProofPayload["endpoint"]): boolean {
|
||||
try {
|
||||
const httpUrl = new URL(endpoint.httpBaseUrl);
|
||||
const wsUrl = new URL(endpoint.wsBaseUrl);
|
||||
return httpUrl.protocol === "https:" && wsUrl.protocol === "wss:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHostname(hostname: string): string {
|
||||
return hostname
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[(.*)\]$/u, "$1");
|
||||
}
|
||||
|
||||
function isLoopbackManagedTunnelOrigin(
|
||||
origin: RelayEnvironmentLinkProofPayload["origin"],
|
||||
): boolean {
|
||||
const hostname = normalizeHostname(origin.localHttpHost);
|
||||
return (
|
||||
(hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
|
||||
Number.isInteger(origin.localHttpPort) &&
|
||||
origin.localHttpPort > 0 &&
|
||||
origin.localHttpPort <= 65_535
|
||||
);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const proofReplay = yield* DpopProofs.DpopProofReplay;
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
|
||||
return EnvironmentLinker.of({
|
||||
link: Effect.fn("relay.environment_linker.link")(function* (input) {
|
||||
const now = yield* DateTime.now;
|
||||
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
|
||||
const unverified = yield* Effect.try({
|
||||
try: () => decodeRelayJwt(input.request.proof),
|
||||
catch: () =>
|
||||
new EnvironmentLinkProofInvalid({
|
||||
environmentId: "unknown",
|
||||
reason: "invalid_signature_or_scope",
|
||||
}),
|
||||
});
|
||||
const decoded = yield* decodeProof(unverified).pipe(Effect.option);
|
||||
if (decoded._tag === "None") {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: "unknown",
|
||||
reason: "invalid_signature_or_scope",
|
||||
});
|
||||
}
|
||||
const candidate = decoded.value;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": candidate.environmentId,
|
||||
"relay.link.notifications_enabled": input.request.notificationsEnabled,
|
||||
"relay.link.live_activities_enabled": input.request.liveActivitiesEnabled,
|
||||
"relay.link.managed_tunnels_enabled": input.request.managedTunnelsEnabled,
|
||||
});
|
||||
if (candidate.exp <= nowSeconds) {
|
||||
return yield* new EnvironmentLinkProofExpired({
|
||||
expiresAt: DateTime.formatIso(DateTime.makeUnsafe(candidate.exp * 1_000)),
|
||||
});
|
||||
}
|
||||
const issuer = `t3-env:${candidate.environmentId}`;
|
||||
const relayIssuer = normalizeRelayIssuer(config.relayIssuer);
|
||||
const verified = yield* verifyRelayJwt({
|
||||
publicKey: candidate.environmentPublicKey,
|
||||
token: input.request.proof,
|
||||
typ: RELAY_LINK_PROOF_TYP,
|
||||
issuer,
|
||||
audience: relayIssuer,
|
||||
nowEpochSeconds: nowSeconds,
|
||||
}).pipe(
|
||||
Effect.flatMap(decodeProof),
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new EnvironmentLinkProofInvalid({
|
||||
environmentId: candidate.environmentId,
|
||||
reason: "invalid_signature_or_scope",
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (
|
||||
verified.sub !== verified.environmentId ||
|
||||
!proofAuthorizesRequestedCapabilities(verified, input.request)
|
||||
) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: candidate.environmentId,
|
||||
reason: "invalid_signature_or_scope",
|
||||
});
|
||||
}
|
||||
if (verified.descriptor.environmentId !== verified.environmentId) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "descriptor_mismatch",
|
||||
});
|
||||
}
|
||||
const challenge = yield* relayTokens.verifyLinkChallenge({
|
||||
token: verified.challenge,
|
||||
userId: input.userId,
|
||||
request: {
|
||||
notificationsEnabled: input.request.notificationsEnabled,
|
||||
liveActivitiesEnabled: input.request.liveActivitiesEnabled,
|
||||
managedTunnelsEnabled: input.request.managedTunnelsEnabled,
|
||||
},
|
||||
nowEpochSeconds: nowSeconds,
|
||||
});
|
||||
if (challenge === null) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "challenge_invalid",
|
||||
});
|
||||
}
|
||||
const expiresAt = DateTime.make(verified.exp * 1_000);
|
||||
if (expiresAt._tag === "None") {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "invalid_signature_or_scope",
|
||||
});
|
||||
}
|
||||
const consumedNonce = yield* proofReplay.consume({
|
||||
thumbprint: verified.environmentPublicKey,
|
||||
jti: verified.jti,
|
||||
iat: verified.iat,
|
||||
expiresAt: expiresAt.value,
|
||||
});
|
||||
if (!consumedNonce) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "replayed_nonce",
|
||||
});
|
||||
}
|
||||
const consumedChallenge = yield* proofReplay.consume({
|
||||
thumbprint: "relay-environment-link-challenge",
|
||||
jti: challenge.jti,
|
||||
iat: challenge.iat,
|
||||
expiresAt: expiresAt.value,
|
||||
});
|
||||
if (!consumedChallenge) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "challenge_invalid",
|
||||
});
|
||||
}
|
||||
if (input.request.managedTunnelsEnabled && !isLoopbackManagedTunnelOrigin(verified.origin)) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "origin_not_allowed",
|
||||
});
|
||||
}
|
||||
const provisioned = input.request.managedTunnelsEnabled
|
||||
? yield* managedEndpointProvider.provision({
|
||||
environmentId: verified.environmentId,
|
||||
origin: verified.origin,
|
||||
})
|
||||
: null;
|
||||
const endpoint = provisioned?.endpoint ?? verified.endpoint;
|
||||
if (!isSecureManagedEndpoint(endpoint)) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "endpoint_not_secure",
|
||||
});
|
||||
}
|
||||
yield* links.upsert({ ...input, proof: verified, endpoint });
|
||||
const environmentCredential = yield* credentials.create({
|
||||
environmentId: verified.environmentId,
|
||||
environmentPublicKey: verified.environmentPublicKey,
|
||||
});
|
||||
return {
|
||||
environmentId: verified.environmentId,
|
||||
endpoint,
|
||||
endpointRuntime: provisioned?.runtime ?? null,
|
||||
environmentCredential,
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(EnvironmentLinker, make);
|
||||
+33
-20
@@ -4,29 +4,42 @@ import * as Layer from "effect/Layer";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
|
||||
import { RelayDb, type RelayDatabase } from "../db.ts";
|
||||
import { relayEnvironmentLinks } from "../schema.ts";
|
||||
import {
|
||||
agentAwarenessDeliveryUserCondition,
|
||||
EnvironmentLinks,
|
||||
layer,
|
||||
} from "./EnvironmentLinks.ts";
|
||||
import { relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
import { EnvironmentLinks, layer } from "./EnvironmentLinks.ts";
|
||||
|
||||
describe("EnvironmentLinks", () => {
|
||||
it("selects users when either notifications or Live Activities are enabled", () => {
|
||||
const dialect = new PgDialect();
|
||||
const condition = agentAwarenessDeliveryUserCondition("env-1");
|
||||
expect(condition).toBeDefined();
|
||||
if (!condition) {
|
||||
throw new Error("Expected agent awareness delivery condition.");
|
||||
}
|
||||
const query = dialect.sqlToQuery(condition);
|
||||
it.effect("selects users when either notifications or Live Activities are enabled", () => {
|
||||
const whereConditions: Array<unknown> = [];
|
||||
const fakeDb = {
|
||||
select: (selection: unknown) => {
|
||||
expect(selection).toBeDefined();
|
||||
return {
|
||||
from: (table: unknown) => {
|
||||
expect(table).toBe(relayEnvironmentLinks);
|
||||
return {
|
||||
where: (condition: unknown) => {
|
||||
whereConditions.push(condition);
|
||||
return Effect.succeed([]);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
} as unknown as RelayDatabase;
|
||||
|
||||
expect(query.sql).toContain('"relay_environment_links"."environment_id" = $1');
|
||||
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
|
||||
expect(query.sql).toContain('"relay_environment_links"."notifications_enabled" = $2');
|
||||
expect(query.sql).toContain('"relay_environment_links"."live_activities_enabled" = $3');
|
||||
expect(query.sql).toContain(" or ");
|
||||
expect(query.params).toEqual(["env-1", true, true]);
|
||||
return Effect.gen(function* () {
|
||||
const links = yield* EnvironmentLinks;
|
||||
expect(yield* links.listUsersForEnvironment({ environmentId: "env-1" })).toEqual([]);
|
||||
expect(whereConditions).toHaveLength(1);
|
||||
|
||||
const query = new PgDialect().sqlToQuery(whereConditions[0] as never);
|
||||
expect(query.sql).toContain('"relay_environment_links"."environment_id" = $1');
|
||||
expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');
|
||||
expect(query.sql).toContain('"relay_environment_links"."notifications_enabled" = $2');
|
||||
expect(query.sql).toContain('"relay_environment_links"."live_activities_enabled" = $3');
|
||||
expect(query.sql).toContain(" or ");
|
||||
expect(query.params).toEqual(["env-1", true, true]);
|
||||
}).pipe(Effect.provide(layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb)))));
|
||||
});
|
||||
|
||||
it.effect("revokes only the active link owned by the requesting user", () => {
|
||||
+4
-8
@@ -12,7 +12,7 @@ import * as Layer from "effect/Layer";
|
||||
import { and, eq, isNull, or } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayEnvironmentLinks } from "../schema.ts";
|
||||
import { relayEnvironmentLinks } from "../persistence/schema.ts";
|
||||
|
||||
export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord {
|
||||
readonly environmentPublicKey: string;
|
||||
@@ -97,10 +97,10 @@ export interface EnvironmentLinksShape {
|
||||
}
|
||||
|
||||
export class EnvironmentLinks extends Context.Service<EnvironmentLinks, EnvironmentLinksShape>()(
|
||||
"EnvironmentLinks",
|
||||
"t3code-relay/environments/EnvironmentLinks",
|
||||
) {}
|
||||
|
||||
export function agentAwarenessDeliveryUserCondition(environmentId: string) {
|
||||
function agentAwarenessDeliveryUserCondition(environmentId: string) {
|
||||
return and(
|
||||
eq(relayEnvironmentLinks.environmentId, environmentId),
|
||||
isNull(relayEnvironmentLinks.revokedAt),
|
||||
@@ -111,7 +111,7 @@ export function agentAwarenessDeliveryUserCondition(environmentId: string) {
|
||||
);
|
||||
}
|
||||
|
||||
export function agentAwarenessDeliveryUserKeyCondition(input: {
|
||||
function agentAwarenessDeliveryUserKeyCondition(input: {
|
||||
readonly environmentId: string;
|
||||
readonly environmentPublicKey: string;
|
||||
}) {
|
||||
@@ -128,7 +128,6 @@ const make = Effect.gen(function* () {
|
||||
upsert: Effect.fn("relay.environment_links.upsert")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.environment_id": input.proof.environmentId,
|
||||
});
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
@@ -233,7 +232,6 @@ const make = Effect.gen(function* () {
|
||||
}),
|
||||
|
||||
listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({ "user.id": input.userId });
|
||||
return yield* db
|
||||
.select({
|
||||
environmentId: relayEnvironmentLinks.environmentId,
|
||||
@@ -271,7 +269,6 @@ const make = Effect.gen(function* () {
|
||||
|
||||
getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
return yield* db
|
||||
@@ -321,7 +318,6 @@ const make = Effect.gen(function* () {
|
||||
revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(
|
||||
function* (input) {
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"user.id": input.userId,
|
||||
"relay.environment_id": input.environmentId,
|
||||
});
|
||||
const revokedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
+12
-6
@@ -6,6 +6,7 @@ import type {
|
||||
RelayAgentActivityState,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt";
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -13,10 +14,9 @@ import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Result from "effect/Result";
|
||||
|
||||
import * as DpopProofs from "../persistence/DpopProofs.ts";
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as EnvironmentPublishSignatures from "./EnvironmentPublishSignatures.ts";
|
||||
import { environmentPublishReplayThumbprint } from "./EnvironmentPublishSignatures.ts";
|
||||
|
||||
const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
|
||||
privateKeyEncoding: { format: "pem", type: "pkcs8" },
|
||||
@@ -86,6 +86,8 @@ function layer(replay?: Partial<DpopProofs.DpopProofReplayShape>) {
|
||||
Layer.merge(
|
||||
Layer.succeed(RelayConfiguration.RelayConfiguration, config),
|
||||
Layer.succeed(DpopProofs.DpopProofReplay, {
|
||||
verifyAndConsume:
|
||||
replay?.verifyAndConsume ?? (() => Effect.die("unexpected DPoP proof verification")),
|
||||
consume: replay?.consume ?? (() => Effect.succeed(true)),
|
||||
pruneExpired: replay?.pruneExpired ?? Effect.void,
|
||||
}),
|
||||
@@ -108,10 +110,14 @@ describe("EnvironmentPublishSignatures", () => {
|
||||
request,
|
||||
});
|
||||
expect(replayThumbprint).toBe(
|
||||
yield* environmentPublishReplayThumbprint({
|
||||
environmentId: state.environmentId,
|
||||
environmentPublicKey: keyPair.publicKey,
|
||||
}),
|
||||
`env-publish:${NodeCrypto.createHash("sha256")
|
||||
.update(
|
||||
stableStringify({
|
||||
environmentId: state.environmentId,
|
||||
environmentPublicKey: keyPair.publicKey,
|
||||
}),
|
||||
)
|
||||
.digest("base64url")}`,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
+2
-14
@@ -18,7 +18,7 @@ import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DpopProofs from "../persistence/DpopProofs.ts";
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
|
||||
export class EnvironmentPublishSignatureExpired extends Data.TaggedError(
|
||||
@@ -57,7 +57,7 @@ export interface EnvironmentPublishSignaturesShape {
|
||||
export class EnvironmentPublishSignatures extends Context.Service<
|
||||
EnvironmentPublishSignatures,
|
||||
EnvironmentPublishSignaturesShape
|
||||
>()("EnvironmentPublishSignatures") {}
|
||||
>()("t3code-relay/environments/EnvironmentPublishSignatures") {}
|
||||
|
||||
const decodeProof = Schema.decodeUnknownEffect(RelayAgentActivityPublishProofPayload);
|
||||
|
||||
@@ -76,18 +76,6 @@ function environmentPublishReplayThumbprintData(input: {
|
||||
const formatEnvironmentPublishReplayThumbprint = (digest: Uint8Array) =>
|
||||
`env-publish:${Encoding.encodeBase64Url(digest)}`;
|
||||
|
||||
export function environmentPublishReplayThumbprint(input: {
|
||||
readonly environmentId: string;
|
||||
readonly environmentPublicKey: string;
|
||||
}) {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) =>
|
||||
crypto.digest("SHA-256", environmentPublishReplayThumbprintData(input)),
|
||||
),
|
||||
Effect.map(formatEnvironmentPublishReplayThumbprint),
|
||||
);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const proofReplay = yield* DpopProofs.DpopProofReplay;
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
File renamed without changes.
+1
-1
@@ -54,7 +54,7 @@ export interface ManagedEndpointProviderShape {
|
||||
export class ManagedEndpointProvider extends Context.Service<
|
||||
ManagedEndpointProvider,
|
||||
ManagedEndpointProviderShape
|
||||
>()("ManagedEndpointProvider") {}
|
||||
>()("t3code-relay/environments/ManagedEndpointProvider") {}
|
||||
|
||||
const CloudflareTunnelCreateResponse = Schema.Struct({
|
||||
success: Schema.Boolean,
|
||||
@@ -12,40 +12,13 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
import { RelayEnvironmentAuth } from "@t3tools/contracts/relay";
|
||||
|
||||
import {
|
||||
isDpopAuthorizationHeader,
|
||||
relayCors,
|
||||
relayCorsPreflightHeaders,
|
||||
relayEnvironmentAuthLayer,
|
||||
relayNotFoundRoute,
|
||||
traceRelayHttpRequestWith,
|
||||
withoutCapturedParentSpan,
|
||||
} from "./api.ts";
|
||||
import * as EnvironmentCredentials from "./persistence/EnvironmentCredentials.ts";
|
||||
|
||||
function splitHeaderTokens(value: string): ReadonlyArray<string> {
|
||||
return value.split(",").map((token) => token.trim());
|
||||
}
|
||||
|
||||
describe("relay CORS", () => {
|
||||
it("allows Effect trace propagation headers from browser clients", () => {
|
||||
expect(splitHeaderTokens(relayCorsPreflightHeaders["access-control-allow-headers"])).toEqual([
|
||||
"authorization",
|
||||
"b3",
|
||||
"traceparent",
|
||||
"content-type",
|
||||
"dpop",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relay DPoP authentication", () => {
|
||||
it("requires the HTTP DPoP authorization scheme", () => {
|
||||
expect(isDpopAuthorizationHeader("DPoP access-token")).toBe(true);
|
||||
expect(isDpopAuthorizationHeader("dpop access-token")).toBe(true);
|
||||
expect(isDpopAuthorizationHeader("Bearer access-token")).toBe(false);
|
||||
expect(isDpopAuthorizationHeader("access-token")).toBe(false);
|
||||
});
|
||||
});
|
||||
} from "./Api.ts";
|
||||
import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";
|
||||
|
||||
describe("relay environment authentication", () => {
|
||||
it.effect("preserves credential lookup persistence failures as internal errors", () => {
|
||||
@@ -111,11 +84,12 @@ describe("relay request tracing", () => {
|
||||
sampled: true,
|
||||
});
|
||||
const endpoint = yield* withoutCapturedParentSpan(
|
||||
Effect.context<any>().pipe(
|
||||
Effect.map((capturedContext: Context.Context<any>) =>
|
||||
Effect.fn("relay.test.endpoint")(() =>
|
||||
Effect.succeed(HttpServerResponse.empty({ status: 204 })),
|
||||
)().pipe(Effect.provideContext(capturedContext)),
|
||||
Effect.context<never>().pipe(
|
||||
Effect.map((capturedContext: Context.Context<never>) =>
|
||||
Effect.succeed(HttpServerResponse.empty({ status: 204 })).pipe(
|
||||
Effect.withSpan("relay.test.endpoint"),
|
||||
Effect.provideContext(capturedContext),
|
||||
),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.provideService(Tracer.ParentSpan, ambientParent));
|
||||
@@ -12,7 +12,6 @@ import * as Schema from "effect/Schema";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware";
|
||||
import * as HttpPlatform from "effect/unstable/http/HttpPlatform";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
|
||||
@@ -48,33 +47,22 @@ import {
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";
|
||||
|
||||
import { verifyAndConsumeDpopProof } from "./dpop.ts";
|
||||
import * as DeliveryAttempts from "./persistence/DeliveryAttempts.ts";
|
||||
import * as AgentActivityRows from "./persistence/AgentActivityRows.ts";
|
||||
import * as Devices from "./persistence/Devices.ts";
|
||||
import * as DpopProofs from "./persistence/DpopProofs.ts";
|
||||
import * as EnvironmentCredentials from "./persistence/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "./persistence/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "./persistence/LiveActivities.ts";
|
||||
import * as RelayConfiguration from "./Config.ts";
|
||||
import * as AgentActivityPublisher from "./services/AgentActivityPublisher.ts";
|
||||
import * as EnvironmentConnector from "./services/EnvironmentConnector.ts";
|
||||
import * as EnvironmentLinker from "./services/EnvironmentLinker.ts";
|
||||
import * as EnvironmentPublishSignatures from "./services/EnvironmentPublishSignatures.ts";
|
||||
import * as MobileRegistrations from "./services/MobileRegistrations.ts";
|
||||
import { withSpanAttributes, withUserId } from "./telemetry.ts";
|
||||
import { RelayDb } from "./db.ts";
|
||||
import {
|
||||
issueDpopAccessToken,
|
||||
issueLinkChallengeToken,
|
||||
resolveDpopAccessTokenScopes,
|
||||
verifyDpopAccessToken,
|
||||
} from "./relayTokens.ts";
|
||||
|
||||
export const RelayHttpPlatformLayer = Layer.succeed(HttpPlatform.HttpPlatform, {
|
||||
fileResponse: () => Effect.die("Relay API does not serve filesystem responses"),
|
||||
fileWebResponse: () => Effect.die("Relay API does not serve file responses"),
|
||||
});
|
||||
import * as DeliveryAttempts from "../agentActivity/DeliveryAttempts.ts";
|
||||
import * as AgentActivityRows from "../agentActivity/AgentActivityRows.ts";
|
||||
import * as Devices from "../agentActivity/Devices.ts";
|
||||
import * as DpopProofs from "../auth/DpopProofs.ts";
|
||||
import * as RelayTokens from "../auth/RelayTokens.ts";
|
||||
import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "../agentActivity/LiveActivities.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";
|
||||
import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";
|
||||
import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";
|
||||
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
|
||||
import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
|
||||
import { withSpanAttributes } from "../observability.ts";
|
||||
import { RelayDb } from "../db.ts";
|
||||
|
||||
const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;
|
||||
const relayCorsAllowedHeaders = [
|
||||
@@ -91,7 +79,7 @@ const relayCorsHeaders = {
|
||||
"access-control-expose-headers": relayCorsExposedHeaders.join(","),
|
||||
} as const;
|
||||
|
||||
export const relayCorsPreflightHeaders = {
|
||||
const relayCorsPreflightHeaders = {
|
||||
...relayCorsHeaders,
|
||||
"access-control-allow-methods": relayCorsAllowedMethods.join(","),
|
||||
"access-control-allow-headers": relayCorsAllowedHeaders.join(","),
|
||||
@@ -195,7 +183,7 @@ export const relayClientAuthLayer = Layer.effect(
|
||||
"relay.auth.subject": verified.sub,
|
||||
});
|
||||
return yield* httpEffect.pipe(
|
||||
withUserId(verified.sub),
|
||||
withSpanAttributes({ "user.id": verified.sub }),
|
||||
Effect.provideService(RelayClientPrincipal, {
|
||||
userId: verified.sub,
|
||||
token,
|
||||
@@ -240,7 +228,7 @@ export const relayEnvironmentAuthLayer = Layer.effect(
|
||||
export const relayDpopClientAuthLayer = Layer.effect(
|
||||
RelayDpopClientAuth,
|
||||
Effect.gen(function* () {
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
return {
|
||||
relayDpop: Effect.fn("relay.auth.dpop_client")(function* (httpEffect, { credential }) {
|
||||
yield* appendRelayDpopChallengeHeader;
|
||||
@@ -252,8 +240,7 @@ export const relayDpopClientAuthLayer = Layer.effect(
|
||||
// the separating spaces in the decoded credential.
|
||||
const token = Redacted.value(credential).trimStart();
|
||||
const now = yield* DateTime.now;
|
||||
const verified = yield* verifyDpopAccessToken({
|
||||
config,
|
||||
const verified = yield* relayTokens.verifyDpopAccessToken({
|
||||
token,
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
});
|
||||
@@ -265,7 +252,7 @@ export const relayDpopClientAuthLayer = Layer.effect(
|
||||
"relay.auth.subject": verified.sub,
|
||||
});
|
||||
return yield* httpEffect.pipe(
|
||||
withUserId(verified.sub),
|
||||
withSpanAttributes({ "user.id": verified.sub }),
|
||||
Effect.provideService(RelayClientPrincipal, {
|
||||
userId: verified.sub,
|
||||
token,
|
||||
@@ -278,7 +265,7 @@ export const relayDpopClientAuthLayer = Layer.effect(
|
||||
}),
|
||||
);
|
||||
|
||||
export function isDpopAuthorizationHeader(value: string | undefined): boolean {
|
||||
function isDpopAuthorizationHeader(value: string | undefined): boolean {
|
||||
return /^DPoP +/iu.test(value ?? "");
|
||||
}
|
||||
|
||||
@@ -298,9 +285,9 @@ export const metadataApi = HttpApiBuilder.group(
|
||||
Effect.succeed({
|
||||
issuer,
|
||||
token_endpoint: `${issuer}/v1/client/dpop-token`,
|
||||
grant_types_supported: ["urn:ietf:params:oauth:grant-type:token-exchange"] as const,
|
||||
token_endpoint_auth_methods_supported: ["none"] as const,
|
||||
dpop_signing_alg_values_supported: ["ES256"] as const,
|
||||
grant_types_supported: ["urn:ietf:params:oauth:grant-type:token-exchange"],
|
||||
token_endpoint_auth_methods_supported: ["none"],
|
||||
dpop_signing_alg_values_supported: ["ES256"],
|
||||
scopes_supported: scopes,
|
||||
}),
|
||||
)
|
||||
@@ -310,7 +297,7 @@ export const metadataApi = HttpApiBuilder.group(
|
||||
authorization_servers: [issuer],
|
||||
scopes_supported: scopes,
|
||||
dpop_bound_access_tokens_required: true,
|
||||
dpop_signing_alg_values_supported: ["ES256"] as const,
|
||||
dpop_signing_alg_values_supported: ["ES256"],
|
||||
}),
|
||||
);
|
||||
}),
|
||||
@@ -326,9 +313,7 @@ export const healthApi = HttpApiBuilder.group(
|
||||
Effect.fn("relay.api.health")(
|
||||
function* () {
|
||||
const startedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
|
||||
yield* db
|
||||
.execute(drizzleSql`SELECT 1`)
|
||||
.pipe(Effect.withSpan("relay.api.health.db_probe"));
|
||||
yield* db.execute(drizzleSql`SELECT 1`);
|
||||
const completedAt = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
|
||||
yield* Effect.logInfo("relay health db probe completed", {
|
||||
durationMs: completedAt - startedAt,
|
||||
@@ -393,6 +378,7 @@ export const clientApi = HttpApiBuilder.group(
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
const linker = yield* EnvironmentLinker.EnvironmentLinker;
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
@@ -486,14 +472,15 @@ export const clientApi = HttpApiBuilder.group(
|
||||
const jti = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.catch(() => relayInternalErrorResponse("internal_error")),
|
||||
);
|
||||
const challenge = yield* issueLinkChallengeToken({
|
||||
config,
|
||||
userId,
|
||||
request: args.payload,
|
||||
jti,
|
||||
issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
}).pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
|
||||
const challenge = yield* relayTokens
|
||||
.issueLinkChallenge({
|
||||
userId,
|
||||
request: args.payload,
|
||||
jti,
|
||||
issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
})
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
|
||||
return { challenge, expiresAt: DateTime.formatIso(expiresAt) };
|
||||
}, mapRelayCommonApiErrors("not_authorized")),
|
||||
)
|
||||
@@ -532,12 +519,13 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const dpopProofs = yield* DpopProofs.DpopProofReplay;
|
||||
const relayTokens = yield* RelayTokens.RelayTokens;
|
||||
return handlers.handle(
|
||||
"exchangeDpopAccessToken",
|
||||
Effect.fn("relay.api.token.exchangeDpopAccessToken")(function* (args) {
|
||||
yield* appendRelayCredentialResponseHeaders;
|
||||
const issuer = normalizeRelayIssuer(config.relayIssuer);
|
||||
const requestedScopes = resolveDpopAccessTokenScopes({
|
||||
const requestedScopes = relayTokens.resolveDpopAccessTokenScopes({
|
||||
clientId: args.payload.client_id,
|
||||
scope: args.payload.scope,
|
||||
});
|
||||
@@ -556,18 +544,17 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
if (!verified.sub) {
|
||||
return yield* relayAuthInvalidError("invalid_bearer");
|
||||
}
|
||||
return yield* Effect.gen(function* () {
|
||||
const proofKeyThumbprint = yield* requireDpopProof().pipe(
|
||||
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 5 });
|
||||
const jti = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.catch(() => relayInternalErrorResponse("internal_error")),
|
||||
);
|
||||
return {
|
||||
access_token: yield* issueDpopAccessToken({
|
||||
config,
|
||||
const proofKeyThumbprint = yield* requireDpopProof().pipe(
|
||||
Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(now, { minutes: 5 });
|
||||
const jti = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.catch(() => relayInternalErrorResponse("internal_error")),
|
||||
);
|
||||
return {
|
||||
access_token: yield* relayTokens
|
||||
.issueDpopAccessToken({
|
||||
userId: verified.sub,
|
||||
proofKeyThumbprint,
|
||||
jti,
|
||||
@@ -575,13 +562,13 @@ export const tokenApi = HttpApiBuilder.group(
|
||||
expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),
|
||||
clientId: args.payload.client_id,
|
||||
scopes: requestedScopes,
|
||||
}).pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
|
||||
issued_token_type: RelayAccessTokenType,
|
||||
token_type: "DPoP" as const,
|
||||
expires_in: 300,
|
||||
scope: encodeOAuthScope(requestedScopes),
|
||||
};
|
||||
}).pipe(withUserId(verified.sub));
|
||||
})
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),
|
||||
issued_token_type: RelayAccessTokenType,
|
||||
token_type: "DPoP" as const,
|
||||
expires_in: 300,
|
||||
scope: encodeOAuthScope(requestedScopes),
|
||||
};
|
||||
}, mapRelayCommonApiErrors("invalid_dpop")),
|
||||
);
|
||||
}),
|
||||
@@ -782,24 +769,26 @@ const currentTraceId = Effect.currentParentSpan.pipe(
|
||||
Effect.orElseSucceed(() => "unavailable"),
|
||||
);
|
||||
|
||||
type RelayCommonPersistenceError =
|
||||
| Devices.DeviceRegistrationPersistenceError
|
||||
| Devices.DeviceUnregistrationPersistenceError
|
||||
| LiveActivities.LiveActivityRegistrationPersistenceError
|
||||
| EnvironmentLinks.EnvironmentLinkUserListPersistenceError
|
||||
| EnvironmentLinks.EnvironmentPublicKeyListPersistenceError
|
||||
| EnvironmentLinks.EnvironmentLinkListPersistenceError
|
||||
| EnvironmentLinks.EnvironmentLinkLookupPersistenceError
|
||||
| EnvironmentLinks.EnvironmentLinkRevokePersistenceError
|
||||
| EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError
|
||||
| EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError
|
||||
| DpopProofs.DpopProofReplayPersistenceError
|
||||
| LiveActivities.LiveActivityTargetListPersistenceError
|
||||
| AgentActivityRows.AgentActivityRowUpsertPersistenceError
|
||||
| AgentActivityRows.AgentActivityRowDeletePersistenceError
|
||||
| AgentActivityRows.AgentActivityRowListPersistenceError
|
||||
| LiveActivities.LiveActivityDeliveryMarkPersistenceError
|
||||
| DeliveryAttempts.DeliveryAttemptRecordPersistenceError;
|
||||
const COMMON_AUTH_INVALID_REASONS = [
|
||||
Devices.DeviceRegistrationPersistenceError,
|
||||
Devices.DeviceUnregistrationPersistenceError,
|
||||
LiveActivities.LiveActivityRegistrationPersistenceError,
|
||||
EnvironmentLinks.EnvironmentLinkUserListPersistenceError,
|
||||
EnvironmentLinks.EnvironmentPublicKeyListPersistenceError,
|
||||
EnvironmentLinks.EnvironmentLinkListPersistenceError,
|
||||
EnvironmentLinks.EnvironmentLinkLookupPersistenceError,
|
||||
EnvironmentLinks.EnvironmentLinkRevokePersistenceError,
|
||||
EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError,
|
||||
EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError,
|
||||
DpopProofs.DpopProofReplayPersistenceError,
|
||||
LiveActivities.LiveActivityTargetListPersistenceError,
|
||||
AgentActivityRows.AgentActivityRowUpsertPersistenceError,
|
||||
AgentActivityRows.AgentActivityRowDeletePersistenceError,
|
||||
AgentActivityRows.AgentActivityRowListPersistenceError,
|
||||
LiveActivities.LiveActivityDeliveryMarkPersistenceError,
|
||||
DeliveryAttempts.DeliveryAttemptRecordPersistenceError,
|
||||
] as const;
|
||||
type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>;
|
||||
|
||||
type MapRelayCommonApiError<E> =
|
||||
| Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>
|
||||
@@ -807,25 +796,7 @@ type MapRelayCommonApiError<E> =
|
||||
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
|
||||
|
||||
function isRelayCommonPersistenceError(error: unknown): error is RelayCommonPersistenceError {
|
||||
return (
|
||||
error instanceof Devices.DeviceRegistrationPersistenceError ||
|
||||
error instanceof Devices.DeviceUnregistrationPersistenceError ||
|
||||
error instanceof LiveActivities.LiveActivityRegistrationPersistenceError ||
|
||||
error instanceof EnvironmentLinks.EnvironmentLinkUserListPersistenceError ||
|
||||
error instanceof EnvironmentLinks.EnvironmentPublicKeyListPersistenceError ||
|
||||
error instanceof EnvironmentLinks.EnvironmentLinkListPersistenceError ||
|
||||
error instanceof EnvironmentLinks.EnvironmentLinkLookupPersistenceError ||
|
||||
error instanceof EnvironmentLinks.EnvironmentLinkRevokePersistenceError ||
|
||||
error instanceof EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError ||
|
||||
error instanceof EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError ||
|
||||
error instanceof DpopProofs.DpopProofReplayPersistenceError ||
|
||||
error instanceof LiveActivities.LiveActivityTargetListPersistenceError ||
|
||||
error instanceof AgentActivityRows.AgentActivityRowUpsertPersistenceError ||
|
||||
error instanceof AgentActivityRows.AgentActivityRowDeletePersistenceError ||
|
||||
error instanceof AgentActivityRows.AgentActivityRowListPersistenceError ||
|
||||
error instanceof LiveActivities.LiveActivityDeliveryMarkPersistenceError ||
|
||||
error instanceof DeliveryAttempts.DeliveryAttemptRecordPersistenceError
|
||||
);
|
||||
return COMMON_AUTH_INVALID_REASONS.some((ErrorType) => error instanceof ErrorType);
|
||||
}
|
||||
|
||||
function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {
|
||||
@@ -904,6 +875,7 @@ function mapErrorTags<
|
||||
return <A, R>(
|
||||
self: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>, R> =>
|
||||
// @effect-diagnostics-next-line unsafeEffectTypeAssertion:off
|
||||
Effect.catchTags(self, catchCases) as Effect.Effect<
|
||||
A,
|
||||
Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>,
|
||||
@@ -977,7 +949,8 @@ const requireDpopThumbprint = Effect.fn("relay.api.require_dpop_thumbprint")(fun
|
||||
if (url._tag === "None") {
|
||||
return yield* new HttpApiError.Unauthorized({});
|
||||
}
|
||||
return yield* verifyAndConsumeDpopProof({
|
||||
const dpopProofs = yield* DpopProofs.DpopProofReplay;
|
||||
return yield* dpopProofs.verifyAndConsume({
|
||||
proof: request.headers.dpop,
|
||||
method: request.method,
|
||||
url: url.value.href,
|
||||
@@ -996,7 +969,8 @@ const requireDpopProof = Effect.fn("relay.api.require_dpop_proof")(function* (op
|
||||
if (url._tag === "None") {
|
||||
return yield* new HttpApiError.Unauthorized({});
|
||||
}
|
||||
return yield* verifyAndConsumeDpopProof({
|
||||
const dpopProofs = yield* DpopProofs.DpopProofReplay;
|
||||
return yield* dpopProofs.verifyAndConsume({
|
||||
proof: request.headers.dpop,
|
||||
method: request.method,
|
||||
url: url.value.href,
|
||||
@@ -1,27 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES,
|
||||
MANAGED_ENDPOINT_ZONE,
|
||||
} from "./ManagedEndpointStackConfig.ts";
|
||||
|
||||
describe("ManagedEndpointStackConfig", () => {
|
||||
it("restricts endpoint provisioning to the relay account and DNS zone", () => {
|
||||
expect(MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES).toEqual([
|
||||
{
|
||||
effect: "allow",
|
||||
permissionGroups: ["Cloudflare Tunnel Read", "Cloudflare Tunnel Write"],
|
||||
resources: {
|
||||
[`com.cloudflare.api.account.${MANAGED_ENDPOINT_ZONE.accountId}`]: "*",
|
||||
},
|
||||
},
|
||||
{
|
||||
effect: "allow",
|
||||
permissionGroups: ["DNS Read", "DNS Write"],
|
||||
resources: {
|
||||
[`com.cloudflare.api.account.zone.${MANAGED_ENDPOINT_ZONE.zoneId}`]: "*",
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
export const MANAGED_ENDPOINT_ZONE = {
|
||||
name: "ineededadomain.com",
|
||||
zoneId: "fcea40a6915723b0f5c4a9480eb3507b",
|
||||
accountId: "1468bbd99811cdaccfbb707dc725421a",
|
||||
} as const;
|
||||
|
||||
export const RELAY_PUBLIC_DOMAIN = `t3code-relay.${MANAGED_ENDPOINT_ZONE.name}`;
|
||||
export const RELAY_PUBLIC_ORIGIN = `https://${RELAY_PUBLIC_DOMAIN}`;
|
||||
export const MANAGED_ENDPOINT_BASE_DOMAIN = MANAGED_ENDPOINT_ZONE.name;
|
||||
|
||||
export const MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES = [
|
||||
{
|
||||
effect: "allow" as const,
|
||||
permissionGroups: ["Cloudflare Tunnel Read" as const, "Cloudflare Tunnel Write" as const],
|
||||
resources: {
|
||||
[`com.cloudflare.api.account.${MANAGED_ENDPOINT_ZONE.accountId}`]: "*",
|
||||
},
|
||||
},
|
||||
{
|
||||
effect: "allow" as const,
|
||||
permissionGroups: ["DNS Read" as const, "DNS Write" as const],
|
||||
resources: {
|
||||
[`com.cloudflare.api.account.zone.${MANAGED_ENDPOINT_ZONE.zoneId}`]: "*",
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1,82 +0,0 @@
|
||||
import * as Alchemy from "alchemy";
|
||||
import * as Axiom from "alchemy/Axiom";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
RELAY_AXIOM_TRACE_DATASET,
|
||||
provisionRelayObservability,
|
||||
relayAxiomIngestDatasetCapabilities,
|
||||
relayAxiomQueryDatasetCapabilities,
|
||||
relayRecentSpansQuery,
|
||||
relayTraceQuery,
|
||||
} from "./RelayObservability.ts";
|
||||
|
||||
describe("RelayObservability", () => {
|
||||
it("scopes the ingest token only to HTTP span ingestion", () => {
|
||||
expect(relayAxiomIngestDatasetCapabilities()).toEqual({
|
||||
[RELAY_AXIOM_TRACE_DATASET]: { ingest: ["create"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("scopes the diagnostics query token only to HTTP spans", () => {
|
||||
expect(relayAxiomQueryDatasetCapabilities()).toEqual({
|
||||
[RELAY_AXIOM_TRACE_DATASET]: { query: ["read"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("builds APL queries for the trace dataset", () => {
|
||||
expect(relayTraceQuery("| where name == 'GET /health'", "relay-traces-test")).toBe(
|
||||
"['relay-traces-test']\n| where name == 'GET /health'",
|
||||
);
|
||||
});
|
||||
|
||||
it("projects Effect HTTP span attributes through their OTLP field names", () => {
|
||||
const query = relayRecentSpansQuery("relay-traces-test");
|
||||
|
||||
expect(query).toContain("['relay-traces-test']");
|
||||
expect(query).toContain("attributes.http.request.method");
|
||||
expect(query).toContain("attributes.http.response.status_code");
|
||||
expect(query).toContain("attributes.url.path");
|
||||
expect(query).toContain("attributes.http.route");
|
||||
expect(query).toContain("customAttributes = column_ifexists('attributes.custom', dynamic({}))");
|
||||
expect(query).toContain("customAttributes['user.id']");
|
||||
expect(query).not.toContain("['http.request.method']");
|
||||
});
|
||||
|
||||
it("orders token and view resources behind the trace dataset", async () => {
|
||||
const stack = {
|
||||
name: "RelayObservabilityTest",
|
||||
stage: "test",
|
||||
resources: {},
|
||||
bindings: {},
|
||||
actions: {},
|
||||
};
|
||||
|
||||
await Effect.runPromise(
|
||||
provisionRelayObservability.pipe(
|
||||
Effect.provideService(Alchemy.Stack, stack),
|
||||
Effect.provideService(Axiom.Providers, {
|
||||
kind: "ProviderCollection",
|
||||
get: () => undefined,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const resources = stack.resources as Record<string, { FQN: string; Props: unknown }>;
|
||||
const traces = resources.RelayTracesDataset;
|
||||
|
||||
expect(traces).toBeDefined();
|
||||
for (const logicalId of [
|
||||
"RelayAxiomIngestToken",
|
||||
"RelayAxiomQueryToken",
|
||||
"RelayRecentSpansView",
|
||||
]) {
|
||||
expect(resources[logicalId]).toBeDefined();
|
||||
expect(Object.keys(Output.resolveUpstream(resources[logicalId]!.Props))).toContain(
|
||||
traces!.FQN,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
import * as Axiom from "alchemy/Axiom";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export const RELAY_OBSERVABILITY_SERVICE_NAME = "t3-code-relay-worker";
|
||||
export const RELAY_OBSERVABILITY_EXPORT_INTERVAL = "1 second";
|
||||
export const RELAY_AXIOM_TRACE_DATASET = "t3-code-relay-traces";
|
||||
|
||||
export const relayTraceQuery = (query: string, dataset: string = RELAY_AXIOM_TRACE_DATASET) =>
|
||||
`['${dataset}']\n${query}`;
|
||||
|
||||
export const relayRecentSpansQuery = (dataset: string = RELAY_AXIOM_TRACE_DATASET) =>
|
||||
relayTraceQuery(
|
||||
"| where isnotnull(span_id) or isnotnull(trace_id)\n| extend requestMethod = column_ifexists('attributes.http.request.method', ''), path = column_ifexists('attributes.url.path', ''), endpoint = column_ifexists('attributes.http.route', ''), statusCode = column_ifexists('attributes.http.response.status_code', 0), customAttributes = column_ifexists('attributes.custom', dynamic({}))\n| extend userId = customAttributes['user.id']\n| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId\n| order by _time desc\n| limit 200",
|
||||
dataset,
|
||||
);
|
||||
|
||||
export const relayAxiomIngestDatasetCapabilities = (
|
||||
dataset: string = RELAY_AXIOM_TRACE_DATASET,
|
||||
) => ({
|
||||
[dataset]: { ingest: ["create" as const] },
|
||||
});
|
||||
|
||||
export const relayAxiomQueryDatasetCapabilities = (
|
||||
dataset: string = RELAY_AXIOM_TRACE_DATASET,
|
||||
) => ({
|
||||
[dataset]: { query: ["read" as const] },
|
||||
});
|
||||
|
||||
export const provisionRelayObservability = Effect.gen(function* () {
|
||||
const traces = yield* Axiom.Dataset("RelayTracesDataset", {
|
||||
name: RELAY_AXIOM_TRACE_DATASET,
|
||||
kind: "otel:traces:v1",
|
||||
description: "T3 Code relay Worker HTTP request spans.",
|
||||
retentionDays: 30,
|
||||
useRetentionPeriod: true,
|
||||
});
|
||||
|
||||
const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", {
|
||||
name: "t3-code-relay-otel-ingest",
|
||||
description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
|
||||
datasetCapabilities: Output.map(traces.name, relayAxiomIngestDatasetCapabilities),
|
||||
});
|
||||
const queryToken = yield* Axiom.ApiToken("RelayAxiomQueryToken", {
|
||||
name: "t3-code-relay-readonly-query",
|
||||
description: "Owned by Alchemy. Read-only query token for relay HTTP span diagnostics.",
|
||||
datasetCapabilities: Output.map(traces.name, relayAxiomQueryDatasetCapabilities),
|
||||
});
|
||||
|
||||
yield* Axiom.View("RelayRecentSpansView", {
|
||||
name: "t3-code-relay-recent-spans",
|
||||
description: "Recent relay HTTP request spans.",
|
||||
datasets: [traces.name],
|
||||
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
|
||||
});
|
||||
|
||||
return { traces, ingestToken, queryToken } as const;
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import * as Cloudflare from "alchemy/Cloudflare";
|
||||
|
||||
// This should be pulled from the Alchemy authenticated cloudflare account
|
||||
export const CLOUDFLARE_ACCOUNT_ID = "1468bbd99811cdaccfbb707dc725421a";
|
||||
|
||||
// We should only need to specify one of these after Alchemy have a CloudflareZone resource: https://github.com/alchemy-run/alchemy-effect/pull/493
|
||||
export const MANAGED_ENDPOINT_ZONE_ID = "fcea40a6915723b0f5c4a9480eb3507b";
|
||||
export const MANAGED_ENDPOINT_ZONE_NAME = "ineededadomain.com";
|
||||
|
||||
export const RELAY_PUBLIC_DOMAIN = `t3code-relay.${MANAGED_ENDPOINT_ZONE_NAME}`;
|
||||
export const RELAY_PUBLIC_ORIGIN = `https://${RELAY_PUBLIC_DOMAIN}`;
|
||||
|
||||
export const ManagedEndpointProvisionerToken = Cloudflare.AccountApiToken(
|
||||
"ManagedEndpointProvisionerToken",
|
||||
{
|
||||
name: "t3-code-relay-managed-endpoint-provisioner",
|
||||
policies: [
|
||||
{
|
||||
effect: "allow" as const,
|
||||
permissionGroups: ["Cloudflare Tunnel Read" as const, "Cloudflare Tunnel Write" as const],
|
||||
resources: {
|
||||
[`com.cloudflare.api.account.${CLOUDFLARE_ACCOUNT_ID}`]: "*",
|
||||
},
|
||||
},
|
||||
{
|
||||
effect: "allow" as const,
|
||||
permissionGroups: ["DNS Read" as const, "DNS Write" as const],
|
||||
resources: {
|
||||
[`com.cloudflare.api.account.zone.${MANAGED_ENDPOINT_ZONE_ID}`]: "*",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,72 @@
|
||||
import * as Axiom from "alchemy/Axiom";
|
||||
import * as Output from "alchemy/Output";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
|
||||
|
||||
const relayRecentSpansQuery = (dataset: string) =>
|
||||
[
|
||||
`['${dataset}']`,
|
||||
`| where isnotnull(span_id) or isnotnull(trace_id)`,
|
||||
`| extend requestMethod = column_ifexists('attributes.http.request.method', ''), path = column_ifexists('attributes.url.path', ''), endpoint = column_ifexists('attributes.http.route', ''), statusCode = column_ifexists('attributes.http.response.status_code', 0), customAttributes = column_ifexists('attributes.custom', dynamic({}))`,
|
||||
`| extend userId = customAttributes['user']['id']`,
|
||||
`| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId`,
|
||||
`| order by _time desc`,
|
||||
`| limit 200`,
|
||||
].join("\n");
|
||||
|
||||
export const RelayObservability = Effect.gen(function* () {
|
||||
const traces = yield* Axiom.Dataset("RelayTracesDataset", {
|
||||
name: "t3-code-relay-traces",
|
||||
kind: "otel:traces:v1",
|
||||
description: "T3 Code relay Worker HTTP request spans.",
|
||||
retentionDays: 30,
|
||||
useRetentionPeriod: true,
|
||||
});
|
||||
|
||||
const ingestToken = yield* Axiom.ApiToken("RelayAxiomIngestToken", {
|
||||
name: "t3-code-relay-otel-ingest",
|
||||
description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
|
||||
datasetCapabilities: Output.map(traces.name, (dataset) => ({
|
||||
[dataset]: { ingest: ["create" as const] },
|
||||
})),
|
||||
});
|
||||
|
||||
yield* Axiom.View("RelayRecentSpansView", {
|
||||
name: "t3-code-relay-recent-spans",
|
||||
description: "Recent relay HTTP request spans.",
|
||||
datasets: [traces.name],
|
||||
aplQuery: Output.map(traces.name, relayRecentSpansQuery),
|
||||
});
|
||||
|
||||
return { traces, ingestToken } as const;
|
||||
});
|
||||
|
||||
export const withSpanAttributes =
|
||||
(attributes: Record<string, unknown>) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
|
||||
Effect.annotateCurrentSpan(attributes).pipe(
|
||||
Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
|
||||
);
|
||||
|
||||
export const makeRelayTraceLayer = (input: {
|
||||
readonly tracesEndpoint: string;
|
||||
readonly tracesDatasetName: string;
|
||||
readonly ingestToken: Redacted.Redacted<string>;
|
||||
}) =>
|
||||
OtlpTracer.layer({
|
||||
url: input.tracesEndpoint,
|
||||
resource: {
|
||||
serviceName: "t3-code-relay-worker",
|
||||
attributes: {
|
||||
"service.runtime": "cloudflare-worker",
|
||||
"service.component": "relay",
|
||||
},
|
||||
},
|
||||
headers: {
|
||||
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
|
||||
"X-Axiom-Dataset": input.tracesDatasetName,
|
||||
},
|
||||
exportInterval: "1 second",
|
||||
}).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
@@ -1,68 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { lt } from "drizzle-orm";
|
||||
|
||||
import { RelayDb } from "../db.ts";
|
||||
import { relayDpopProofs } from "../schema.ts";
|
||||
|
||||
export class DpopProofReplayPersistenceError extends Data.TaggedError(
|
||||
"DpopProofReplayPersistenceError",
|
||||
)<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export interface DpopProofReplayShape {
|
||||
readonly consume: (input: {
|
||||
readonly thumbprint: string;
|
||||
readonly jti: string;
|
||||
readonly iat: number;
|
||||
readonly expiresAt: DateTime.DateTime;
|
||||
}) => Effect.Effect<boolean, DpopProofReplayPersistenceError>;
|
||||
|
||||
readonly pruneExpired: Effect.Effect<void, DpopProofReplayPersistenceError>;
|
||||
}
|
||||
|
||||
export class DpopProofReplay extends Context.Service<DpopProofReplay, DpopProofReplayShape>()(
|
||||
"DpopProofReplay",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const db = yield* RelayDb;
|
||||
|
||||
const consume: DpopProofReplayShape["consume"] = Effect.fn("relay.dpop_proofs.consume")(
|
||||
function* (input) {
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const inserted = yield* db
|
||||
.insert(relayDpopProofs)
|
||||
.values({
|
||||
thumbprint: input.thumbprint,
|
||||
jti: input.jti,
|
||||
iat: input.iat,
|
||||
expiresAt: DateTime.formatIso(input.expiresAt),
|
||||
createdAt,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning({ jti: relayDpopProofs.jti });
|
||||
return inserted.length > 0;
|
||||
},
|
||||
Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })),
|
||||
);
|
||||
|
||||
const pruneExpired: DpopProofReplayShape["pruneExpired"] = Effect.fn(
|
||||
"relay.dpop_proofs.prune_expired",
|
||||
)(function* () {
|
||||
const now = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* Effect.annotateCurrentSpan({ "relay.dpop_prune.before": now });
|
||||
yield* db.delete(relayDpopProofs).where(lt(relayDpopProofs.expiresAt, now));
|
||||
})().pipe(Effect.mapError((cause) => new DpopProofReplayPersistenceError({ cause })));
|
||||
|
||||
return DpopProofReplay.of({
|
||||
consume,
|
||||
pruneExpired,
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DpopProofReplay, make);
|
||||
@@ -1,10 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const decodeJsonString = Schema.decodeEffect(Schema.UnknownFromJsonString);
|
||||
const encodeJsonValue = Schema.encodeEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
export const parseJsonString = <A>(value: string) =>
|
||||
decodeJsonString(value).pipe(Effect.map((decoded) => decoded as A));
|
||||
|
||||
export const stringifyJsonValue = (value: unknown) => encodeJsonValue(value);
|
||||
File renamed without changes.
@@ -1,196 +0,0 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { signRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
|
||||
import * as RelayConfiguration from "./Config.ts";
|
||||
import {
|
||||
issueDpopAccessToken,
|
||||
issueLinkChallengeToken,
|
||||
resolveDpopAccessTokenScopes,
|
||||
verifyDpopAccessToken,
|
||||
verifyLinkChallengeToken,
|
||||
} from "./relayTokens.ts";
|
||||
|
||||
const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {
|
||||
privateKeyEncoding: { format: "pem", type: "pkcs8" },
|
||||
publicKeyEncoding: { format: "pem", type: "spki" },
|
||||
});
|
||||
|
||||
const config = RelayConfiguration.RelayConfiguration.of({
|
||||
relayIssuer: "https://relay.example.test/",
|
||||
apns: {
|
||||
environment: "sandbox",
|
||||
teamId: "team-id",
|
||||
keyId: "key-id",
|
||||
privateKey: Redacted.make("private-key"),
|
||||
bundleId: "com.t3tools.t3code.dev",
|
||||
},
|
||||
apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),
|
||||
clerkSecretKey: Redacted.make("clerk-secret"),
|
||||
cloudMintPrivateKey: Redacted.make(keyPair.privateKey),
|
||||
cloudMintPublicKey: keyPair.publicKey,
|
||||
managedEndpointBaseDomain: undefined,
|
||||
cloudflareAccountId: undefined,
|
||||
cloudflareZoneId: undefined,
|
||||
cloudflareApiToken: undefined,
|
||||
});
|
||||
|
||||
describe("relay tokens", () => {
|
||||
it("issues a user-bound environment link challenge", async () => {
|
||||
const token = await Effect.runPromise(
|
||||
issueLinkChallengeToken({
|
||||
config,
|
||||
userId: "user_123",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
},
|
||||
jti: "challenge-1",
|
||||
issuedAtEpochSeconds: 100,
|
||||
expiresAtEpochSeconds: 200,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
await Effect.runPromise(
|
||||
verifyLinkChallengeToken({
|
||||
config,
|
||||
token,
|
||||
userId: "user_123",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
},
|
||||
nowEpochSeconds: 150,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ sub: "user_123", jti: "challenge-1" });
|
||||
expect(
|
||||
await Effect.runPromise(
|
||||
verifyLinkChallengeToken({
|
||||
config,
|
||||
token,
|
||||
userId: "attacker",
|
||||
request: {
|
||||
notificationsEnabled: true,
|
||||
liveActivitiesEnabled: true,
|
||||
managedTunnelsEnabled: true,
|
||||
},
|
||||
nowEpochSeconds: 150,
|
||||
}),
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("issues and verifies DPoP access tokens bound to one proof-key thumbprint", async () => {
|
||||
const token = await Effect.runPromise(
|
||||
issueDpopAccessToken({
|
||||
config,
|
||||
userId: "user_123",
|
||||
proofKeyThumbprint: "proof-key-thumbprint",
|
||||
jti: "access-token-1",
|
||||
issuedAtEpochSeconds: 100,
|
||||
expiresAtEpochSeconds: 200,
|
||||
clientId: "t3-mobile",
|
||||
scopes: ["environment:connect", "environment:status", "mobile:registration"],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })),
|
||||
).toMatchObject({
|
||||
sub: "user_123",
|
||||
cnf: { jkt: "proof-key-thumbprint" },
|
||||
client_id: "t3-mobile",
|
||||
scope: ["environment:connect", "environment:status", "mobile:registration"],
|
||||
});
|
||||
expect(
|
||||
await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 261 })),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("issues tunnel-only DPoP access tokens to web public clients", async () => {
|
||||
const token = await Effect.runPromise(
|
||||
issueDpopAccessToken({
|
||||
config,
|
||||
userId: "user_123",
|
||||
proofKeyThumbprint: "web-proof-key-thumbprint",
|
||||
jti: "web-access-token-1",
|
||||
issuedAtEpochSeconds: 100,
|
||||
expiresAtEpochSeconds: 200,
|
||||
clientId: "t3-web",
|
||||
scopes: ["environment:connect", "environment:status"],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })),
|
||||
).toMatchObject({
|
||||
client_id: "t3-web",
|
||||
scope: ["environment:connect", "environment:status"],
|
||||
cnf: { jkt: "web-proof-key-thumbprint" },
|
||||
});
|
||||
});
|
||||
|
||||
it("treats requested scope as an order-independent set", () => {
|
||||
expect(
|
||||
resolveDpopAccessTokenScopes({
|
||||
clientId: "t3-mobile",
|
||||
scope: "environment:status environment:connect environment:status",
|
||||
}),
|
||||
).toEqual(["environment:status", "environment:connect"]);
|
||||
});
|
||||
|
||||
it("rejects signed DPoP tokens whose scope is outside the relay policy", async () => {
|
||||
const token = await Effect.runPromise(
|
||||
signRelayJwt({
|
||||
privateKey: keyPair.privateKey,
|
||||
typ: "t3-relay-dpop-access+jwt",
|
||||
payload: {
|
||||
iss: "https://relay.example.test",
|
||||
aud: "https://relay.example.test",
|
||||
sub: "user_123",
|
||||
jti: "access-token-invalid-scope",
|
||||
iat: 100,
|
||||
exp: 200,
|
||||
client_id: "t3-mobile",
|
||||
scope: "environment:admin",
|
||||
cnf: { jkt: "proof-key-thumbprint" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects mobile registration scope on a web public client token", async () => {
|
||||
const token = await Effect.runPromise(
|
||||
signRelayJwt({
|
||||
privateKey: keyPair.privateKey,
|
||||
typ: "t3-relay-dpop-access+jwt",
|
||||
payload: {
|
||||
iss: "https://relay.example.test",
|
||||
aud: "https://relay.example.test",
|
||||
sub: "user_123",
|
||||
jti: "web-token-invalid-mobile-scope",
|
||||
iat: 100,
|
||||
exp: 200,
|
||||
client_id: "t3-web",
|
||||
scope: "environment:connect mobile:registration",
|
||||
cnf: { jkt: "proof-key-thumbprint" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
await Effect.runPromise(verifyDpopAccessToken({ config, token, nowEpochSeconds: 150 })),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,186 +0,0 @@
|
||||
import {
|
||||
RelayDpopAccessTokenScope,
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
RelayMobileClientId,
|
||||
RelayMobileRegistrationScope,
|
||||
RelayWebClientId,
|
||||
type RelayPublicClientId,
|
||||
type RelayEnvironmentLinkChallengeRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";
|
||||
import { normalizeRelayIssuer, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as RelayConfiguration from "./Config.ts";
|
||||
|
||||
const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt";
|
||||
const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt";
|
||||
const LINK_CHALLENGE_KIND = "environment_link_challenge";
|
||||
|
||||
const LinkChallengeClaims = Schema.Struct({
|
||||
kind: Schema.Literal(LINK_CHALLENGE_KIND),
|
||||
iss: Schema.String,
|
||||
aud: Schema.String,
|
||||
sub: Schema.String,
|
||||
jti: Schema.String,
|
||||
iat: Schema.Int,
|
||||
exp: Schema.Int,
|
||||
notificationsEnabled: Schema.Boolean,
|
||||
liveActivitiesEnabled: Schema.Boolean,
|
||||
managedTunnelsEnabled: Schema.Boolean,
|
||||
});
|
||||
export type LinkChallengeClaims = typeof LinkChallengeClaims.Type;
|
||||
|
||||
const RelayDpopAccessTokenClaims = Schema.Struct({
|
||||
iss: Schema.String,
|
||||
aud: Schema.String,
|
||||
sub: Schema.String,
|
||||
jti: Schema.String,
|
||||
iat: Schema.Int,
|
||||
exp: Schema.Int,
|
||||
client_id: Schema.Literals([RelayMobileClientId, RelayWebClientId]),
|
||||
scope: Schema.String,
|
||||
cnf: Schema.Struct({ jkt: Schema.String }),
|
||||
});
|
||||
export type RelayDpopAccessTokenClaims = Omit<typeof RelayDpopAccessTokenClaims.Type, "scope"> & {
|
||||
readonly scope: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
};
|
||||
|
||||
const decodeLinkChallengeClaims = Schema.decodeUnknownEffect(LinkChallengeClaims);
|
||||
const decodeDpopAccessTokenClaims = Schema.decodeUnknownEffect(RelayDpopAccessTokenClaims);
|
||||
|
||||
const allowedScopesByClientId: Record<
|
||||
RelayPublicClientId,
|
||||
ReadonlySet<RelayDpopAccessTokenScope>
|
||||
> = {
|
||||
[RelayMobileClientId]: new Set([
|
||||
RelayEnvironmentConnectScope,
|
||||
RelayEnvironmentStatusScope,
|
||||
RelayMobileRegistrationScope,
|
||||
]),
|
||||
[RelayWebClientId]: new Set([RelayEnvironmentConnectScope, RelayEnvironmentStatusScope]),
|
||||
};
|
||||
|
||||
export function resolveDpopAccessTokenScopes(input: {
|
||||
readonly clientId: RelayPublicClientId;
|
||||
readonly scope: string;
|
||||
}): ReadonlyArray<RelayDpopAccessTokenScope> | null {
|
||||
return parseAllowedOAuthScope({
|
||||
value: input.scope,
|
||||
allowedScopes: allowedScopesByClientId[input.clientId],
|
||||
});
|
||||
}
|
||||
|
||||
export function issueLinkChallengeToken(input: {
|
||||
readonly config: RelayConfiguration.RelayConfigurationShape;
|
||||
readonly userId: string;
|
||||
readonly request: RelayEnvironmentLinkChallengeRequest;
|
||||
readonly jti: string;
|
||||
readonly issuedAtEpochSeconds: number;
|
||||
readonly expiresAtEpochSeconds: number;
|
||||
}) {
|
||||
const issuer = normalizeRelayIssuer(input.config.relayIssuer);
|
||||
return signRelayJwt({
|
||||
privateKey: Redacted.value(input.config.cloudMintPrivateKey),
|
||||
typ: LINK_CHALLENGE_TYP,
|
||||
payload: {
|
||||
kind: LINK_CHALLENGE_KIND,
|
||||
iss: issuer,
|
||||
aud: issuer,
|
||||
sub: input.userId,
|
||||
jti: input.jti,
|
||||
iat: input.issuedAtEpochSeconds,
|
||||
exp: input.expiresAtEpochSeconds,
|
||||
...input.request,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function verifyLinkChallengeToken(input: {
|
||||
readonly config: RelayConfiguration.RelayConfigurationShape;
|
||||
readonly token: string;
|
||||
readonly userId: string;
|
||||
readonly request: RelayEnvironmentLinkChallengeRequest;
|
||||
readonly nowEpochSeconds: number;
|
||||
}) {
|
||||
const issuer = normalizeRelayIssuer(input.config.relayIssuer);
|
||||
return verifyRelayJwt({
|
||||
publicKey: input.config.cloudMintPublicKey,
|
||||
token: input.token,
|
||||
typ: LINK_CHALLENGE_TYP,
|
||||
issuer,
|
||||
audience: issuer,
|
||||
nowEpochSeconds: input.nowEpochSeconds,
|
||||
}).pipe(
|
||||
Effect.flatMap(decodeLinkChallengeClaims),
|
||||
Effect.map((claims) => {
|
||||
if (
|
||||
claims.sub !== input.userId ||
|
||||
(input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||
|
||||
(input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||
|
||||
(input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return claims;
|
||||
}),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
}
|
||||
|
||||
export function issueDpopAccessToken(input: {
|
||||
readonly config: RelayConfiguration.RelayConfigurationShape;
|
||||
readonly userId: string;
|
||||
readonly proofKeyThumbprint: string;
|
||||
readonly jti: string;
|
||||
readonly issuedAtEpochSeconds: number;
|
||||
readonly expiresAtEpochSeconds: number;
|
||||
readonly clientId: RelayPublicClientId;
|
||||
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
|
||||
}) {
|
||||
const issuer = normalizeRelayIssuer(input.config.relayIssuer);
|
||||
return signRelayJwt({
|
||||
privateKey: Redacted.value(input.config.cloudMintPrivateKey),
|
||||
typ: ACCESS_TOKEN_TYP,
|
||||
payload: {
|
||||
iss: issuer,
|
||||
aud: issuer,
|
||||
sub: input.userId,
|
||||
jti: input.jti,
|
||||
iat: input.issuedAtEpochSeconds,
|
||||
exp: input.expiresAtEpochSeconds,
|
||||
client_id: input.clientId,
|
||||
scope: encodeOAuthScope(input.scopes),
|
||||
cnf: { jkt: input.proofKeyThumbprint },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function verifyDpopAccessToken(input: {
|
||||
readonly config: RelayConfiguration.RelayConfigurationShape;
|
||||
readonly token: string;
|
||||
readonly nowEpochSeconds: number;
|
||||
}) {
|
||||
const issuer = normalizeRelayIssuer(input.config.relayIssuer);
|
||||
return verifyRelayJwt({
|
||||
publicKey: input.config.cloudMintPublicKey,
|
||||
token: input.token,
|
||||
typ: ACCESS_TOKEN_TYP,
|
||||
issuer,
|
||||
audience: issuer,
|
||||
nowEpochSeconds: input.nowEpochSeconds,
|
||||
}).pipe(
|
||||
Effect.flatMap(decodeDpopAccessTokenClaims),
|
||||
Effect.map((claims): RelayDpopAccessTokenClaims | null => {
|
||||
const scopes = resolveDpopAccessTokenScopes({
|
||||
clientId: claims.client_id,
|
||||
scope: claims.scope,
|
||||
});
|
||||
return scopes === null ? null : { ...claims, scope: scopes };
|
||||
}),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
|
||||
export interface ClientPrincipalShape {
|
||||
readonly userId: string;
|
||||
}
|
||||
|
||||
export class ClientPrincipal extends Context.Service<ClientPrincipal, ClientPrincipalShape>()(
|
||||
"ClientPrincipal",
|
||||
) {}
|
||||
|
||||
export interface EnvironmentPrincipalShape {
|
||||
readonly environmentId: string;
|
||||
readonly credentialId: string;
|
||||
}
|
||||
|
||||
export class EnvironmentPrincipal extends Context.Service<
|
||||
EnvironmentPrincipal,
|
||||
EnvironmentPrincipalShape
|
||||
>()("EnvironmentPrincipal") {}
|
||||
@@ -1,270 +0,0 @@
|
||||
import {
|
||||
RelayEnvironmentLinkProofPayload,
|
||||
type RelayEnvironmentLinkProofInvalidReason,
|
||||
type RelayEnvironmentLinkRequest,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import {
|
||||
decodeRelayJwt,
|
||||
normalizeRelayIssuer,
|
||||
RELAY_LINK_PROOF_TYP,
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as DpopProofs from "../persistence/DpopProofs.ts";
|
||||
import * as EnvironmentCredentials from "../persistence/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "../persistence/EnvironmentLinks.ts";
|
||||
import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";
|
||||
import * as RelayConfiguration from "../Config.ts";
|
||||
import { verifyLinkChallengeToken } from "../relayTokens.ts";
|
||||
import { withUserId } from "../telemetry.ts";
|
||||
|
||||
export class EnvironmentLinkProofExpired extends Data.TaggedError("EnvironmentLinkProofExpired")<{
|
||||
readonly expiresAt: string;
|
||||
}> {}
|
||||
|
||||
export class EnvironmentLinkProofInvalid extends Data.TaggedError("EnvironmentLinkProofInvalid")<{
|
||||
readonly environmentId: string;
|
||||
readonly reason: RelayEnvironmentLinkProofInvalidReason;
|
||||
}> {}
|
||||
|
||||
export type EnvironmentLinkError =
|
||||
| EnvironmentLinkProofExpired
|
||||
| EnvironmentLinkProofInvalid
|
||||
| DpopProofs.DpopProofReplayPersistenceError
|
||||
| EnvironmentLinks.EnvironmentLinkUpsertPersistenceError
|
||||
| EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError
|
||||
| ManagedEndpointProvider.ManagedEndpointProviderError;
|
||||
|
||||
export interface EnvironmentLinkerShape {
|
||||
readonly link: (input: {
|
||||
readonly userId: string;
|
||||
readonly request: RelayEnvironmentLinkRequest;
|
||||
}) => Effect.Effect<
|
||||
{
|
||||
readonly environmentId: RelayEnvironmentLinkProofPayload["environmentId"];
|
||||
readonly endpoint: RelayEnvironmentLinkProofPayload["endpoint"];
|
||||
readonly endpointRuntime:
|
||||
| ManagedEndpointProvider.ManagedEndpointProvisioningResult["runtime"]
|
||||
| null;
|
||||
readonly environmentCredential: string;
|
||||
},
|
||||
EnvironmentLinkError
|
||||
>;
|
||||
}
|
||||
|
||||
export class EnvironmentLinker extends Context.Service<EnvironmentLinker, EnvironmentLinkerShape>()(
|
||||
"EnvironmentLinker",
|
||||
) {}
|
||||
|
||||
const decodeProof = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);
|
||||
|
||||
function proofAuthorizesRequestedCapabilities(
|
||||
proof: RelayEnvironmentLinkProofPayload,
|
||||
request: RelayEnvironmentLinkRequest,
|
||||
): boolean {
|
||||
const scopes = new Set(proof.scopes);
|
||||
if (request.managedTunnelsEnabled && !scopes.has("managed_tunnels")) {
|
||||
return false;
|
||||
}
|
||||
return !(
|
||||
(request.notificationsEnabled || request.liveActivitiesEnabled) &&
|
||||
!scopes.has("agent_activity_notifications")
|
||||
);
|
||||
}
|
||||
|
||||
function isSecureManagedEndpoint(endpoint: RelayEnvironmentLinkProofPayload["endpoint"]): boolean {
|
||||
try {
|
||||
const httpUrl = new URL(endpoint.httpBaseUrl);
|
||||
const wsUrl = new URL(endpoint.wsBaseUrl);
|
||||
return httpUrl.protocol === "https:" && wsUrl.protocol === "wss:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHostname(hostname: string): string {
|
||||
return hostname
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^\[(.*)\]$/u, "$1");
|
||||
}
|
||||
|
||||
function isLoopbackManagedTunnelOrigin(
|
||||
origin: RelayEnvironmentLinkProofPayload["origin"],
|
||||
): boolean {
|
||||
const hostname = normalizeHostname(origin.localHttpHost);
|
||||
return (
|
||||
(hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&
|
||||
Number.isInteger(origin.localHttpPort) &&
|
||||
origin.localHttpPort > 0 &&
|
||||
origin.localHttpPort <= 65_535
|
||||
);
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const links = yield* EnvironmentLinks.EnvironmentLinks;
|
||||
const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;
|
||||
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
|
||||
const proofReplay = yield* DpopProofs.DpopProofReplay;
|
||||
const config = yield* RelayConfiguration.RelayConfiguration;
|
||||
|
||||
return EnvironmentLinker.of({
|
||||
link: Effect.fn("relay.environment_linker.link")(
|
||||
function* (input) {
|
||||
const now = yield* DateTime.now;
|
||||
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
|
||||
const unverified = yield* Effect.try({
|
||||
try: () => decodeRelayJwt(input.request.proof),
|
||||
catch: () =>
|
||||
new EnvironmentLinkProofInvalid({
|
||||
environmentId: "unknown",
|
||||
reason: "invalid_signature_or_scope",
|
||||
}),
|
||||
});
|
||||
const decoded = yield* decodeProof(unverified).pipe(Effect.option);
|
||||
if (decoded._tag === "None") {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: "unknown",
|
||||
reason: "invalid_signature_or_scope",
|
||||
});
|
||||
}
|
||||
const candidate = decoded.value;
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.environment_id": candidate.environmentId,
|
||||
"relay.link.notifications_enabled": input.request.notificationsEnabled,
|
||||
"relay.link.live_activities_enabled": input.request.liveActivitiesEnabled,
|
||||
"relay.link.managed_tunnels_enabled": input.request.managedTunnelsEnabled,
|
||||
});
|
||||
if (candidate.exp <= nowSeconds) {
|
||||
return yield* new EnvironmentLinkProofExpired({
|
||||
expiresAt: DateTime.formatIso(DateTime.makeUnsafe(candidate.exp * 1_000)),
|
||||
});
|
||||
}
|
||||
const issuer = `t3-env:${candidate.environmentId}`;
|
||||
const relayIssuer = normalizeRelayIssuer(config.relayIssuer);
|
||||
const verified = yield* verifyRelayJwt({
|
||||
publicKey: candidate.environmentPublicKey,
|
||||
token: input.request.proof,
|
||||
typ: RELAY_LINK_PROOF_TYP,
|
||||
issuer,
|
||||
audience: relayIssuer,
|
||||
nowEpochSeconds: nowSeconds,
|
||||
}).pipe(
|
||||
Effect.flatMap(decodeProof),
|
||||
Effect.mapError(
|
||||
() =>
|
||||
new EnvironmentLinkProofInvalid({
|
||||
environmentId: candidate.environmentId,
|
||||
reason: "invalid_signature_or_scope",
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (
|
||||
verified.sub !== verified.environmentId ||
|
||||
!proofAuthorizesRequestedCapabilities(verified, input.request)
|
||||
) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: candidate.environmentId,
|
||||
reason: "invalid_signature_or_scope",
|
||||
});
|
||||
}
|
||||
if (verified.descriptor.environmentId !== verified.environmentId) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "descriptor_mismatch",
|
||||
});
|
||||
}
|
||||
const challenge = yield* verifyLinkChallengeToken({
|
||||
config,
|
||||
token: verified.challenge,
|
||||
userId: input.userId,
|
||||
request: {
|
||||
notificationsEnabled: input.request.notificationsEnabled,
|
||||
liveActivitiesEnabled: input.request.liveActivitiesEnabled,
|
||||
managedTunnelsEnabled: input.request.managedTunnelsEnabled,
|
||||
},
|
||||
nowEpochSeconds: nowSeconds,
|
||||
});
|
||||
if (challenge === null) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "challenge_invalid",
|
||||
});
|
||||
}
|
||||
const expiresAt = DateTime.make(verified.exp * 1_000);
|
||||
if (expiresAt._tag === "None") {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "invalid_signature_or_scope",
|
||||
});
|
||||
}
|
||||
const consumedNonce = yield* proofReplay.consume({
|
||||
thumbprint: verified.environmentPublicKey,
|
||||
jti: verified.jti,
|
||||
iat: verified.iat,
|
||||
expiresAt: expiresAt.value,
|
||||
});
|
||||
if (!consumedNonce) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "replayed_nonce",
|
||||
});
|
||||
}
|
||||
const consumedChallenge = yield* proofReplay.consume({
|
||||
thumbprint: "relay-environment-link-challenge",
|
||||
jti: challenge.jti,
|
||||
iat: challenge.iat,
|
||||
expiresAt: expiresAt.value,
|
||||
});
|
||||
if (!consumedChallenge) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "challenge_invalid",
|
||||
});
|
||||
}
|
||||
if (
|
||||
input.request.managedTunnelsEnabled &&
|
||||
!isLoopbackManagedTunnelOrigin(verified.origin)
|
||||
) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "origin_not_allowed",
|
||||
});
|
||||
}
|
||||
const provisioned = input.request.managedTunnelsEnabled
|
||||
? yield* managedEndpointProvider.provision({
|
||||
environmentId: verified.environmentId,
|
||||
origin: verified.origin,
|
||||
})
|
||||
: null;
|
||||
const endpoint = provisioned?.endpoint ?? verified.endpoint;
|
||||
if (!isSecureManagedEndpoint(endpoint)) {
|
||||
return yield* new EnvironmentLinkProofInvalid({
|
||||
environmentId: verified.environmentId,
|
||||
reason: "endpoint_not_secure",
|
||||
});
|
||||
}
|
||||
yield* links.upsert({ ...input, proof: verified, endpoint });
|
||||
const environmentCredential = yield* credentials.create({
|
||||
environmentId: verified.environmentId,
|
||||
environmentPublicKey: verified.environmentPublicKey,
|
||||
});
|
||||
return {
|
||||
environmentId: verified.environmentId,
|
||||
endpoint,
|
||||
endpointRuntime: provisioned?.runtime ?? null,
|
||||
environmentCredential,
|
||||
};
|
||||
},
|
||||
(effect, input) => effect.pipe(withUserId(input.userId)),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(EnvironmentLinker, make);
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
|
||||
import { withUserId } from "./telemetry.ts";
|
||||
|
||||
describe("relay telemetry", () => {
|
||||
it.effect("annotates the active span and descendant spans with the user id", () =>
|
||||
Effect.gen(function* () {
|
||||
const spans: Array<Tracer.NativeSpan> = [];
|
||||
const tracer = Tracer.make({
|
||||
span: (options) => {
|
||||
const span = new Tracer.NativeSpan(options);
|
||||
spans.push(span);
|
||||
return span;
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.succeed("ok").pipe(
|
||||
Effect.withSpan("relay.test.child"),
|
||||
withUserId("user-123"),
|
||||
Effect.withSpan("relay.test.parent"),
|
||||
Effect.provide(Layer.succeed(Tracer.Tracer, tracer)),
|
||||
);
|
||||
|
||||
expect(spans.map((span) => span.name)).toEqual(["relay.test.parent", "relay.test.child"]);
|
||||
expect(spans.map((span) => span.attributes.get("user.id"))).toEqual(["user-123", "user-123"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export const withSpanAttributes =
|
||||
(attributes: Record<string, unknown>) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
|
||||
Effect.annotateCurrentSpan(attributes).pipe(
|
||||
Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
|
||||
);
|
||||
|
||||
export const withUserId = (userId: string) => withSpanAttributes({ "user.id": userId });
|
||||
+103
-114
@@ -2,20 +2,18 @@ import * as Alchemy from "alchemy";
|
||||
import * as Cloudflare from "alchemy/Cloudflare";
|
||||
import * as Drizzle from "alchemy/Drizzle";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Etag from "effect/unstable/http/Etag";
|
||||
import * as HttpPlatform from "effect/unstable/http/HttpPlatform";
|
||||
import * as HttpRouter from "effect/unstable/http/HttpRouter";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as OtlpSerialization from "effect/unstable/observability/OtlpSerialization";
|
||||
import * as OtlpTracer from "effect/unstable/observability/OtlpTracer";
|
||||
|
||||
import { RelayApi } from "@t3tools/contracts/relay";
|
||||
|
||||
import {
|
||||
RelayHttpPlatformLayer,
|
||||
clientApi,
|
||||
dpopClientApi,
|
||||
healthApi,
|
||||
@@ -30,39 +28,54 @@ import {
|
||||
traceRelayHttpRequestWith,
|
||||
tokenApi,
|
||||
withoutCapturedParentSpan,
|
||||
} from "./api.ts";
|
||||
} from "./http/Api.ts";
|
||||
import {
|
||||
MANAGED_ENDPOINT_BASE_DOMAIN,
|
||||
MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES,
|
||||
MANAGED_ENDPOINT_ZONE,
|
||||
CLOUDFLARE_ACCOUNT_ID,
|
||||
MANAGED_ENDPOINT_ZONE_ID,
|
||||
MANAGED_ENDPOINT_ZONE_NAME,
|
||||
ManagedEndpointProvisionerToken,
|
||||
RELAY_PUBLIC_DOMAIN,
|
||||
RELAY_PUBLIC_ORIGIN,
|
||||
} from "./infra/ManagedEndpointStackConfig.ts";
|
||||
import {
|
||||
RELAY_AXIOM_TRACE_DATASET,
|
||||
RELAY_OBSERVABILITY_EXPORT_INTERVAL,
|
||||
RELAY_OBSERVABILITY_SERVICE_NAME,
|
||||
provisionRelayObservability,
|
||||
} from "./infra/RelayObservability.ts";
|
||||
import * as DeliveryAttempts from "./persistence/DeliveryAttempts.ts";
|
||||
import * as AgentActivityRows from "./persistence/AgentActivityRows.ts";
|
||||
import * as Devices from "./persistence/Devices.ts";
|
||||
import * as DpopProofs from "./persistence/DpopProofs.ts";
|
||||
import * as EnvironmentCredentials from "./persistence/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "./persistence/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "./persistence/LiveActivities.ts";
|
||||
} from "./managedEndpointStack.ts";
|
||||
import { makeRelayTraceLayer, RelayObservability } from "./observability.ts";
|
||||
import * as DeliveryAttempts from "./agentActivity/DeliveryAttempts.ts";
|
||||
import * as AgentActivityRows from "./agentActivity/AgentActivityRows.ts";
|
||||
import * as Devices from "./agentActivity/Devices.ts";
|
||||
import * as DpopProofs from "./auth/DpopProofs.ts";
|
||||
import * as RelayTokens from "./auth/RelayTokens.ts";
|
||||
import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts";
|
||||
import * as EnvironmentLinks from "./environments/EnvironmentLinks.ts";
|
||||
import * as LiveActivities from "./agentActivity/LiveActivities.ts";
|
||||
import { RelayDb, RelayHyperdrive } from "./db.ts";
|
||||
import { RelayApnsDeliveryDeadLetterQueue, RelayApnsDeliveryQueue } from "./queues.ts";
|
||||
import * as RelayConfiguration from "./Config.ts";
|
||||
import * as AgentActivityPublisher from "./services/AgentActivityPublisher.ts";
|
||||
import * as ApnsDeliveryQueue from "./services/ApnsDeliveryQueue.ts";
|
||||
import * as ApnsDeliveries from "./services/ApnsDeliveries.ts";
|
||||
import * as EnvironmentConnector from "./services/EnvironmentConnector.ts";
|
||||
import * as EnvironmentLinker from "./services/EnvironmentLinker.ts";
|
||||
import * as EnvironmentPublishSignatures from "./services/EnvironmentPublishSignatures.ts";
|
||||
import * as ManagedEndpointProvider from "./services/ManagedEndpointProvider.ts";
|
||||
import * as MobileRegistrations from "./services/MobileRegistrations.ts";
|
||||
import * as RelayCrypto from "./RelayCrypto.ts";
|
||||
import * as AgentActivityPublisher from "./agentActivity/AgentActivityPublisher.ts";
|
||||
import * as ApnsClient from "./agentActivity/ApnsClient.ts";
|
||||
import * as ApnsDeliveryQueue from "./agentActivity/ApnsDeliveryQueue.ts";
|
||||
import * as ApnsDeliveries from "./agentActivity/ApnsDeliveries.ts";
|
||||
import * as EnvironmentConnector from "./environments/EnvironmentConnector.ts";
|
||||
import * as EnvironmentLinker from "./environments/EnvironmentLinker.ts";
|
||||
import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublishSignatures.ts";
|
||||
import * as ManagedEndpointProvider from "./environments/ManagedEndpointProvider.ts";
|
||||
import * as MobileRegistrations from "./agentActivity/MobileRegistrations.ts";
|
||||
|
||||
const webcryptoLayer = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
Crypto.make({
|
||||
randomBytes: (size) => globalThis.crypto.getRandomValues(new Uint8Array(size)),
|
||||
digest: (algorithm, data) =>
|
||||
Effect.promise(async () => {
|
||||
const input = new Uint8Array(data.length);
|
||||
input.set(data);
|
||||
return new Uint8Array(await globalThis.crypto.subtle.digest(algorithm, input.buffer));
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const httpPlatformNotSupportedLayer = Layer.succeed(HttpPlatform.HttpPlatform, {
|
||||
fileResponse: () => Effect.die("Relay API does not serve filesystem responses"),
|
||||
fileWebResponse: () => Effect.die("Relay API does not serve file responses"),
|
||||
});
|
||||
|
||||
const relayApiLayer = Layer.mergeAll(
|
||||
healthApi,
|
||||
@@ -74,32 +87,10 @@ const relayApiLayer = Layer.mergeAll(
|
||||
serverApi,
|
||||
);
|
||||
|
||||
const makeRelayTraceLayer = (input: {
|
||||
readonly tracesEndpoint: string;
|
||||
readonly tracesDatasetName: string;
|
||||
readonly ingestToken: Redacted.Redacted<string>;
|
||||
}) =>
|
||||
OtlpTracer.layer({
|
||||
url: input.tracesEndpoint,
|
||||
resource: {
|
||||
serviceName: RELAY_OBSERVABILITY_SERVICE_NAME,
|
||||
attributes: {
|
||||
"service.runtime": "cloudflare-worker",
|
||||
"service.component": "relay",
|
||||
},
|
||||
},
|
||||
headers: {
|
||||
Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
|
||||
"X-Axiom-Dataset": input.tracesDatasetName,
|
||||
},
|
||||
exportInterval: RELAY_OBSERVABILITY_EXPORT_INTERVAL,
|
||||
}).pipe(Layer.provide(OtlpSerialization.layerJson));
|
||||
|
||||
// Bind secrets explicitly and only read them through the runtime worker
|
||||
// environment. Reading them through Config during Worker init currently
|
||||
// registers a competing plaintext binding.
|
||||
const apnsPrivateKeyConfig = Config.redacted("APNS_PRIVATE_KEY");
|
||||
const clerkSecretKeyConfig = Config.redacted("CLERK_SECRET_KEY");
|
||||
const CloudMintKeyPair = Alchemy.KeyPair("CloudMintKeyPair");
|
||||
const ApnsDeliveryJobSigningSecret = Alchemy.makeRandom("ApnsDeliveryJobSigningSecret", {
|
||||
bytes: 32,
|
||||
});
|
||||
|
||||
export default class Api extends Cloudflare.Worker<Api>()(
|
||||
"Api",
|
||||
@@ -110,58 +101,57 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
flags: ["nodejs_compat"],
|
||||
},
|
||||
domain: RELAY_PUBLIC_DOMAIN,
|
||||
env: {
|
||||
APNS_PRIVATE_KEY: apnsPrivateKeyConfig,
|
||||
CLERK_SECRET_KEY: clerkSecretKeyConfig,
|
||||
},
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const managedEndpointProvisionerToken = yield* Cloudflare.AccountApiToken(
|
||||
"ManagedEndpointProvisionerToken",
|
||||
{
|
||||
name: "t3-code-relay-managed-endpoint-provisioner",
|
||||
policies: MANAGED_ENDPOINT_PROVISIONER_TOKEN_POLICIES,
|
||||
},
|
||||
);
|
||||
const managedEndpointCloudflareApiToken = yield* managedEndpointProvisionerToken.value;
|
||||
const relayHyperdrive = yield* RelayHyperdrive;
|
||||
//
|
||||
// 1. Provision Infrastructure for the Worker to use
|
||||
//
|
||||
const apnsDeliveryQueue = yield* RelayApnsDeliveryQueue;
|
||||
const apnsDeliveryDeadLetterQueue = yield* RelayApnsDeliveryDeadLetterQueue;
|
||||
const hyperdrive = yield* Cloudflare.Hyperdrive.bind(relayHyperdrive);
|
||||
const apnsDeliveryQueueSender = yield* Cloudflare.QueueBinding.bind(apnsDeliveryQueue);
|
||||
const cloudMintKeyPair = yield* Alchemy.KeyPair("CloudMintKeyPair");
|
||||
const alchemyRuntimeContext = yield* Alchemy.RuntimeContext;
|
||||
const cloudMintKeyPair = yield* CloudMintKeyPair;
|
||||
const hyperdrive = yield* Cloudflare.Hyperdrive.bind(yield* RelayHyperdrive);
|
||||
const managedEndpointProvisionerToken = yield* ManagedEndpointProvisionerToken;
|
||||
const managedEndpointCloudflareApiToken = yield* managedEndpointProvisionerToken.value;
|
||||
const randomApnsDeliveryJobSigningSecret = yield* ApnsDeliveryJobSigningSecret;
|
||||
const observability = yield* RelayObservability;
|
||||
|
||||
//
|
||||
// 2. Create bindings
|
||||
//
|
||||
const environment = yield* Config.schema(
|
||||
RelayConfiguration.ApnsEnvironment,
|
||||
"APNS_ENVIRONMENT",
|
||||
).pipe(Config.withDefault("sandbox"));
|
||||
);
|
||||
const apnsTeamId = yield* Config.string("APNS_TEAM_ID");
|
||||
const apnsKeyId = yield* Config.string("APNS_KEY_ID");
|
||||
const apnsBundleId = yield* Config.string("APNS_BUNDLE_ID");
|
||||
const relayObservability = yield* provisionRelayObservability;
|
||||
const axiomIngestToken = yield* relayObservability.ingestToken.token;
|
||||
const axiomTracesEndpoint = yield* relayObservability.traces.otelTracesEndpoint;
|
||||
const relayTraceLayer = Effect.all({
|
||||
tracesEndpoint: axiomTracesEndpoint,
|
||||
ingestToken: axiomIngestToken,
|
||||
}).pipe(
|
||||
Effect.map((input) =>
|
||||
makeRelayTraceLayer({ ...input, tracesDatasetName: RELAY_AXIOM_TRACE_DATASET }),
|
||||
),
|
||||
Layer.unwrap,
|
||||
);
|
||||
const randomApnsDeliveryJobSigningSecret = yield* Alchemy.Random(
|
||||
"ApnsDeliveryJobSigningSecret",
|
||||
{ bytes: 32 },
|
||||
);
|
||||
const apnsDeliveryJobSigningSecret = yield* randomApnsDeliveryJobSigningSecret.text;
|
||||
const apnsPrivateKey = yield* Config.redacted("APNS_PRIVATE_KEY");
|
||||
const apnsDeliveryJobSigningSecret = yield* randomApnsDeliveryJobSigningSecret;
|
||||
|
||||
const axiomDatasetName = yield* observability.traces.name;
|
||||
const axiomIngestToken = yield* observability.ingestToken.token;
|
||||
const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint;
|
||||
|
||||
const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");
|
||||
|
||||
const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;
|
||||
const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;
|
||||
const db = yield* Drizzle.postgres(hyperdrive.connectionString);
|
||||
const queueSender = ApnsDeliveryQueue.ApnsDeliveryQueueSender.of({
|
||||
send: (body) =>
|
||||
apnsDeliveryQueueSender.send(body).pipe(
|
||||
Effect.mapError((cause) => new ApnsDeliveryQueue.ApnsDeliveryQueueSendError({ cause })),
|
||||
Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),
|
||||
),
|
||||
});
|
||||
|
||||
//
|
||||
// 3. Runtime layers and app construction
|
||||
//
|
||||
|
||||
const loadSettings = Effect.gen(function* () {
|
||||
const workerEnvironment = yield* Cloudflare.WorkerEnvironment;
|
||||
const apnsPrivateKey = Redacted.make(workerEnvironment.APNS_PRIVATE_KEY);
|
||||
const clerkSecretKey = Redacted.make(workerEnvironment.CLERK_SECRET_KEY);
|
||||
return RelayConfiguration.RelayConfiguration.of({
|
||||
relayIssuer: RELAY_PUBLIC_ORIGIN,
|
||||
apns: {
|
||||
@@ -175,16 +165,25 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
clerkSecretKey,
|
||||
cloudMintPrivateKey: yield* cloudMintPrivateKey,
|
||||
cloudMintPublicKey: yield* cloudMintPublicKey,
|
||||
managedEndpointBaseDomain: MANAGED_ENDPOINT_BASE_DOMAIN,
|
||||
cloudflareAccountId: MANAGED_ENDPOINT_ZONE.accountId,
|
||||
cloudflareZoneId: MANAGED_ENDPOINT_ZONE.zoneId,
|
||||
managedEndpointBaseDomain: MANAGED_ENDPOINT_ZONE_NAME,
|
||||
cloudflareAccountId: CLOUDFLARE_ACCOUNT_ID,
|
||||
cloudflareZoneId: MANAGED_ENDPOINT_ZONE_ID,
|
||||
cloudflareApiToken: yield* managedEndpointCloudflareApiToken,
|
||||
});
|
||||
});
|
||||
|
||||
const relayTraceLayer = Layer.unwrap(
|
||||
Effect.all({
|
||||
tracesDatasetName: axiomDatasetName,
|
||||
tracesEndpoint: axiomTracesEndpoint,
|
||||
ingestToken: axiomIngestToken,
|
||||
}).pipe(Effect.map(makeRelayTraceLayer)),
|
||||
);
|
||||
|
||||
const runtimeLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* loadSettings;
|
||||
|
||||
return Layer.mergeAll(
|
||||
MobileRegistrations.layer.pipe(Layer.provideMerge(AgentActivityPublisher.layer)),
|
||||
EnvironmentConnector.layer,
|
||||
@@ -195,7 +194,7 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
EnvironmentPublishSignatures.layer.pipe(Layer.provideMerge(DpopProofs.layer)),
|
||||
DpopProofs.layer,
|
||||
).pipe(
|
||||
Layer.provide(ApnsDeliveries.layer),
|
||||
Layer.provide(ApnsDeliveries.layer.pipe(Layer.provide(ApnsClient.layer))),
|
||||
Layer.provide(ApnsDeliveryQueue.layer),
|
||||
Layer.provide(AgentActivityRows.layer),
|
||||
Layer.provide(Devices.layer),
|
||||
@@ -203,21 +202,11 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
Layer.provide(EnvironmentLinks.layer),
|
||||
Layer.provide(LiveActivities.layer),
|
||||
Layer.provide(DeliveryAttempts.layer),
|
||||
Layer.provide(RelayTokens.layer),
|
||||
Layer.provide(Layer.succeed(RelayDb, db)),
|
||||
Layer.provide(
|
||||
Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
|
||||
send: (body) =>
|
||||
apnsDeliveryQueueSender
|
||||
.send(body)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ApnsDeliveryQueue.ApnsDeliveryQueueSendError({ cause }),
|
||||
),
|
||||
) as Effect.Effect<void, ApnsDeliveryQueue.ApnsDeliveryQueueSendError>,
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, queueSender)),
|
||||
Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, settings)),
|
||||
Layer.provide(RelayCrypto.layer),
|
||||
Layer.provide(webcryptoLayer),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -232,9 +221,10 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
Layer.provide(relayEnvironmentAuthLayer),
|
||||
Layer.provide(EnvironmentCredentials.layer),
|
||||
Layer.provide(EnvironmentLinks.layer),
|
||||
Layer.provide(RelayTokens.layer),
|
||||
Layer.provide(Layer.succeed(RelayDb, db)),
|
||||
Layer.provideMerge(Layer.succeed(RelayConfiguration.RelayConfiguration, settings)),
|
||||
Layer.provide(RelayCrypto.layer),
|
||||
Layer.provide(webcryptoLayer),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -271,14 +261,13 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
const fetch = Layer.merge(
|
||||
HttpApiBuilder.layer(RelayApi).pipe(
|
||||
Layer.provide(appLayer),
|
||||
Layer.provide([Etag.layerWeak, RelayHttpPlatformLayer, relayCors]),
|
||||
Layer.provide([Etag.layerWeak, httpPlatformNotSupportedLayer, relayCors]),
|
||||
),
|
||||
relayNotFoundRoute,
|
||||
).pipe(
|
||||
HttpRouter.toHttpEffect,
|
||||
withoutCapturedParentSpan,
|
||||
Effect.map((httpEffect) => traceRelayHttpRequestWith(httpEffect, relayTraceLayer)),
|
||||
Effect.flatten,
|
||||
Effect.flatMap((httpEffect) => traceRelayHttpRequestWith(httpEffect, relayTraceLayer)),
|
||||
);
|
||||
|
||||
return { fetch };
|
||||
|
||||
Reference in new issue
Block a user