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
2 changes: 1 addition & 1 deletion app/api/local.settings.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"VITE_SUPABASE_ANON_KEY": "eyJ...",
"SUPABASE_ANON_KEY": "eyJ...",
"SUPABASE_SERVICE_ROLE_KEY": "eyJ...",
"SPORTY_SYNC_API_KEY": "any-secret-string-you-choose"
"SPORTY_SYNC_API_KEY": "any-secret-string-you-choose (used by /api/sporty-health monitoring endpoint only)"
}
}
13 changes: 10 additions & 3 deletions app/api/sportySync.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { app } from '@azure/functions';
import { verifySupabaseJwt } from './claudeUtils.js';

// BU 8 is hardcoded for the single-gym MVP (Sporty Thon Senter Ski).
// When multi-gym support lands, replace with a DB lookup via user_gyms.sporty_business_unit_id.
Expand Down Expand Up @@ -180,14 +181,20 @@ app.http('sportySyncHealth', {
// ── HTTP trigger: manual kick + optional backfill ─────────────────────
// POST /api/sporty-sync → sync today
// POST /api/sporty-sync {"shiftDays":-7} → duplicate current data 7 days back
// Requires header: x-api-key: <SPORTY_SYNC_API_KEY>
// Requires header: X-Supabase-Token: <valid Supabase JWT>
// (Azure SWA hijacks the Authorization header — never use it for app JWTs)
app.http('sportySyncHttp', {
methods: ['POST'],
route: 'sporty-sync',
authLevel: 'anonymous',
handler: async (request, context) => {
const expectedKey = process.env.SPORTY_SYNC_API_KEY;
if (!expectedKey || request.headers.get('x-api-key') !== expectedKey) {
const token = request.headers.get('x-supabase-token');
const userId = await verifySupabaseJwt(
token,
process.env.SUPABASE_URL,
process.env.SUPABASE_ANON_KEY,
);
if (!userId) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
Expand Down
6 changes: 5 additions & 1 deletion app/src/components/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
import { BodySVG } from "../lib/bodymap.jsx";
import { fetchLastSession, fetchThisWeekSessions } from "../lib/db";
import { extractMuscles, logDevError, getIntlLocale, toWeekIso, isoWeekMonday, toIsoDate } from "../lib/utils";
import { supabase } from "../lib/supabase";
import PageShell, { SectionLabel, AccentChip } from "./PageShell";
import { useNav } from "../lib/NavContext";

Expand Down Expand Up @@ -45,9 +46,12 @@ export default function Home({ onShowHistoryWithDate }) {
setSyncState('loading');
setSyncMsg('');
try {
const { data: { session } } = await supabase.auth.getSession();
const res = await fetch('/api/sporty-sync', {
method: 'POST',
headers: { 'x-api-key': import.meta.env.VITE_SPORTY_SYNC_API_KEY ?? '' },
headers: {
...(session?.access_token ? { 'X-Supabase-Token': session.access_token } : {}),
},
});
const json = await res.json();
setSyncState(res.ok ? 'ok' : 'error');
Expand Down
33 changes: 33 additions & 0 deletions supabase/migrations/20260515_rec_cache_ownership.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
-- Add written_by so each cache entry has a deterministic owner.
-- DEFAULT auth.uid() means saveRecsCache does not need to include the column —
-- PostgreSQL sets it automatically from the calling user on INSERT.
ALTER TABLE public.recommendation_cache
ADD COLUMN written_by uuid REFERENCES profiles(id);

-- Clear the cache before making the column NOT NULL.
-- recommendation_cache is ephemeral (7-day TTL) — truncating is safe.
TRUNCATE public.recommendation_cache;

ALTER TABLE public.recommendation_cache
ALTER COLUMN written_by SET NOT NULL,
ALTER COLUMN written_by SET DEFAULT auth.uid();

-- Tighten INSERT: written_by must equal the calling user.
DROP POLICY "Authenticated users can write rec cache" ON public.recommendation_cache;

CREATE POLICY "Authenticated users can write rec cache"
ON public.recommendation_cache
FOR INSERT
TO authenticated
WITH CHECK (written_by = auth.uid());

-- Tighten UPDATE: only the original writer can refresh their own entry.
-- When a different user's upsert hits ON CONFLICT, the UPDATE is silently
-- skipped (no error) — the existing entry stays, preventing poisoning.
DROP POLICY "Authenticated users can update rec cache" ON public.recommendation_cache;

CREATE POLICY "Cache owner can update their entry"
ON public.recommendation_cache
FOR UPDATE
TO authenticated
USING (written_by = auth.uid());