Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// apps/mobile/modules/t3-native-controls/ios/T3DpopKeys.swift
// generates, checks & signs w/ P-256 keys for DPoP proofs
import CryptoKit
import Foundation

/// P-256 keys for DPoP proofs, as 32-byte private scalars and 65-byte uncompressed public points.
enum T3DpopKeys {
/// The private scalar followed by the public point.
static func generate() -> Data {
let key = P256.Signing.PrivateKey()
return key.rawRepresentation + key.publicKey.x963Representation
}

static func matches(privateKey: Data, publicKey: Data) throws -> Bool {
try P256.Signing.PrivateKey(rawRepresentation: privateKey).publicKey.x963Representation == publicKey
}

/// ES256 over the JWS signing input, as the raw `r‖s` pair JWS uses.
static func sign(privateKey: Data, signingInput: Data) throws -> Data {
try P256.Signing.PrivateKey(rawRepresentation: privateKey).signature(for: signingInput).rawRepresentation
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ public final class T3NativeControlsModule: Module {
ViewName("ScrollEdgeBleed")
}

AsyncFunction("generateDpopKey") { T3DpopKeys.generate() }

AsyncFunction("dpopKeyMatches") { (privateKey: Data, publicKey: Data) in
try T3DpopKeys.matches(privateKey: privateKey, publicKey: publicKey)
}

AsyncFunction("signDpop") { (privateKey: Data, signingInput: Data) in
try T3DpopKeys.sign(privateKey: privateKey, signingInput: signingInput)
}

AsyncFunction("presentVideo") { (url: URL, title: String, sourceIdentifier: String, identifier: String, promise: Promise) in
try self.presentVideo(
url: url,
Expand Down
109 changes: 109 additions & 0 deletions apps/mobile/src/connection/dpop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// apps/mobile/src/connection/dpop.ts
// keeps this install's DPoP key in the keychain & signs w/ native P-256
import { DpopProof } from "@t3tools/client-runtime/authorization";
import { DpopPublicJwk } from "@t3tools/shared/dpopCommon";
import * as Effect from "effect/Effect";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";

const DPOP_KEY_STORAGE_KEY = "456code.connection.dpop-proof-key";
const DEVICE_ONLY = { keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY };

const DpopPrivateJwkJson = Schema.fromJsonString(
Schema.Struct({ ...DpopPublicJwk.fields, d: Schema.String }),
);
const decodePrivateJwk = Schema.decodeUnknownEffect(DpopPrivateJwkJson);
const encodePrivateJwk = Schema.encodeEffect(DpopPrivateJwkJson);

interface NativeDpopKeys {
/** A 32-byte private scalar followed by its 65-byte uncompressed public point. */
generateDpopKey(): Promise<Uint8Array>;
dpopKeyMatches(privateKey: Uint8Array, publicKey: Uint8Array): Promise<boolean>;
/** ES256 over the signing input, as the raw 64-byte `r||s` pair. */
signDpop(privateKey: Uint8Array, signingInput: Uint8Array): Promise<Uint8Array>;
}

// imported lazily since loading `expo` at module scope breaks node tests
const nativeDpopKeys = async () =>
(await import("expo")).requireNativeModule<NativeDpopKeys>("T3NativeControls");

const dpopError = (message: string) => (cause: unknown) =>
new DpopProof.DpopProofError({ message, cause });

const base64UrlToBytes = (value: string) => Result.getOrThrow(Base64Url.decode(value));

function uncompressedPublicKey(jwk: DpopPublicJwk): Uint8Array {
const x = base64UrlToBytes(jwk.x);
const y = base64UrlToBytes(jwk.y);
if (x.length !== 32 || y.length !== 32) {
throw new Error("DPoP key coordinate is not 32 bytes.");
}
const publicKey = new Uint8Array(65);
publicKey[0] = 0x04;
publicKey.set(x, 1);
publicKey.set(y, 33);
return publicKey;
}

const generateKey = Effect.fn("mobile.dpop.generateKey")(function* () {
const generated = yield* Effect.tryPromise({
try: async () => (await nativeDpopKeys()).generateDpopKey(),
catch: dpopError("Could not generate the device key."),
});
const publicKey = generated.slice(32);
if (generated.length !== 97 || publicKey[0] !== 0x04) {
return yield* new DpopProof.DpopProofError({ message: "Generated device key is invalid." });
}
const jwk = {
kty: "EC" as const,
crv: "P-256" as const,
x: Base64Url.encode(publicKey.slice(1, 33)),
y: Base64Url.encode(publicKey.slice(33, 65)),
d: Base64Url.encode(generated.slice(0, 32)),
};
const encoded = yield* encodePrivateJwk(jwk).pipe(
Effect.mapError(dpopError("Could not encode the device key.")),
);
yield* Effect.tryPromise({
try: () => SecureStore.setItemAsync(DPOP_KEY_STORAGE_KEY, encoded, DEVICE_ONLY),
catch: dpopError("Could not store the device key."),
});
return jwk;
});

const loadStoredKey = Effect.fn("mobile.dpop.loadStoredKey")(function* (stored: string) {
const jwk = yield* decodePrivateJwk(stored).pipe(
Effect.mapError(dpopError("Stored device key is invalid.")),
);
const matches = yield* Effect.tryPromise({
try: async () =>
(await nativeDpopKeys()).dpopKeyMatches(base64UrlToBytes(jwk.d), uncompressedPublicKey(jwk)),
catch: dpopError("Stored device key is invalid."),
});
if (!matches) {
return yield* new DpopProof.DpopProofError({ message: "Stored device key is invalid." });
}
return jwk;
});

export const loadOrCreateProofKey = Effect.fn("mobile.dpop.loadOrCreateProofKey")(function* () {
const stored = yield* Effect.tryPromise({
try: () => SecureStore.getItemAsync(DPOP_KEY_STORAGE_KEY, DEVICE_ONLY),
catch: dpopError("Could not read the device key."),
});
const { d, ...publicJwk } = stored ? yield* loadStoredKey(stored) : yield* generateKey();
const privateKey = yield* Effect.try({
try: () => base64UrlToBytes(d),
catch: dpopError("Could not read the device key."),
});
return {
publicJwk,
sign: (signingInput) =>
Effect.tryPromise({
try: async () => (await nativeDpopKeys()).signDpop(privateKey, signingInput),
catch: dpopError("Could not sign the DPoP proof."),
}),
} satisfies DpopProof.DpopProofKey;
});
8 changes: 8 additions & 0 deletions apps/mobile/src/connection/platform.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// apps/mobile/src/connection/platform.ts
// supplies native client connectivity and authentication capabilities
import { DpopProof } from "@t3tools/client-runtime/authorization";
import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform";
import { Connectivity, Wakeups } from "@t3tools/client-runtime/connection";
import * as Clock from "effect/Clock";
Expand All @@ -13,8 +14,10 @@ import * as Network from "expo-network";
import { AppState } from "react-native";

import { authClientMetadata } from "../lib/authClientMetadata";
import * as ExpoCrypto from "../lib/expoCrypto";
import * as Runtime from "../lib/runtime";
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
import { loadOrCreateProofKey } from "./dpop";
import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup";
import * as ConnectionStorage from "./storage";

Expand Down Expand Up @@ -161,13 +164,17 @@ const layerPlatformConnectionSource = Layer.succeed(

const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer));
const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer));
const layerDpopSigner = DpopProof.layerSigner(loadOrCreateProofKey()).pipe(
Layer.provide(ExpoCrypto.layer),
);

type ConnectionPlatformLayerSource =
| typeof layerProvidedConnectionStorage
| typeof Runtime.layer
| typeof layerConnectivity
| typeof layerWakeups
| typeof layerProvidedCapabilities
| typeof layerDpopSigner
| typeof layerPlatformConnectionSource
| typeof EnvironmentOwnedDataCleanup.layer;

Expand All @@ -181,6 +188,7 @@ export const layer: Layer.Layer<
layerConnectivity,
layerWakeups,
layerProvidedCapabilities,
layerDpopSigner,
layerPlatformConnectionSource,
EnvironmentOwnedDataCleanup.layer,
);
2 changes: 1 addition & 1 deletion apps/mobile/src/state/remote-environment-projections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function createRemoteEnvironmentProjectionAtoms(input: {
displayUrl,
httpBaseUrl,
wsBaseUrl,
bearerToken: authorization?.token ?? null,
bearerToken: authorization?._tag === "Bearer" ? authorization.token : null,
};
return previous;
}).pipe(Atom.withLabel(`mobile:saved-connection:${environmentId}`));
Expand Down
94 changes: 94 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as TestClock from "effect/testing/TestClock";

import * as ServerConfig from "../config.ts";
import { makeDpopKey } from "./dpop.testkit.ts";
Expand Down Expand Up @@ -300,6 +301,99 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
);

it.effect("renews a pairing-link DPoP session in place while its device keeps using it", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const sessions = yield* SessionStore.SessionStore;
const admin = yield* serverAuth.issueSession({ label: "Owner" });
const key = makeDpopKey();
const other = makeDpopKey();
const pair = (proofKeyThumbprint?: string) =>
serverAuth
.issuePairingCredential({ scopes: ["orchestration:read"] })
.pipe(
Effect.flatMap((pairing) =>
serverAuth.exchangeBootstrapCredentialForAccessToken(
pairing.credential,
undefined,
requestMetadata,
proofKeyThumbprint ? { proofKeyThumbprint } : undefined,
),
),
);
const sessionExpiry = (sessionId: string) =>
serverAuth
.listClientSessions(admin.sessionId)
.pipe(
Effect.map(
(sessions) =>
sessions.find((session) => session.sessionId === sessionId)?.expiresAt
.epochMilliseconds,
),
);

const paired = yield* pair(key.thumbprint);
expect(paired.expires_in).toBe(60 * 60);
const { sessionId } = yield* sessions.verify(paired.access_token);
const pairedAt = (yield* DateTime.now).epochMilliseconds;
// Listed for the whole renewal window, so an idle device can still be revoked.
expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000);

yield* TestClock.adjust("20 days");
const replay = new EnvironmentAuth.ServerAuthInvalidCredentialError({
dpopFailureReason: "replay",
});
const rejected = yield* serverAuth
.renewAccessToken(paired.access_token, key.thumbprint, Effect.fail(replay))
.pipe(Effect.flip);
expect(rejected).toBe(replay);
expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 30 * 24 * 60 * 60 * 1000);

const renewed = yield* serverAuth.renewAccessToken(
paired.access_token,
key.thumbprint,
Effect.void,
);
expect(renewed.scope).toBe("orchestration:read");
const verified = yield* sessions.verify(renewed.access_token);
expect(verified.sessionId).toBe(sessionId);
expect(yield* sessionExpiry(sessionId)).toBe(pairedAt + 50 * 24 * 60 * 60 * 1000);

const refused = (token: string, thumbprint: string) =>
serverAuth
.renewAccessToken(
token,
thumbprint,
Effect.die("Invalid credentials cannot consume a proof."),
)
.pipe(
Effect.flip,
Effect.map((error) => error._tag),
);
expect(yield* refused(renewed.access_token, other.thumbprint)).toBe(
"ServerAuthInvalidCredentialError",
);
// Bearer sessions keep their fixed lifetimes.
const bearer = yield* pair();
expect(yield* refused(bearer.access_token, key.thumbprint)).toBe(
"ServerAuthInvalidCredentialError",
);

// Inside the renewed window, so only the revocation can refuse it.
expect(yield* serverAuth.revokeClientSession(admin.sessionId, sessionId)).toBe(true);
expect(yield* refused(renewed.access_token, key.thumbprint)).toBe(
"ServerAuthInvalidCredentialError",
);

// Idle past the window, the device pairs again.
const idle = yield* pair(key.thumbprint);
yield* TestClock.adjust("31 days");
expect(yield* refused(idle.access_token, key.thumbprint)).toBe(
"ServerAuthInvalidCredentialError",
);
}).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
);

it.effect("preserves pairing grants after rejecting scopes they do not grant", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
Expand Down
Loading
Loading