Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1cb9811e93 | ||
|
|
a2b6fd8274 |
No files matched your search
@@ -95,24 +95,7 @@ describe("mobile DPoP", () => {
|
||||
|
||||
const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
operation: "decode-key",
|
||||
cause: expect.anything(),
|
||||
});
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
it.effect("reports invalid proof URLs as a structural operation failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const proofKey = yield* generateDpopProofKeyPair();
|
||||
const error = yield* createDpopProof({
|
||||
method: "POST",
|
||||
url: "not a URL",
|
||||
proofKey,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({ operation: "normalize-proof-url" });
|
||||
expect(error.cause).toBeUndefined();
|
||||
expect(error.message).toBe("Stored DPoP proof key is invalid.");
|
||||
}).pipe(Effect.provide(cryptoLayer)),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -15,53 +16,13 @@ import {
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
export class CloudDpopError extends Schema.TaggedErrorClass<CloudDpopError>()("CloudDpopError", {
|
||||
operation: Schema.Literals([
|
||||
"generate-key-randomness",
|
||||
"derive-public-key",
|
||||
"read-key",
|
||||
"decode-key",
|
||||
"validate-key",
|
||||
"encode-key",
|
||||
"store-key",
|
||||
"normalize-proof-url",
|
||||
"import-private-key",
|
||||
"generate-proof-id",
|
||||
"encode-proof-header",
|
||||
"encode-proof-payload",
|
||||
"hash-signing-input",
|
||||
"sign-proof",
|
||||
]),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Cloud DPoP operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class DpopPublicKeyFormatError extends Schema.TaggedErrorClass<DpopPublicKeyFormatError>()(
|
||||
"DpopPublicKeyFormatError",
|
||||
{
|
||||
byteLength: Schema.Number,
|
||||
firstByte: Schema.optional(Schema.Number),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const prefix =
|
||||
this.firstByte === undefined
|
||||
? "no prefix byte"
|
||||
: `prefix 0x${this.firstByte.toString(16).padStart(2, "0")}`;
|
||||
return `Expected a 65-byte uncompressed P-256 public key beginning with 0x04; received ${this.byteLength} bytes with ${prefix}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopStoredPublicKeyMismatchError extends Schema.TaggedErrorClass<DpopStoredPublicKeyMismatchError>()(
|
||||
"DpopStoredPublicKeyMismatchError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Stored DPoP private and public key material do not match.";
|
||||
}
|
||||
function cloudDpopError(message: string) {
|
||||
return (cause: unknown) => new CloudDpopError({ message, cause });
|
||||
}
|
||||
|
||||
const DpopPrivateJwkSchema = Schema.Struct({
|
||||
@@ -136,28 +97,29 @@ function base64UrlToBytes(value: string): Uint8Array {
|
||||
return Result.getOrThrow(Encoding.decodeBase64Url(value));
|
||||
}
|
||||
|
||||
function sha256Digest(data: Uint8Array): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
function sha256Digest(
|
||||
data: Uint8Array,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "hash-signing-input", cause })),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function secureRandomBytes(
|
||||
byteCount: number,
|
||||
message: string,
|
||||
): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {
|
||||
return Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "generate-key-randomness", cause })),
|
||||
Effect.mapError(cloudDpopError(message)),
|
||||
);
|
||||
}
|
||||
|
||||
function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {
|
||||
if (publicKey.length !== 65 || publicKey[0] !== 0x04) {
|
||||
throw new DpopPublicKeyFormatError({
|
||||
byteLength: publicKey.length,
|
||||
...(publicKey[0] === undefined ? {} : { firstByte: publicKey[0] }),
|
||||
});
|
||||
throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");
|
||||
}
|
||||
return {
|
||||
kty: "EC",
|
||||
@@ -182,11 +144,14 @@ export function generateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
let privateKey: Uint8Array;
|
||||
do {
|
||||
privateKey = yield* secureRandomBytes(p256.CURVE.nByteLength);
|
||||
privateKey = yield* secureRandomBytes(
|
||||
p256.CURVE.nByteLength,
|
||||
"Could not generate DPoP key pair randomness.",
|
||||
);
|
||||
} while (!p256.utils.isValidPrivateKey(privateKey));
|
||||
const publicJwk = yield* Effect.try({
|
||||
try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),
|
||||
catch: (cause) => new CloudDpopError({ operation: "derive-public-key", cause }),
|
||||
catch: cloudDpopError("Generated DPoP public key is invalid."),
|
||||
});
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
return {
|
||||
@@ -205,11 +170,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
return Effect.gen(function* () {
|
||||
const stored = yield* Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),
|
||||
catch: (cause) => new CloudDpopError({ operation: "read-key", cause }),
|
||||
catch: cloudDpopError("Could not read the DPoP proof key."),
|
||||
});
|
||||
if (stored) {
|
||||
const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "decode-key", cause })),
|
||||
Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),
|
||||
);
|
||||
const restored = yield* Effect.try({
|
||||
try: () => {
|
||||
@@ -218,11 +183,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
p256.getPublicKey(privateKey, false),
|
||||
);
|
||||
if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {
|
||||
throw new DpopStoredPublicKeyMismatchError();
|
||||
throw new Error("Stored DPoP key does not match its public key.");
|
||||
}
|
||||
return { privateJwk: storedPrivateJwk, publicJwk };
|
||||
},
|
||||
catch: (cause) => new CloudDpopError({ operation: "validate-key", cause }),
|
||||
catch: cloudDpopError("Stored DPoP proof key is invalid."),
|
||||
});
|
||||
return {
|
||||
...restored,
|
||||
@@ -231,11 +196,11 @@ export function loadOrCreateDpopProofKeyPair(): Effect.Effect<
|
||||
}
|
||||
const generated = yield* generateDpopProofKeyPair();
|
||||
const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "encode-key", cause })),
|
||||
Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),
|
||||
);
|
||||
yield* Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),
|
||||
catch: (cause) => new CloudDpopError({ operation: "store-key", cause }),
|
||||
catch: cloudDpopError("Could not store the DPoP proof key."),
|
||||
});
|
||||
return generated;
|
||||
});
|
||||
@@ -245,7 +210,7 @@ function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {
|
||||
const normalized = normalizeDpopHtu(url);
|
||||
return normalized
|
||||
? Effect.succeed(normalized)
|
||||
: Effect.fail(new CloudDpopError({ operation: "normalize-proof-url" }));
|
||||
: Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));
|
||||
}
|
||||
|
||||
export function createDpopProof(input: {
|
||||
@@ -262,12 +227,12 @@ export function createDpopProof(input: {
|
||||
const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());
|
||||
const privateKey = yield* Effect.try({
|
||||
try: () => base64UrlToBytes(keyPair.privateJwk.d),
|
||||
catch: (cause) => new CloudDpopError({ operation: "import-private-key", cause }),
|
||||
catch: cloudDpopError("Could not import DPoP private key."),
|
||||
});
|
||||
const nowMs = yield* Clock.currentTimeMillis;
|
||||
const jti = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "generate-proof-id", cause })),
|
||||
Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),
|
||||
);
|
||||
const htu = yield* normalizeHtu(input.url);
|
||||
const header = yield* encodeDpopJwtHeaderJson({
|
||||
@@ -276,7 +241,7 @@ export function createDpopProof(input: {
|
||||
jwk: keyPair.publicJwk,
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "encode-proof-header", cause })),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),
|
||||
);
|
||||
const ath = input.accessToken ? computeDpopAccessTokenHash(input.accessToken) : null;
|
||||
const payload = yield* encodeDpopJwtPayloadJson({
|
||||
@@ -287,14 +252,15 @@ export function createDpopProof(input: {
|
||||
...(ath ? { ath } : {}),
|
||||
}).pipe(
|
||||
Effect.map(Encoding.encodeBase64Url),
|
||||
Effect.mapError((cause) => new CloudDpopError({ operation: "encode-proof-payload", cause })),
|
||||
Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),
|
||||
);
|
||||
const signatureInputHash = yield* sha256Digest(
|
||||
new TextEncoder().encode(`${header}.${payload}`),
|
||||
"Could not hash DPoP signing input.",
|
||||
);
|
||||
const signature = yield* Effect.try({
|
||||
try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),
|
||||
catch: (cause) => new CloudDpopError({ operation: "sign-proof", cause }),
|
||||
catch: cloudDpopError("Could not sign DPoP proof."),
|
||||
});
|
||||
return {
|
||||
proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as References from "effect/References";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
@@ -18,10 +16,7 @@ vi.mock("expo-secure-store", () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
isManagedRelayTokenStoreError,
|
||||
managedRelayAccessTokenStore,
|
||||
} from "./managedRelayTokenStore";
|
||||
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
|
||||
|
||||
it.effect("round-trips and clears persisted managed relay access tokens", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -50,21 +45,7 @@ it.effect("falls back to an empty cache when persisted data is invalid", () =>
|
||||
Effect.gen(function* () {
|
||||
secureStore.clear();
|
||||
secureStore.set("t3code.cloud.relay-access-tokens", "not-json");
|
||||
const annotations: Array<Record<string, unknown>> = [];
|
||||
const logger = Logger.make(({ fiber }) => {
|
||||
annotations.push(fiber.getRef(References.CurrentLogAnnotations));
|
||||
});
|
||||
|
||||
expect(
|
||||
yield* managedRelayAccessTokenStore.load.pipe(
|
||||
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(annotations).toHaveLength(1);
|
||||
expect(isManagedRelayTokenStoreError(annotations[0]?.error)).toBe(true);
|
||||
expect(annotations[0]?.error).toMatchObject({
|
||||
operation: "decode-cache",
|
||||
cause: expect.anything(),
|
||||
});
|
||||
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
|
||||
}),
|
||||
);
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
@@ -30,48 +31,36 @@ const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
|
||||
);
|
||||
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
|
||||
|
||||
export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(
|
||||
"ManagedRelayTokenStoreError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"read-cache",
|
||||
"decode-cache",
|
||||
"encode-cache",
|
||||
"write-cache",
|
||||
"clear-cache",
|
||||
]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Managed relay token store operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export const isManagedRelayTokenStoreError = Schema.is(ManagedRelayTokenStoreError);
|
||||
const storeError =
|
||||
(message: string) =>
|
||||
(cause: unknown): ManagedRelayTokenStoreError =>
|
||||
new ManagedRelayTokenStoreError({ message, cause });
|
||||
|
||||
function logStoreFailure(error: ManagedRelayTokenStoreError) {
|
||||
return Effect.logWarning(error.message).pipe(
|
||||
Effect.annotateLogs({
|
||||
error,
|
||||
errorTag: error._tag,
|
||||
operation: error.operation,
|
||||
}),
|
||||
);
|
||||
function logStoreFailure(operation: string) {
|
||||
return (error: ManagedRelayTokenStoreError) =>
|
||||
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
|
||||
Effect.annotateLogs({
|
||||
errorTag: error._tag,
|
||||
message: error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const loadManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: (cause) => new ManagedRelayTokenStoreError({ operation: "read-cache", cause }),
|
||||
catch: storeError("Could not read persisted relay access tokens."),
|
||||
}).pipe(
|
||||
Effect.flatMap((encoded) =>
|
||||
encoded === null
|
||||
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
|
||||
: decodeManagedRelayAccessTokenCache(encoded).pipe(
|
||||
Effect.map((cache) => cache.entries),
|
||||
Effect.mapError(
|
||||
(cause) => new ManagedRelayTokenStoreError({ operation: "decode-cache", cause }),
|
||||
),
|
||||
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -83,33 +72,34 @@ const saveManagedRelayAccessTokens = (
|
||||
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
|
||||
entries,
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ManagedRelayTokenStoreError({ operation: "encode-cache", cause }),
|
||||
),
|
||||
Effect.mapError(storeError("Could not encode relay access tokens.")),
|
||||
Effect.flatMap((encoded) =>
|
||||
Effect.tryPromise({
|
||||
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
|
||||
catch: (cause) => new ManagedRelayTokenStoreError({ operation: "write-cache", cause }),
|
||||
catch: storeError("Could not persist relay access tokens."),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const clearManagedRelayAccessTokens = Effect.tryPromise({
|
||||
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
|
||||
catch: (cause) => new ManagedRelayTokenStoreError({ operation: "clear-cache", cause }),
|
||||
catch: storeError("Could not clear persisted relay access tokens."),
|
||||
});
|
||||
|
||||
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
|
||||
load: loadManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure),
|
||||
Effect.tapError(logStoreFailure("load")),
|
||||
Effect.orElseSucceed(() => []),
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.load"),
|
||||
),
|
||||
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
|
||||
saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),
|
||||
saveManagedRelayAccessTokens(entries).pipe(
|
||||
Effect.tapError(logStoreFailure("save")),
|
||||
Effect.ignore,
|
||||
),
|
||||
),
|
||||
clear: clearManagedRelayAccessTokens.pipe(
|
||||
Effect.tapError(logStoreFailure),
|
||||
Effect.tapError(logStoreFailure("clear")),
|
||||
Effect.ignore,
|
||||
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
|
||||
),
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createSourceHighlightAtomFamily,
|
||||
isSourceHighlightError,
|
||||
type SourceHighlightTokens,
|
||||
} from "./sourceHighlightingState";
|
||||
|
||||
@@ -101,8 +104,9 @@ describe("sourceHighlightingState", () => {
|
||||
});
|
||||
|
||||
it("exposes highlighter errors as a failed async result", async () => {
|
||||
const cause = new Error("highlight failed");
|
||||
const highlight = vi.fn(async () => {
|
||||
throw new Error("highlight failed");
|
||||
throw cause;
|
||||
});
|
||||
const sourceHighlightAtom = createSourceHighlightAtomFamily({ highlight });
|
||||
const registry = AtomRegistry.make();
|
||||
@@ -113,8 +117,17 @@ describe("sourceHighlightingState", () => {
|
||||
});
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
|
||||
const result = registry.get(atom);
|
||||
const error = AsyncResult.isFailure(result)
|
||||
? Option.getOrUndefined(Cause.findErrorOption(result.cause))
|
||||
: undefined;
|
||||
|
||||
expect(isSourceHighlightError(error)).toBe(true);
|
||||
expect(error).toMatchObject({
|
||||
path: "src/example.ts",
|
||||
theme: "light",
|
||||
cause,
|
||||
});
|
||||
|
||||
unmount();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -22,9 +23,20 @@ type SourceHighlighter = (input: SourceHighlightInput) => Promise<SourceHighligh
|
||||
|
||||
class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
|
||||
|
||||
class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
export class SourceHighlightError extends Schema.TaggedErrorClass<SourceHighlightError>()(
|
||||
"SourceHighlightError",
|
||||
{
|
||||
path: Schema.String,
|
||||
theme: Schema.Literals(["light", "dark"]),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to highlight ${this.path} with the ${this.theme} theme.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isSourceHighlightError = Schema.is(SourceHighlightError);
|
||||
|
||||
export function createSourceHighlightAtomFamily(options?: {
|
||||
readonly highlight?: SourceHighlighter;
|
||||
@@ -36,7 +48,8 @@ export function createSourceHighlightAtomFamily(options?: {
|
||||
Atom.make(
|
||||
Effect.tryPromise({
|
||||
try: () => highlight(request),
|
||||
catch: (cause) => new SourceHighlightError({ cause }),
|
||||
catch: (cause) =>
|
||||
new SourceHighlightError({ path: request.path, theme: request.theme, cause }),
|
||||
}),
|
||||
).pipe(
|
||||
Atom.setIdleTTL(idleTtlMs),
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { createWorkspaceFileImageAtomFamily } from "./workspace-file-image-cache";
|
||||
import {
|
||||
createWorkspaceFileImageAtomFamily,
|
||||
isWorkspaceImagePrefetchError,
|
||||
} from "./workspace-file-image-cache";
|
||||
|
||||
describe("workspaceFileImageAtom", () => {
|
||||
it("reuses a prefetched image across route remounts", async () => {
|
||||
@@ -48,14 +53,47 @@ describe("workspaceFileImageAtom", () => {
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("exposes prefetch failures", async () => {
|
||||
it("exposes a false native prefetch result", async () => {
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({ prefetch: async () => false });
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom("https://example.test/missing.png");
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(AsyncResult.isFailure(registry.get(atom))).toBe(true);
|
||||
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
|
||||
const result = registry.get(atom);
|
||||
const error = AsyncResult.isFailure(result)
|
||||
? Option.getOrUndefined(Cause.findErrorOption(result.cause))
|
||||
: undefined;
|
||||
|
||||
expect(isWorkspaceImagePrefetchError(error)).toBe(true);
|
||||
expect(error).toMatchObject({ uri: "https://example.test/missing.png" });
|
||||
expect(error).not.toHaveProperty("cause");
|
||||
|
||||
unmount();
|
||||
registry.dispose();
|
||||
});
|
||||
|
||||
it("preserves thrown prefetch causes", async () => {
|
||||
const cause = new Error("native image prefetch failed");
|
||||
const imageAtom = createWorkspaceFileImageAtomFamily({
|
||||
prefetch: async () => {
|
||||
throw cause;
|
||||
},
|
||||
});
|
||||
const registry = AtomRegistry.make();
|
||||
const atom = imageAtom("https://example.test/missing.png");
|
||||
const unmount = registry.mount(atom);
|
||||
|
||||
await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));
|
||||
const result = registry.get(atom);
|
||||
const error = AsyncResult.isFailure(result)
|
||||
? Option.getOrUndefined(Cause.findErrorOption(result.cause))
|
||||
: undefined;
|
||||
|
||||
expect(isWorkspaceImagePrefetchError(error)).toBe(true);
|
||||
expect(error).toMatchObject({
|
||||
uri: "https://example.test/missing.png",
|
||||
cause,
|
||||
});
|
||||
|
||||
unmount();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
const WORKSPACE_IMAGE_IDLE_TTL_MS = 30 * 60_000;
|
||||
@@ -8,10 +9,19 @@ type ImagePrefetch = (uri: string) => Promise<boolean>;
|
||||
|
||||
class WorkspaceImageCacheKey extends Data.Class<{ readonly uri: string }> {}
|
||||
|
||||
export class WorkspaceImagePrefetchError extends Data.TaggedError("WorkspaceImagePrefetchError")<{
|
||||
readonly cause?: unknown;
|
||||
readonly uri: string;
|
||||
}> {}
|
||||
export class WorkspaceImagePrefetchError extends Schema.TaggedErrorClass<WorkspaceImagePrefetchError>()(
|
||||
"WorkspaceImagePrefetchError",
|
||||
{
|
||||
uri: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to prefetch workspace image ${this.uri}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isWorkspaceImagePrefetchError = Schema.is(WorkspaceImagePrefetchError);
|
||||
|
||||
async function prefetchWithNativeImage(uri: string): Promise<boolean> {
|
||||
const { Image } = await import("react-native");
|
||||
@@ -35,7 +45,7 @@ export function createWorkspaceFileImageAtomFamily(options?: {
|
||||
return key.uri;
|
||||
},
|
||||
catch: (cause) =>
|
||||
cause instanceof WorkspaceImagePrefetchError
|
||||
isWorkspaceImagePrefetchError(cause)
|
||||
? cause
|
||||
: new WorkspaceImagePrefetchError({ uri: key.uri, cause }),
|
||||
}),
|
||||
|
||||
@@ -4,31 +4,9 @@ import * as Effect from "effect/Effect";
|
||||
import { decodeJwt } from "jose";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
BrowserDpopError,
|
||||
type BrowserDpopKey,
|
||||
browserCryptoLayer,
|
||||
createBrowserDpopProof,
|
||||
generateBrowserDpopKey,
|
||||
} from "./dpop";
|
||||
import { browserCryptoLayer, createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";
|
||||
|
||||
describe("browser DPoP proofs", () => {
|
||||
it.effect("reports URL normalization failures structurally with their cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* createBrowserDpopProof({
|
||||
method: "POST",
|
||||
url: "not a URL",
|
||||
proofKey: {} as BrowserDpopKey,
|
||||
}).pipe(Effect.provide(browserCryptoLayer), Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(BrowserDpopError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "normalize-proof-url",
|
||||
cause: expect.any(TypeError),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("signs relay resource proofs with an access-token hash", () =>
|
||||
Effect.gen(function* () {
|
||||
vi.stubGlobal("indexedDB", undefined);
|
||||
|
||||
+21
-54
@@ -4,6 +4,7 @@ import {
|
||||
DpopPublicJwk,
|
||||
} from "@t3tools/shared/dpop";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -15,31 +16,10 @@ export interface BrowserDpopKey {
|
||||
readonly thumbprint: string;
|
||||
}
|
||||
|
||||
export class BrowserDpopError extends Schema.TaggedErrorClass<BrowserDpopError>()(
|
||||
"BrowserDpopError",
|
||||
{
|
||||
operation: Schema.Literals([
|
||||
"open-key-storage",
|
||||
"read-key",
|
||||
"write-key",
|
||||
"generate-key",
|
||||
"export-private-key",
|
||||
"export-public-key",
|
||||
"decode-public-key",
|
||||
"import-private-key",
|
||||
"normalize-proof-url",
|
||||
"generate-proof-id",
|
||||
"sign-proof",
|
||||
]),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Browser DPoP operation "${this.operation}" failed.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isBrowserDpopError = Schema.is(BrowserDpopError);
|
||||
export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const DPOP_DATABASE_NAME = "t3code:cloud-auth";
|
||||
const DPOP_DATABASE_VERSION = 1;
|
||||
@@ -60,17 +40,16 @@ export const browserCryptoLayer = Layer.succeed(
|
||||
}),
|
||||
);
|
||||
|
||||
function dpopError(message: string, cause?: unknown) {
|
||||
return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });
|
||||
}
|
||||
|
||||
function openDpopDatabase(): Effect.Effect<IDBDatabase, BrowserDpopError> {
|
||||
return Effect.callback<IDBDatabase, BrowserDpopError>((resume) => {
|
||||
const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION);
|
||||
request.addEventListener("error", () =>
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BrowserDpopError({
|
||||
operation: "open-key-storage",
|
||||
...(request.error === null ? {} : { cause: request.error }),
|
||||
}),
|
||||
),
|
||||
Effect.fail(dpopError("Could not open DPoP key storage.", request.error ?? undefined)),
|
||||
),
|
||||
);
|
||||
request.addEventListener("upgradeneeded", () => {
|
||||
@@ -95,14 +74,7 @@ export function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null,
|
||||
.objectStore(DPOP_KEY_STORE_NAME)
|
||||
.get(DPOP_KEY_ID);
|
||||
request.addEventListener("error", () =>
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BrowserDpopError({
|
||||
operation: "read-key",
|
||||
...(request.error === null ? {} : { cause: request.error }),
|
||||
}),
|
||||
),
|
||||
),
|
||||
resume(Effect.fail(dpopError("Could not read DPoP key.", request.error ?? undefined))),
|
||||
);
|
||||
request.addEventListener("success", () =>
|
||||
resume(Effect.succeed((request.result as BrowserDpopKey | undefined) ?? null)),
|
||||
@@ -125,12 +97,7 @@ export function writeStoredBrowserDpopKey(
|
||||
const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite");
|
||||
transaction.addEventListener("error", () =>
|
||||
resume(
|
||||
Effect.fail(
|
||||
new BrowserDpopError({
|
||||
operation: "write-key",
|
||||
...(transaction.error === null ? {} : { cause: transaction.error }),
|
||||
}),
|
||||
),
|
||||
Effect.fail(dpopError("Could not write DPoP key.", transaction.error ?? undefined)),
|
||||
),
|
||||
);
|
||||
transaction.addEventListener("complete", () => resume(Effect.void));
|
||||
@@ -147,26 +114,26 @@ export const generateBrowserDpopKey = Effect.gen(function* () {
|
||||
"sign",
|
||||
"verify",
|
||||
]) as Promise<CryptoKeyPair>,
|
||||
catch: (cause) => new BrowserDpopError({ operation: "generate-key", cause }),
|
||||
catch: (cause) => dpopError("Could not generate DPoP proof key.", cause),
|
||||
});
|
||||
const privateJwk = yield* Effect.tryPromise({
|
||||
try: () => crypto.subtle.exportKey("jwk", generated.privateKey),
|
||||
catch: (cause) => new BrowserDpopError({ operation: "export-private-key", cause }),
|
||||
catch: (cause) => dpopError("Could not export DPoP private key.", cause),
|
||||
});
|
||||
const publicJwk = yield* Effect.tryPromise({
|
||||
try: () => crypto.subtle.exportKey("jwk", generated.publicKey),
|
||||
catch: (cause) => new BrowserDpopError({ operation: "export-public-key", cause }),
|
||||
catch: (cause) => dpopError("Could not export DPoP public key.", cause),
|
||||
}).pipe(
|
||||
Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),
|
||||
Effect.mapError((cause) =>
|
||||
isBrowserDpopError(cause)
|
||||
cause instanceof BrowserDpopError
|
||||
? cause
|
||||
: new BrowserDpopError({ operation: "decode-public-key", cause }),
|
||||
: dpopError("Generated DPoP public key is invalid.", cause),
|
||||
),
|
||||
);
|
||||
const privateKey = yield* Effect.tryPromise({
|
||||
try: () => importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise<CryptoKey>,
|
||||
catch: (cause) => new BrowserDpopError({ operation: "import-private-key", cause }),
|
||||
catch: (cause) => dpopError("Could not import DPoP private key.", cause),
|
||||
});
|
||||
return {
|
||||
privateKey,
|
||||
@@ -188,13 +155,13 @@ export function createBrowserDpopProof(input: {
|
||||
return Effect.gen(function* () {
|
||||
const normalizedUrl = yield* Effect.try({
|
||||
try: () => new URL(input.url),
|
||||
catch: (cause) => new BrowserDpopError({ operation: "normalize-proof-url", cause }),
|
||||
catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),
|
||||
});
|
||||
normalizedUrl.search = "";
|
||||
normalizedUrl.hash = "";
|
||||
const jti = yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError((cause) => new BrowserDpopError({ operation: "generate-proof-id", cause })),
|
||||
Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),
|
||||
);
|
||||
const proof = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
@@ -211,7 +178,7 @@ export function createBrowserDpopProof(input: {
|
||||
})
|
||||
.setIssuedAt()
|
||||
.sign(input.proofKey.privateKey),
|
||||
catch: (cause) => new BrowserDpopError({ operation: "sign-proof", cause }),
|
||||
catch: (cause) => dpopError("Could not sign DPoP proof.", cause),
|
||||
});
|
||||
return { proof, thumbprint: input.proofKey.thumbprint };
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user