Skip to content

Commit 848e7a9

Browse files
refactor(server): sign server tokens through PayloadSigner
Five modules each loaded a secret and called signPayload/verify helpers that rebuilt the HMAC key per call, and the asset helpers reloaded the secret and carried Mac in their requirements. PayloadSigner builds the key once and exposes sign/verify; AssetSigner holds the key shared by asset and upload URLs. Signatures are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7faf852 commit 848e7a9

16 files changed

Lines changed: 152 additions & 153 deletions

‎apps/server/src/assets/AssetAccess.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import * as TestClock from "effect/testing/TestClock";
2525
import { HttpClientRequest, HttpClientResponse, HttpServerResponse } from "effect/http";
2626
import { vi } from "vite-plus/test";
2727

28+
import * as AssetSigner from "./AssetSigner.ts";
2829
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
2930
import * as ServerConfig from "../config.ts";
3031
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
@@ -119,7 +120,9 @@ const layerTest = Layer.mergeAll(
119120
Layer.provide(T3ProjectFileLoader.layer),
120121
),
121122
NativeAppIconResolver.layer.pipe(Layer.provide(layerConfig)),
122-
ServerSecretStore.layer.pipe(Layer.provide(layerConfig)),
123+
AssetSigner.layer.pipe(
124+
Layer.provideMerge(ServerSecretStore.layer.pipe(Layer.provide(layerConfig))),
125+
),
123126
).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
124127

125128
describe("AssetAccess", () => {

‎apps/server/src/assets/AssetAccess.ts‎

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,8 @@ import * as Path from "effect/Path";
4747
import * as Schema from "effect/Schema";
4848
import * as Stream from "effect/Stream";
4949

50-
import {
51-
base64UrlDecodeUtf8,
52-
base64UrlEncode,
53-
signPayload,
54-
verifyPayloadSignature,
55-
} from "../auth/utils.ts";
56-
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
50+
import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
51+
import * as AssetSigner from "./AssetSigner.ts";
5752
import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts";
5853
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
5954
import * as ServerConfig from "../config.ts";
@@ -70,7 +65,6 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
7065

7166
export const ASSET_ROUTE_PREFIX = "/api/assets";
7267

73-
const SIGNING_SECRET_NAME = "asset-access-signing-key";
7468
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
7569
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
7670
const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
@@ -848,16 +842,6 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
848842
}
849843
}
850844

851-
const secretStore = yield* ServerSecretStore.ServerSecretStore;
852-
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
853-
Effect.mapError(
854-
(cause) =>
855-
new AssetSigningKeyLoadError({
856-
resource: input.resource,
857-
cause,
858-
}),
859-
),
860-
);
861845
if (claims.kind === "project-favicon" || claims.kind === "project-favicon-external") {
862846
const issuedAt = yield* Clock.currentTimeMillis;
863847
expiresAt =
@@ -872,7 +856,13 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
872856
claims = { ...claims, expiresAt };
873857
}
874858
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
875-
const token = `${encodedPayload}.${yield* signPayload(encodedPayload, signingSecret)}`;
859+
const signer = yield* AssetSigner.AssetSigner;
860+
const signature = yield* signer
861+
.sign(encodedPayload)
862+
.pipe(
863+
Effect.mapError((cause) => new AssetSigningKeyLoadError({ resource: input.resource, cause })),
864+
);
865+
const token = `${encodedPayload}.${signature}`;
876866
return {
877867
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
878868
expiresAt,
@@ -889,13 +879,12 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
889879
const [encodedPayload, signature] = token.split(".");
890880
if (!encodedPayload || !signature) return null;
891881

892-
const secretStore = yield* ServerSecretStore.ServerSecretStore;
893-
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(
882+
const signer = yield* AssetSigner.AssetSigner;
883+
const verified = yield* signer.verify(encodedPayload, signature).pipe(
894884
Effect.tapError((cause) => Effect.logError("Failed to load the asset signing key.", { cause })),
895-
Effect.orElseSucceed(() => null),
885+
Effect.orElseSucceed(() => false),
896886
);
897-
if (!signingSecret) return null;
898-
if (!(yield* verifyPayloadSignature(encodedPayload, signature, signingSecret))) return null;
887+
if (!verified) return null;
899888

900889
const claims = decodeClaims(encodedPayload);
901890
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import * as Context from "effect/Context";
2+
import * as Layer from "effect/Layer";
3+
4+
import * as PayloadSigner from "../auth/PayloadSigner.ts";
5+
import type * as ServerSecretStore from "../auth/ServerSecretStore.ts";
6+
7+
/** Signs asset and attachment-upload URLs; both share one key. */
8+
export class AssetSigner extends Context.Service<
9+
AssetSigner,
10+
PayloadSigner.PayloadSigner<ServerSecretStore.SecretStoreError>
11+
>()("t3/assets/AssetSigner") {}
12+
13+
export const layer = Layer.effect(AssetSigner, PayloadSigner.make("asset-access-signing-key"));

‎apps/server/src/assets/AttachmentUpload.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as AssetSigner from "./AssetSigner.ts";
12
import * as DocumentText from "../provider/DocumentText.ts";
23
// @effect-diagnostics nodeBuiltinImport:off
34
import * as NodeFS from "node:fs";
@@ -17,7 +18,7 @@ import * as Schema from "effect/Schema";
1718
import * as Stream from "effect/Stream";
1819

1920
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
20-
import { base64UrlEncode, signPayload } from "../auth/utils.ts";
21+
import { base64UrlEncode } from "../auth/utils.ts";
2122
import * as ServerConfig from "../config.ts";
2223
import {
2324
claimPendingAttachments,
@@ -31,7 +32,8 @@ import {
3132
validateAttachmentUploadToken,
3233
} from "./AttachmentUpload.ts";
3334

34-
const layerTest = ServerSecretStore.layer.pipe(
35+
const layerTest = AssetSigner.layer.pipe(
36+
Layer.provideMerge(ServerSecretStore.layer),
3537
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-upload-" })),
3638
Layer.provideMerge(
3739
DocumentText.layer.pipe(
@@ -152,8 +154,7 @@ describe("AttachmentUpload", () => {
152154
it.effect("accepts unexpired image upload tokens issued before file support", () =>
153155
Effect.gen(function* () {
154156
const issued = yield* issueAttachmentUploadUrl(uploadInput);
155-
const secretStore = yield* ServerSecretStore.ServerSecretStore;
156-
const secret = yield* secretStore.getOrCreateRandom("asset-access-signing-key", 32);
157+
const signer = yield* AssetSigner.AssetSigner;
157158
const encodedPayload = base64UrlEncode(
158159
yield* encodeLegacyAttachmentUploadClaims({
159160
version: 1,
@@ -165,7 +166,7 @@ describe("AttachmentUpload", () => {
165166
expiresAt: issued.expiresAt,
166167
}),
167168
);
168-
const legacyToken = `${encodedPayload}.${yield* signPayload(encodedPayload, secret)}`;
169+
const legacyToken = `${encodedPayload}.${yield* signer.sign(encodedPayload)}`;
169170

170171
expect(yield* validateAttachmentUploadToken(legacyToken)).toMatchObject({
171172
type: "image",

‎apps/server/src/assets/AttachmentUpload.ts‎

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,14 @@ import {
2727
sweepStalePendingAttachments,
2828
} from "../attachmentStore.ts";
2929
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
30-
import {
31-
base64UrlDecodeUtf8,
32-
base64UrlEncode,
33-
signPayload,
34-
verifyPayloadSignature,
35-
} from "../auth/utils.ts";
36-
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
30+
import { base64UrlDecodeUtf8, base64UrlEncode } from "../auth/utils.ts";
31+
import * as AssetSigner from "./AssetSigner.ts";
3732
import * as ServerConfig from "../config.ts";
3833
import { inferImageExtension } from "../imageMime.ts";
3934
import * as DocumentText from "../provider/DocumentText.ts";
4035

4136
export const ATTACHMENT_UPLOAD_ROUTE_PREFIX = "/api/attachments/upload";
4237

43-
const SIGNING_SECRET_NAME = "asset-access-signing-key";
4438
const PENDING_ATTACHMENT_SWEEP_INTERVAL_MS = 15 * 60_000;
4539
const lastPendingSweepByDirectory = new Map<string, number>();
4640

@@ -70,17 +64,9 @@ function decodeClaims(encodedPayload: string): AttachmentUploadClaims | null {
7064
}
7165
}
7266

73-
const loadSigningSecret = Effect.gen(function* () {
74-
const secretStore = yield* ServerSecretStore.ServerSecretStore;
75-
return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
76-
});
77-
7867
export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(function* (
7968
input: AttachmentCreateUploadUrlInput,
8069
) {
81-
const secret = yield* loadSigningSecret.pipe(
82-
Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })),
83-
);
8470
const config = yield* ServerConfig.ServerConfig;
8571
const nowMs = yield* Clock.currentTimeMillis;
8672
const previousSweep = lastPendingSweepByDirectory.get(config.attachmentsDir);
@@ -120,7 +106,10 @@ export const issueAttachmentUploadUrl = Effect.fn("AttachmentUpload.issueUrl")(f
120106
}),
121107
);
122108

123-
const signature = yield* signPayload(encodedPayload, secret);
109+
const signer = yield* AssetSigner.AssetSigner;
110+
const signature = yield* signer
111+
.sign(encodedPayload)
112+
.pipe(Effect.mapError((cause) => new AttachmentUploadSigningKeyError({ cause })));
124113
return {
125114
attachmentId,
126115
relativeUrl: `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/${encodedPayload}.${signature}`,
@@ -136,13 +125,14 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat
136125
return null;
137126
}
138127

139-
const secret = yield* loadSigningSecret.pipe(
128+
const signer = yield* AssetSigner.AssetSigner;
129+
const verified = yield* signer.verify(encodedPayload, signature).pipe(
140130
Effect.tapError((cause) =>
141131
Effect.logError("Failed to load the attachment upload signing key.", { cause }),
142132
),
143-
Effect.orElseSucceed(() => null),
133+
Effect.orElseSucceed(() => false),
144134
);
145-
if (!secret || !(yield* verifyPayloadSignature(encodedPayload, signature, secret))) {
135+
if (!verified) {
146136
return null;
147137
}
148138

‎apps/server/src/auth/McpOAuth.ts‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import * as Clock from "effect/Clock";
2323
import * as Context from "effect/Context";
2424
import * as Digest from "effect/crypto/Digest";
2525
import * as SecureRandom from "effect/crypto/SecureRandom";
26-
import * as Mac from "effect/crypto/Mac";
2726
import * as Effect from "effect/Effect";
2827
import * as Layer from "effect/Layer";
2928
import * as Option from "effect/Option";
@@ -37,15 +36,14 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
3736
import * as ServerSettings from "../serverSettings.ts";
3837
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
3938
import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
39+
import * as PayloadSigner from "./PayloadSigner.ts";
4040
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
4141
import * as ServerSecretStore from "./ServerSecretStore.ts";
4242
import {
4343
base64UrlDecodeUtf8,
4444
base64UrlEncode,
4545
deriveAuthClientMetadata,
46-
signPayload,
4746
timingSafeEqualBase64Url,
48-
verifyPayloadSignature,
4947
} from "./utils.ts";
5048
import { requestUrl } from "../requestUrl.ts";
5149

@@ -263,14 +261,12 @@ const make = Effect.gen(function* () {
263261
Effect.map((settings) => settings.linkedEnvironmentsEnabled),
264262
Effect.orElseSucceed(() => false),
265263
);
266-
const signingKey = yield* secretStore
267-
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
268-
.pipe(Effect.orDie);
264+
const signer = yield* PayloadSigner.fromSecret(
265+
yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie),
266+
);
269267
const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
270268

271-
const mac = yield* Mac.Mac;
272-
const sign = (domain: string, payload: string) =>
273-
signPayload(`${domain}.${payload}`, signingKey).pipe(Effect.provideService(Mac.Mac, mac));
269+
const sign = (domain: string, payload: string) => signer.sign(`${domain}.${payload}`);
274270

275271
const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
276272
const body = base64UrlEncode(
@@ -285,11 +281,7 @@ const make = Effect.gen(function* () {
285281
): Effect.fn.Return<McpOAuthClient | undefined> {
286282
const [body, signature, extra] = clientId.split(".");
287283
if (!body || !signature || extra !== undefined) return undefined;
288-
const verified = yield* verifyPayloadSignature(
289-
`mcp-client-id.${body}`,
290-
signature,
291-
signingKey,
292-
).pipe(Effect.provideService(Mac.Mac, mac));
284+
const verified = yield* signer.verify(`mcp-client-id.${body}`, signature);
293285
if (!verified) return undefined;
294286
const json = yield* Effect.try(() => base64UrlDecodeUtf8(body)).pipe(Effect.option);
295287
if (Option.isNone(json)) return undefined;
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import * as Mac from "effect/crypto/Mac";
2+
import * as Effect from "effect/Effect";
3+
import * as Base64Url from "effect/encoding/Base64Url";
4+
import * as Result from "effect/Result";
5+
6+
import * as ServerSecretStore from "./ServerSecretStore.ts";
7+
8+
/** HMAC-SHA256 signatures over UTF-8 payloads, as unpadded base64url. */
9+
export interface PayloadSigner<E = never> {
10+
readonly sign: (payload: string) => Effect.Effect<string, E>;
11+
readonly verify: (payload: string, signature: string) => Effect.Effect<boolean, E>;
12+
}
13+
14+
const utf8 = (value: string) => new TextEncoder().encode(value);
15+
16+
const fromKey = <E>(mac: Mac.Mac["Service"], key: Effect.Effect<Mac.Key, E>): PayloadSigner<E> => ({
17+
sign: (payload) =>
18+
key.pipe(
19+
Effect.flatMap((loaded) => mac.sign(loaded, utf8(payload)).pipe(Effect.orDie)),
20+
Effect.map(Base64Url.encode),
21+
),
22+
verify: (payload, signature) => {
23+
const tag = Base64Url.decode(signature);
24+
return Result.isFailure(tag)
25+
? Effect.succeed(false)
26+
: key.pipe(
27+
Effect.flatMap((loaded) =>
28+
mac.verify(loaded, tag.success, utf8(payload)).pipe(Effect.orDie),
29+
),
30+
);
31+
},
32+
});
33+
34+
/** A signer for secret bytes the caller already holds. */
35+
export const fromSecret = Effect.fn("PayloadSigner.fromSecret")(function* (secret: Uint8Array) {
36+
const mac = yield* Mac.Mac;
37+
const key = yield* Mac.key(Mac.hmacSha256, secret).pipe(Effect.orDie);
38+
return fromKey(mac, Effect.succeed(key));
39+
});
40+
41+
/** A signer keyed by a named server secret, loaded on first use so store failures reach callers. */
42+
export const make = Effect.fn("PayloadSigner.make")(function* (secretName: string) {
43+
const secrets = yield* ServerSecretStore.ServerSecretStore;
44+
const mac = yield* Mac.Mac;
45+
let key: Mac.Key | undefined;
46+
const loadKey = Effect.suspend(() =>
47+
key !== undefined
48+
? Effect.succeed(key)
49+
: secrets.getOrCreateRandom(secretName, 32).pipe(
50+
Effect.flatMap((bytes) => Mac.key(Mac.hmacSha256, bytes).pipe(Effect.orDie)),
51+
Effect.tap((loaded) =>
52+
Effect.sync(() => {
53+
key = loaded;
54+
}),
55+
),
56+
),
57+
);
58+
return fromKey(mac, loadKey);
59+
});

‎apps/server/src/auth/SessionStore.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
1919
import * as SqlitePersistence from "../persistence/Sqlite.ts";
2020
import * as SessionStore from "./SessionStore.ts";
2121
import * as ServerSecretStore from "./ServerSecretStore.ts";
22-
import { base64UrlDecodeUtf8, base64UrlEncode, signPayload } from "./utils.ts";
22+
import { base64UrlDecodeUtf8, base64UrlEncode } from "./utils.ts";
23+
import * as PayloadSigner from "./PayloadSigner.ts";
2324

2425
const layerServerConfig = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
2526
Layer.effect(
@@ -367,12 +368,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("SessionStore.lay
367368
const [encodedPayload] = issued.token.split(".");
368369
const currentClaims = base64UrlDecodeUtf8(encodedPayload!);
369370
expect(currentClaims).toContain('"v":1');
370-
const secret = yield* secrets.getOrCreateRandom("server-signing-key", 32);
371+
const signer = yield* PayloadSigner.fromSecret(
372+
yield* secrets.getOrCreateRandom("server-signing-key", 32),
373+
);
371374
const resign = (claims: string) => {
372375
const payload = base64UrlEncode(claims);
373-
return signPayload(payload, secret).pipe(
374-
Effect.map((signature) => `${payload}.${signature}`),
375-
);
376+
return signer.sign(payload).pipe(Effect.map((signature) => `${payload}.${signature}`));
376377
};
377378
const legacyToken = yield* resign(currentClaims.replace('"v":1', '"v":2'));
378379
const editedToken = yield* resign(

0 commit comments

Comments
 (0)