mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
feat(integrations): per-user Polar and Oura OAuth credentials
Polar and Oura resolved their OAuth client id/secret from the server
environment only, forcing every user on a deploy to share one app. Both
now read per-user BYO keys first, falling back to the shared env app when
unset, mirroring the WHOOP and Fitbit model.
- Add DB-first-then-env resolvers in src/lib/{polar,oura}/credentials.ts,
encrypting the client id/secret at rest on User.
- Repoint the connect, callback, status routes and the Oura refresh path
to the user-scoped resolver.
- Add /api/{polar,oura}/credentials (GET/PUT/DELETE) with Zod-validated
input and userId narrowed from the session.
- Render an optional 'your OAuth app credentials' form on the Polar and
Oura cards; the status read exposes hasOwnCredentials for the saved
placeholder. Existing env-only deploys keep working unchanged.
- Cover both resolvers (DB hit, env fallback, no creds) and the card form
with unit tests; add the new strings across all six locales.
This commit is contained in:
1 parent
111fa7a323
commit
38c7604ce4
28 files changed
+856
-76
No files matched your search
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const findUnique = vi.fn();
|
||||
const getOuraCredentials = vi.fn();
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { user: { findUnique: (...args: unknown[]) => findUnique(...args) } },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/crypto", () => ({
|
||||
decrypt: (cipher: string) => `dec(${cipher})`,
|
||||
encrypt: (plain: string) => `enc(${plain})`,
|
||||
}));
|
||||
|
||||
// The env fallback lives in ./client; stub it so the precedence is observable.
|
||||
vi.mock("../client", () => ({
|
||||
getOuraCredentials: () => getOuraCredentials(),
|
||||
}));
|
||||
|
||||
import { getOuraClientCredentials } from "../credentials";
|
||||
|
||||
describe("getOuraClientCredentials — DB-first then env", () => {
|
||||
beforeEach(() => {
|
||||
findUnique.mockReset();
|
||||
getOuraCredentials.mockReset();
|
||||
});
|
||||
|
||||
it("returns the per-user BYO client id/secret when both columns are set", async () => {
|
||||
findUnique.mockResolvedValue({
|
||||
ouraClientIdEncrypted: "enc-id",
|
||||
ouraClientSecretEncrypted: "enc-secret",
|
||||
});
|
||||
const creds = await getOuraClientCredentials("user-1");
|
||||
expect(creds).toEqual({
|
||||
clientId: "dec(enc-id)",
|
||||
clientSecret: "dec(enc-secret)",
|
||||
});
|
||||
expect(getOuraCredentials).not.toHaveBeenCalled();
|
||||
expect(findUnique).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
select: {
|
||||
ouraClientIdEncrypted: true,
|
||||
ouraClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the shared env app when the user has no BYO pair", async () => {
|
||||
findUnique.mockResolvedValue({
|
||||
ouraClientIdEncrypted: null,
|
||||
ouraClientSecretEncrypted: null,
|
||||
});
|
||||
getOuraCredentials.mockReturnValue({
|
||||
clientId: "env-id",
|
||||
clientSecret: "env-secret",
|
||||
});
|
||||
const creds = await getOuraClientCredentials("user-1");
|
||||
expect(creds).toEqual({ clientId: "env-id", clientSecret: "env-secret" });
|
||||
expect(getOuraCredentials).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("falls back to env when only one half of the BYO pair is present", async () => {
|
||||
findUnique.mockResolvedValue({
|
||||
ouraClientIdEncrypted: null,
|
||||
ouraClientSecretEncrypted: "enc-secret",
|
||||
});
|
||||
getOuraCredentials.mockReturnValue({
|
||||
clientId: "env-id",
|
||||
clientSecret: "env-secret",
|
||||
});
|
||||
const creds = await getOuraClientCredentials("user-1");
|
||||
expect(creds).toEqual({ clientId: "env-id", clientSecret: "env-secret" });
|
||||
});
|
||||
|
||||
it("returns null when neither the user nor the env is configured", async () => {
|
||||
findUnique.mockResolvedValue(null);
|
||||
getOuraCredentials.mockReturnValue(null);
|
||||
expect(await getOuraClientCredentials("ghost")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -31,6 +31,7 @@ const {
|
||||
vi.mock("../credentials", () => ({
|
||||
getOuraConnection: getConnMock,
|
||||
storeOuraTokens: storeTokensMock,
|
||||
getOuraClientCredentials: getCredsMock,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
@@ -57,7 +58,6 @@ vi.mock("../client", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../client")>();
|
||||
return {
|
||||
...actual,
|
||||
getOuraCredentials: getCredsMock,
|
||||
fetchReadiness: fetchReadinessMock,
|
||||
fetchSleep: fetchSleepMock,
|
||||
fetchDailyActivity: fetchActivityMock,
|
||||
@@ -73,7 +73,9 @@ const CONN = { accessToken: "acc", refreshToken: "ref" };
|
||||
beforeEach(() => {
|
||||
getConnMock.mockReset();
|
||||
storeTokensMock.mockReset().mockResolvedValue(undefined);
|
||||
getCredsMock.mockReset().mockReturnValue({ clientId: "c", clientSecret: "s" });
|
||||
getCredsMock
|
||||
.mockReset()
|
||||
.mockResolvedValue({ clientId: "c", clientSecret: "s" });
|
||||
fetchReadinessMock.mockReset().mockResolvedValue([]);
|
||||
fetchSleepMock.mockReset().mockResolvedValue([]);
|
||||
fetchActivityMock.mockReset().mockResolvedValue([]);
|
||||
|
||||
@@ -1,14 +1,76 @@
|
||||
/**
|
||||
* v1.17.0 (F4) — per-user Oura token accessors.
|
||||
* v1.17.1 — per-user BYO client id/secret resolver (DB-first then env).
|
||||
*
|
||||
* Oura uses a single shared OAuth app (env client id/secret via
|
||||
* `getOuraCredentials`). Per-user state is the granted access + refresh token,
|
||||
* stored encrypted on `User`. The merged schema carries NO token-expiry column,
|
||||
* so the sync layer refreshes REACTIVELY on a 401 rather than proactively on an
|
||||
* expiry timestamp (and persists both rotated tokens).
|
||||
* Like WHOOP / Fitbit, Oura is now a per-user BYO-key integration: each user may
|
||||
* register their own Oura app and store the client id/secret encrypted on
|
||||
* `User`, with a fall-back to the shared env app for existing single-app
|
||||
* deploys. Also per-user is the granted access + refresh token. The schema
|
||||
* carries NO token-expiry column, so the sync layer refreshes REACTIVELY on a
|
||||
* 401 rather than proactively on an expiry timestamp (persisting both rotated
|
||||
* tokens).
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
import { getOuraCredentials, type OuraCredentials } from "./client";
|
||||
|
||||
/**
|
||||
* Resolve the user's Oura OAuth client id/secret, DB-first then env.
|
||||
*
|
||||
* v1.17.1 makes Oura a per-user BYO-key integration (mirroring WHOOP / Fitbit):
|
||||
* a self-hoster registers their own Oura app and pastes the client id/secret
|
||||
* into Settings, stored encrypted on `User`. When the user has not configured
|
||||
* per-user keys we fall back to the shared env app (`OURA_CLIENT_ID` /
|
||||
* `OURA_CLIENT_SECRET`) so existing single-app deploys keep working. Returns
|
||||
* null when neither source is configured.
|
||||
*/
|
||||
export async function getOuraClientCredentials(
|
||||
userId: string,
|
||||
): Promise<OuraCredentials | null> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
ouraClientIdEncrypted: true,
|
||||
ouraClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (user?.ouraClientIdEncrypted && user?.ouraClientSecretEncrypted) {
|
||||
return {
|
||||
clientId: decrypt(user.ouraClientIdEncrypted),
|
||||
clientSecret: decrypt(user.ouraClientSecretEncrypted),
|
||||
};
|
||||
}
|
||||
|
||||
// Fall back to the shared env-configured OAuth app.
|
||||
return getOuraCredentials();
|
||||
}
|
||||
|
||||
/** Persist the user's Oura OAuth client id/secret, encrypted at rest. */
|
||||
export async function storeOuraClientCredentials(
|
||||
userId: string,
|
||||
clientId: string,
|
||||
clientSecret: string,
|
||||
): Promise<void> {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
ouraClientIdEncrypted: encrypt(clientId),
|
||||
ouraClientSecretEncrypted: encrypt(clientSecret),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Clear the user's stored Oura OAuth client id/secret. */
|
||||
export async function clearOuraClientCredentials(userId: string): Promise<void> {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
ouraClientIdEncrypted: null,
|
||||
ouraClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface OuraConnection {
|
||||
accessToken: string;
|
||||
|
||||
@@ -35,14 +35,17 @@ import {
|
||||
fetchDailyActivity,
|
||||
fetchReadiness,
|
||||
fetchSleep,
|
||||
getOuraCredentials,
|
||||
mapDailyActivity,
|
||||
mapReadiness,
|
||||
mapSleep,
|
||||
refreshAccessToken,
|
||||
type MappedMeasurement,
|
||||
} from "./client";
|
||||
import { getOuraConnection, storeOuraTokens } from "./credentials";
|
||||
import {
|
||||
getOuraClientCredentials,
|
||||
getOuraConnection,
|
||||
storeOuraTokens,
|
||||
} from "./credentials";
|
||||
import { OuraApiError, classifyOuraError } from "./response-classifier";
|
||||
|
||||
/** Default lookback window (days) for an incremental sync. Oura finalises a
|
||||
@@ -118,7 +121,7 @@ async function fetchAll(
|
||||
// case — rethrow so the caller classifies it.
|
||||
if (!(err instanceof OuraApiError) || err.httpStatus !== 401) throw err;
|
||||
|
||||
const creds = getOuraCredentials();
|
||||
const creds = await getOuraClientCredentials(userId);
|
||||
if (!creds) throw err;
|
||||
|
||||
const rotated = await refreshAccessToken(refreshToken, creds);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const findUnique = vi.fn();
|
||||
const getPolarCredentials = vi.fn();
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { user: { findUnique: (...args: unknown[]) => findUnique(...args) } },
|
||||
}));
|
||||
|
||||
// decrypt() is the fail-closed AES-256-GCM reader; the resolver only needs it
|
||||
// to round-trip the stored ciphertext, so a `dec(<x>)` shim is sufficient here.
|
||||
vi.mock("@/lib/crypto", () => ({
|
||||
decrypt: (cipher: string) => `dec(${cipher})`,
|
||||
encrypt: (plain: string) => `enc(${plain})`,
|
||||
}));
|
||||
|
||||
// The env fallback lives in ./client; stub it so the precedence is observable.
|
||||
vi.mock("../client", () => ({
|
||||
getPolarCredentials: () => getPolarCredentials(),
|
||||
}));
|
||||
|
||||
import { getPolarClientCredentials } from "../credentials";
|
||||
|
||||
describe("getPolarClientCredentials — DB-first then env", () => {
|
||||
beforeEach(() => {
|
||||
findUnique.mockReset();
|
||||
getPolarCredentials.mockReset();
|
||||
});
|
||||
|
||||
it("returns the per-user BYO client id/secret when both columns are set", async () => {
|
||||
findUnique.mockResolvedValue({
|
||||
polarClientIdEncrypted: "enc-id",
|
||||
polarClientSecretEncrypted: "enc-secret",
|
||||
});
|
||||
const creds = await getPolarClientCredentials("user-1");
|
||||
expect(creds).toEqual({
|
||||
clientId: "dec(enc-id)",
|
||||
clientSecret: "dec(enc-secret)",
|
||||
});
|
||||
// DB hit must not consult the env fallback.
|
||||
expect(getPolarCredentials).not.toHaveBeenCalled();
|
||||
expect(findUnique).toHaveBeenCalledWith({
|
||||
where: { id: "user-1" },
|
||||
select: {
|
||||
polarClientIdEncrypted: true,
|
||||
polarClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the shared env app when the user has no BYO pair", async () => {
|
||||
findUnique.mockResolvedValue({
|
||||
polarClientIdEncrypted: null,
|
||||
polarClientSecretEncrypted: null,
|
||||
});
|
||||
getPolarCredentials.mockReturnValue({
|
||||
clientId: "env-id",
|
||||
clientSecret: "env-secret",
|
||||
});
|
||||
const creds = await getPolarClientCredentials("user-1");
|
||||
expect(creds).toEqual({ clientId: "env-id", clientSecret: "env-secret" });
|
||||
expect(getPolarCredentials).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("falls back to env when only one half of the BYO pair is present", async () => {
|
||||
findUnique.mockResolvedValue({
|
||||
polarClientIdEncrypted: "enc-id",
|
||||
polarClientSecretEncrypted: null,
|
||||
});
|
||||
getPolarCredentials.mockReturnValue({
|
||||
clientId: "env-id",
|
||||
clientSecret: "env-secret",
|
||||
});
|
||||
const creds = await getPolarClientCredentials("user-1");
|
||||
expect(creds).toEqual({ clientId: "env-id", clientSecret: "env-secret" });
|
||||
});
|
||||
|
||||
it("returns null when neither the user nor the env is configured", async () => {
|
||||
findUnique.mockResolvedValue(null);
|
||||
getPolarCredentials.mockReturnValue(null);
|
||||
expect(await getPolarClientCredentials("ghost")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,75 @@
|
||||
/**
|
||||
* v1.17.0 (F4) — per-user Polar token accessors.
|
||||
* v1.17.1 — per-user BYO client id/secret resolver (DB-first then env).
|
||||
*
|
||||
* Unlike WHOOP (per-user BYO client id/secret), Polar uses a single shared
|
||||
* OAuth app whose client id/secret come from env (`getPolarCredentials`). What
|
||||
* is per-user is the granted token + Polar member id, stored encrypted on
|
||||
* `User`. Polar access tokens do not expire and carry no refresh token, so
|
||||
* there is no refresh path — a revoked grant surfaces as a 401 on the next read.
|
||||
* Like WHOOP / Fitbit, Polar is now a per-user BYO-key integration: each user
|
||||
* may register their own AccessLink app and store the client id/secret encrypted
|
||||
* on `User`, with a fall-back to the shared env app for existing single-app
|
||||
* deploys. Also per-user is the granted token + Polar member id. Polar access
|
||||
* tokens do not expire and carry no refresh token, so there is no refresh path —
|
||||
* a revoked grant surfaces as a 401 on the next read.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { decrypt, encrypt } from "@/lib/crypto";
|
||||
import { getPolarCredentials, type PolarCredentials } from "./client";
|
||||
|
||||
/**
|
||||
* Resolve the user's Polar OAuth client id/secret, DB-first then env.
|
||||
*
|
||||
* v1.17.1 makes Polar a per-user BYO-key integration (mirroring WHOOP / Fitbit):
|
||||
* a self-hoster registers their own Polar AccessLink app and pastes the client
|
||||
* id/secret into Settings, stored encrypted on `User`. When the user has not
|
||||
* configured per-user keys we fall back to the shared env app
|
||||
* (`POLAR_CLIENT_ID` / `POLAR_CLIENT_SECRET`) so existing single-app deploys
|
||||
* keep working. Returns null when neither source is configured.
|
||||
*/
|
||||
export async function getPolarClientCredentials(
|
||||
userId: string,
|
||||
): Promise<PolarCredentials | null> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
polarClientIdEncrypted: true,
|
||||
polarClientSecretEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (user?.polarClientIdEncrypted && user?.polarClientSecretEncrypted) {
|
||||
return {
|
||||
clientId: decrypt(user.polarClientIdEncrypted),
|
||||
clientSecret: decrypt(user.polarClientSecretEncrypted),
|
||||
};
|
||||
}
|
||||
|
||||
// Fall back to the shared env-configured OAuth app.
|
||||
return getPolarCredentials();
|
||||
}
|
||||
|
||||
/** Persist the user's Polar OAuth client id/secret, encrypted at rest. */
|
||||
export async function storePolarClientCredentials(
|
||||
userId: string,
|
||||
clientId: string,
|
||||
clientSecret: string,
|
||||
): Promise<void> {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
polarClientIdEncrypted: encrypt(clientId),
|
||||
polarClientSecretEncrypted: encrypt(clientSecret),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Clear the user's stored Polar OAuth client id/secret. */
|
||||
export async function clearPolarClientCredentials(userId: string): Promise<void> {
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
polarClientIdEncrypted: null,
|
||||
polarClientSecretEncrypted: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface PolarConnection {
|
||||
accessToken: string;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Per-user Oura BYO-key credentials. Each self-hoster registers their own Oura
|
||||
* app and pastes the client id/secret into Settings. Stored encrypted on
|
||||
* `User`. When unset, the integration falls back to the shared env-configured
|
||||
* OAuth app.
|
||||
*/
|
||||
export const ouraCredentialsSchema = z.object({
|
||||
// Trimmed: a trailing space or newline from the portal's copy button reaches
|
||||
// Oura verbatim and answers as "unknown client".
|
||||
clientId: z.string().trim().min(1).max(200),
|
||||
clientSecret: z.string().trim().min(1).max(200),
|
||||
});
|
||||
|
||||
export type OuraCredentialsInput = z.infer<typeof ouraCredentialsSchema>;
|
||||
@@ -0,0 +1,16 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Per-user Polar BYO-key credentials. Each self-hoster registers their own
|
||||
* Polar AccessLink app and pastes the client id/secret into Settings. Stored
|
||||
* encrypted on `User`. When unset, the integration falls back to the shared
|
||||
* env-configured OAuth app.
|
||||
*/
|
||||
export const polarCredentialsSchema = z.object({
|
||||
// Trimmed: a trailing space or newline from the portal's copy button reaches
|
||||
// Polar verbatim and answers as "unknown client".
|
||||
clientId: z.string().trim().min(1).max(200),
|
||||
clientSecret: z.string().trim().min(1).max(200),
|
||||
});
|
||||
|
||||
export type PolarCredentialsInput = z.infer<typeof polarCredentialsSchema>;
|
||||
Reference in new issue
Block a user