TogetherDone Grocery Integration
TogetherMeals builds no native grocery lists (MVP). It sends ingredients to TogetherDone, authenticating as an OAuth client of TogetherDone's existing OAuth 2.1 authorization server (DCR + PKCE — already live at the sister product; no new TogetherDone surface needed).
Connect flow
- Settings → Connected apps → "Connect TogetherDone". The web app opens TogetherDone's authorization endpoint
(PKCE, scopes
read write). TogetherMeals is registered once as an OAuth client (via DCR or manual registration; client id in config). - TogetherDone redirects to the browser page
/integrations/togetherdone/callbackwithcode,state, andiss, or an OAuth error. The page checks the pending transaction's state and issuer, removes the query from browser history, and requires the TogetherMeals account that started the attempt. A Google sign-in round trip resumes on the same page through tab-scoped session storage, without forwarding the authorization code to Google. Denial shows a cancellation message without exchanging a code. The page posts a verified code and state to the authenticatedservices/apicallback, which exchanges the code, encrypts thetd_mcp_*access + refresh tokens, and stores them inintegration_connections(per user — D-104). - The person chooses a grocery list inside the send flow (fetched via TogetherDone
GET /api/v1/listswith the stored token), not in Connected apps. A successful send saves it as their default (see Send flow). Group settings may store a suggested list per group; the user's own choice wins.
The web settings card shows connection status, reconnect, and confirmed disconnect. It requires the person's own TogetherMeals Pro or trial to connect, and keeps disconnect available after that access ends. Each browser attempt expires after ten minutes. A failed or uncertain exchange requires checking connection status and starting a new attempt, since authorization codes are single use. Browser storage must be available. Grocery review and list selection are not part of the connection flow: they live in the send flow, opened from the Meal Plan or a Recipe (see Clients under Send flow).
Mobile connection
More → Connected apps opens the native TogetherDone settings screen. Connect uses the same authenticated API as web, then opens TogetherDone in the system browser. Both clients see the same connection for the signed-in TogetherMeals user. Tokens and the PKCE verifier stay in the API.
Mobile registers a separate HTTPS redirect:
https://www.togethermeals.app/integrations/togetherdone/mobile-callback.
The app claims only that path through iOS Universal Links and Android App Links, so the web
callback continues to open in the browser. TogetherDone rejects direct custom-scheme redirects.
When automatic app-link delivery leaves the callback in the browser, its fallback page offers
an explicit "Open TogetherMeals" link to the installed app. This page needs no browser sign-in
and never exchanges a code. Both callback pages suppress caching, framing, referrers and
development request logging of authorization codes.
The app stores a pending attempt in SecureStore, bound to its initiating account, expected issuer, state and ten-minute lifetime. It captures the response before its sign-in gate and removes callback parameters from navigation. A cold launch can resume the captured response. Repeated callback deliveries share one in-flight exchange. A durable marker written before exchange prevents replay after a process crash or uncertain response. Denial never exchanges a code. A different TogetherMeals account must switch back or start its own connection.
Configure app links and register the mobile callback
- Deploy the callback and both association endpoints on the callback origin, with no redirects:
/.well-known/apple-app-site-associationand/.well-known/assetlinks.json. - Configure the web deployment's public signing identities. Set
TOGETHERMEALS_APPLE_TEAM_IDto the signing team's ten-character ID.TOGETHERMEALS_IOS_BUNDLE_IDandTOGETHERMEALS_ANDROID_PACKAGEdefault toapp.togethermeals.appand must match the native builds. SetTOGETHERMEALS_ANDROID_SHA256_FINGERPRINTSto comma-separated, colon-delimited SHA-256 signing certificate fingerprints. Google Play installs use the Play app signing certificate, not the upload certificate. Missing identities return 404; malformed identities return 503 instead of advertising an incorrect association. - Build and install a new native app.
EXPO_PUBLIC_TOGETHERDONE_CALLBACK_ORIGINdefaults tohttps://www.togethermeals.app, andEXPO_PUBLIC_TOGETHERDONE_ISSUERdefaults tohttps://api.togetherdone.app. The origin must be HTTPS with no path, port, query or fragment. An OTA JavaScript update cannot add the native associated-domain/intent-filter capabilities. - Register both exact callback URLs under the same production public PKCE client. The prepared metadata includes both callbacks. Follow the TogetherDone handoff's target-specific approval before remote registration or changing an existing allowlist. This code change performs neither operation.
- Verify on signed iOS and Android devices: warm and cold callbacks, browser fallback, denial, wrong-account sign-in, duplicate delivery, disconnect, and status shared with web. Check the public association responses and the installed app's verified-domain state before testing.
Production activation still needs the real public signing identities, deployment, native builds and approved OAuth registration. No database migration is needed for mobile connections.
Production setup
The TogetherDone OAuth handoff defines the production registration. Deploy the browser callback before registering its exact URL.
| Setting | Production value |
|---|---|
| Browser callback | https://www.togethermeals.app/integrations/togetherdone/callback |
| Mobile callback | https://www.togethermeals.app/integrations/togetherdone/mobile-callback |
API and worker TOGETHERDONE_ORIGIN | https://api.togetherdone.app |
API and worker TOGETHERDONE_AUTHORIZATION_ORIGIN | https://togetherdone.app |
API and worker TOGETHERDONE_CLIENT_ID | togethermeals-production, after approved registration |
Web NEXT_PUBLIC_TOGETHERDONE_ISSUER | https://api.togetherdone.app, the default |
The proposed registration is a public PKCE client and needs no client secret. The API and
credential worker also need the same private INTEGRATION_TOKEN_KEY and any previous keys.
See the credential worker runbook.
The browser derives its callback from its current origin; only an exactly registered origin and
path can complete authorization. For isolated local tests, the public issuer override must match
the API's TOGETHERDONE_ORIGIN. No development OAuth client is registered by this implementation.
The repository change does not deploy services, register the production OAuth application, or change remote configuration. Follow TogetherDone's handoff for approval of the exact application registration and verify the real browser flow after deployment.
Disconnect always succeeds, even while TogetherDone is down (D-104). It marks the row revoked
immediately and queues the stored refresh ciphertext for the
credential worker, then tries POST /oauth/revoke at
once so the common case needs no worker round trip. Disconnect wins over a concurrent refresh or
an unfinished reconnect. Refresh failures mark error and surface a reconnect prompt, never
silently.
Tokens and the PKCE verifier are AES-GCM ciphertext (D-105). Each payload names its key id, and
its authenticated data binds the owning user and purpose (access, refresh, or verifier), so
a ciphertext copied to another account or field does not decrypt. INTEGRATION_TOKEN_KEY
encrypts; comma-separated INTEGRATION_TOKEN_PREVIOUS_KEYS still decrypt during a rotation. A
credential that cannot be decrypted returns 503 and stays stored, because restoring the key
repairs it; the user can still disconnect.
Send flow
Send is a private acting-user operation rather than a shared Meal Space mutation. A Viewer may send ingredients they can read when they have their own Pro or trial entitlement and TogetherDone Connection. The operation never uses another member's credentials or changes shared content.
POST /api/v1/integrations/togetherdone/send with { items: [{content, quantity?, note?}], list_id?, section_id? }:
- Client-side: user selects a Recipe or several planned Recipe Entries. Multi-meal Send defaults to individually selectable eligible Entries in the next seven days from Meal Spaces visible on that user's Timeline. The user previews and edits the ingredient list before sending (dedup/merge is client-side UX in MVP). The client suggests a merge only for normalized ingredient matches with compatible parsed quantities and units, retains source-Entry labels, and waits for user acceptance. Unparsed or incompatible lines stay separate; no unit conversion occurs. Ingredient-name matching normalizes only case, punctuation, and harmless whitespace. It does not use AI or infer semantic equivalence; users may merge near-matches manually. Different preparation notes do not block a suggestion when ingredient and unit match. Accepted merges retain the quantities, preparation notes, and source Entry for each component during review, and the user can split them again before sending. Source meal names and preparation notes are not sent to TogetherDone unless the user manually adds them to an outgoing note. Every ingredient begins unselected; the user may Select all or choose individual missing items. Any content, quantity, or note edits apply only to this outgoing payload. Unparsed ingredients use their raw line with no structured quantity. MVP does not send Prep Entries or other tasks. Merge suggestions appear only after selection and use selected lines only. Send requires at least one non-empty item. Empty edited content removes the item after confirmation. Closing the sheet discards all review state; reopening starts from current Recipe data. Ingredient section headings appear only as visual group labels during review. They cannot be selected and never become TogetherDone items or notes. A Recipe with no Ingredient lines has no Send action.
- API decrypts the acting user's connection tokens (tokens never leave the server), refreshes if expired.
- Pushes via TogetherDone's
POST /api/v1/batch(cap 100/BATCH_MAX, chunked if larger) with anIdempotency-Keyderived from the send request, so retries never duplicate groceries. Items go directly to the selected list; TogetherMeals creates no automatic sections. - Returns per-item results; failures are surfaced with a retry affordance.
After success, each source Entry is labeled Sent for that user and excluded from their later default multi-meal selections. It remains visible and manually selectable for resend. Send state is private to the acting user; another member's export through their own Connection does not change it. Only Entries contributing at least one selected outgoing item receive state. All selected source items succeeding means Sent; mixed results mean Partially sent; no selected contribution means no state. A newly chosen list becomes the user's default only after a successful Send. If a run has mixed item results, affected Entries are labeled Partially sent and also excluded from a fresh full-send default. Finish sending retries only the failed item payloads; successful provider items are never included. Item-level payload and result snapshots make the retry idempotent even when one outgoing item merged ingredients from several Entries. Later edits to an Entry, Recipe, Variation, target yield, or ingredient selection do not create a Changed since sent state and do not trigger a delta. A manual resend starts a fresh review and may send the full current selection again. Unresolved sends can be retried for up to 23 hours, within TogetherDone's 24-hour deduplication window. After that, the API refuses to resend an uncertain payload; the user must check the provider list before starting a new send. Completed runs still replay their saved results.
If the saved provider list no longer exists, clear that default and require an explicit new list; never select another provider list automatically.
The API uses a minimal client verified against the TogetherDone v2 source contracts for the documented
/api/v1 paths (the public MCP package's shorter /v1 prefix is not used):
GET /oauth/authorizeonTOGETHERDONE_AUTHORIZATION_ORIGINwith PKCE S256 and scoperead write.POST /oauth/token,POST /oauth/revoke, and/api/v1useTOGETHERDONE_ORIGIN. The authorization origin is the TogetherDone web app; the API origin is its OAuth issuer. Both origins andTOGETHERDONE_CLIENT_IDmust be configured to enable the integration.GET /api/v1/lists?limit=100, then&cursor=with eachlinks.nextkeyset cursor untilmeta.has_moreis false. The query is strict: TogetherDone rejects any other parameter. More than 20 pages, orhas_morewithout a cursor, fails closed rather than offering a partial list. List titles are the display names.POST /api/v1/batchbody{ operations: [{ method: "POST", path: "/api/v1/items", body: { list_id, content, notes?, section_id? } }] }withIdempotency-Key. (/api/v1/lists/{id}/itemsis read-only.) Item content is at most 1000 characters including the quantity prefix. Response{ data: { results: [{ status }] } }. The first chunk reuses the command UUID; later chunks use a stable key derived from it. Definitive whole-batch rejection fails the remaining items. HTTP or item-level 409 and server errors keep the original run pending because the outcome may be uncertain. Retrying preserves the original item order and keys. Per-itemstatusvalues apply only when the batch HTTP call succeeds.
POST /api/v1/integrations/togetherdone/preview returns unselected lines (origin entry or recipe). Headings are omitted. Name matching changes only case, punctuation, and whitespace; near-matches, including singular/plural names, stay distinct for manual review. suggestGroceryMerges lives in core and is not applied by the API.
A database cron sweep expires retained credentials without waiting for another user request. It moves the encrypted refresh token to a private revocation queue; the credential worker revokes it and removes the queued ciphertext. Deployment must configure that worker and its scheduler.
Account deletion (D-149), disconnect, a reconnect over live credentials, and an error clear after a refused refresh all move the refresh ciphertext they replace into the same queue before clearing it. Tokens TogetherDone mints for a refresh or callback whose storage is then definitively refused (a lost fence, a lapsed plan, a pending deletion) were never stored; the API revokes them once, best effort. Queue entries outlive account finalization until the worker revokes them.
The connect callback is fenced on a connection epoch that only a completed reconnect advances, so a token refresh during the consent screen does not cancel it. Starting a connect supersedes earlier attempts, consumed or not. A placeholder row from a connect that never finished reads as disconnected.
Clients
The web and native Meal Plans send planned meals' groceries, and the web and native Recipe pages send one Recipe's ingredients (D-228).
Entry points. On web, a Meal Plan header button (IconShoppingCart, "Send groceries to
TogetherDone") opens the flow. It is hidden when the app has no provider or no Entry reads, and
disabled offline. On mobile, the Meal Plan header IconButton carries the same label. An Entry
labeled Partially sent offers Finish sending in its actions (the web Entry menu, the mobile meal
sheet). It uses the label's root run_id and opens straight on a confirmation, skipping meal
choice and review.
Recipe entry point. The Recipe page has a "Send to TogetherDone" button
(IconShoppingCart) in the Ingredients section, on web and mobile. On web it has a row of its own
under the Ingredients heading and servings, so it sits in the same place on every Recipe, with a
44 px target in the narrow layout. On mobile it sits at the top of the Ingredients tab, beside Makes.
It reuses the Meal Plan's dialog (web) and sheet (mobile) in a recipe mode.
- Visibility. It shows only when the Recipe has an Ingredient line with text
(
hasGroceryIngredientsin core), and only when the app has a provider. A Viewer who has their own Pro or trial and a Connection can send (D-104), so it does not depend on write access. - What it sends. The version on screen. A Variation sends its
variation_idin the preview request; the Base Recipe omits it. The review names the version in each line's source label ("Recipe title · Variation name"). - Yield. Baseline yield (D-135). When the person changed servings on screen, the review shows "Quantities are for the original N unit." above the lines, because the sent quantities do not follow the stepper.
- Disabled states. The button is disabled offline ("Sending needs a connection"). On web it is also disabled while Variations are loading or failed to load, or while the Recipe read has failed or may be out of date, because the version on screen may not be the one the send would name. Its title says "Loading versions…" while Variations load, and "Recipe may be out of date. Try again in a moment." after a failed read. On mobile it is disabled while Recipe syncing is paused or an app update is required, since the local copy may be out of date. Mobile's Recipe and Variations come from one local read, so it has no loading state.
- Flow. The same gates (Pro, Connect, unconfirmed send) and the same attempt recovery, but it opens straight on the review: no meals step, and the review's Back button becomes Cancel. After a failed send, the start-over action reads "Review ingredients" in place of "Choose meals".
- No Sent state. A Recipe send has no source meals, so each outgoing item's
source_entry_idsis empty and no Entry gets a Sent or Partially sent label. Finish sending still works inside the dialog or sheet, through the root run id the first send returned.
Gates. Each time the flow opens it reads connection status again and never acts on a cached answer. It then checks, in order:
- Pro: the person's own Pro or trial. Otherwise it explains and offers See Pro plans.
- Connect: no usable connection (not connected, or status
error) links to Connected apps. OAuth is not started in place. - Unconfirmed send: an attempt kept from an earlier send (see Attempt recovery) offers Check send or Discard and start over. Discard asks first, because the send may have gone through. Nothing new is sent until the attempt is settled.
Steps. A Recipe send starts at step 2.
- Choose meals. The list is the eligible planned Recipe Entries from today through today + 6 in
the Meal Spaces visible on the Timeline (
groceryMealChoicesin core). Sent and Partially sent meals are listed with their label but not preselected. At most 40 meals (GROCERY_PREVIEW_SOURCES_MAX) can be reviewed at once, and preselection stops there. Mobile lists a meal that has not synced yet as "Waiting to sync", unselectable because it has no server row to preview. - Review ingredients. Every line begins unselected. The review offers merge suggestions for the selected lines, manual merge, split, edit, and removal with an inline confirmation. A line the person has edited is never suggested, because accepting would replace what they typed; it can still be merged by hand. A manual merge keeps the first draft's content and every draft's notes, and when any merged draft has a typed quantity it joins the drafts' quantities with " + " in draft order instead of recomputing them. The list picker preselects the person's default list only if it is still among the provider's lists.
- Result. A send is reported as sent, partial (with Finish sending for the items that missed), failed (none reached the provider, with Try again), or unconfirmed. An unconfirmed send always offers Check send and Discard and start over. It shows the API's detail when there is one; a sign-in refusal instead says to sign in again, and a Pro refusal says to renew Pro and links See Pro plans. A 412 shows the API's detail and, once the refreshed status fails a gate, a link to Connected apps or See Pro plans beside Check send. Finish sending asks "Finish your send that included ?", because it retries every failed item of the root run, not only that meal's.
Attempt recovery. The client stores the Idempotency-Key and the exact request body (or the root run id for Finish sending) before it sends, so a reload or relaunch replays the same request instead of making a new one.
- Web keeps one slot per person and provider in
localStorage(togethermeals:grocery-send:<actor>:<provider>), so the attempt survives closing the tab or a crash, and every tab of that person sees it. A temporary auth loss keeps it, because a lost key risks duplicate groceries. Explicit sign-out, an account switch, and a denial clear it. - Mobile keeps it in the person's encrypted SQLite store (table
grocery_attempts, one row per provider). An account switch or disposal clears it with the rest of that person's local data. - A first send or Finish sending keeps the attempt after a network failure, any response of 500 or higher, 409, 412 and 429 (the rule of D-199 item 3). Any other refusal of a first request comes before a run starts, so it clears the attempt.
- A Check send, which replays a stored attempt, keeps it after every refusal, whatever the status (D-228). Only a result, or the person choosing Discard and start over, settles it.
- An attempt expires after 23 hours, inside the provider's 24-hour deduplication window. The flow drops an expired attempt the next time it opens.
Failed reads. Inside the flow, a failed send-states read blocks meal choice with Try again, so a Sent meal is never preselected by accident. On the Timeline the Sent labels are decoration: when their read fails they are simply hidden.
API additions. Preview lines carry match ({ item, unit, quantity } or null), the parsed
ingredient the review uses to suggest merges. Send states carry the root run_id (nullable),
the id that Finish sending names.
Deploy order: the API deploys first, before the migration and before the web and mobile clients.
It reads a missing run_id as null, so it works against a database without the migration. The
clients parse match and run_id strictly, so they must never meet an API that lacks them. Then
apply migration 1793428594000_grocery_send_state_runs.sql, which fills run_id, and ship the
clients. Once that migration is applied on every database, remove the nullable-run_id
normalization (withStateRuns in services/api/src/integrations/store.ts); that is the contract
phase.
Installed builds parse these responses, so the preview, send, finish and send-states response shapes are now frozen. Change them only in phases (expand, migrate, contract), as for any API an installed build reads.
Provider seam
The API implements this behind a GroceryExportProvider interface
(connect, listTargets, send) with togetherdone as the only MVP provider. Future:
Apple Reminders, Todoist, AnyList (plan-outline §24). Provider identity lives in
integration_connections.provider, so the schema needs no changes for new providers.
The clients have their own provider-neutral seam (D-228). @togethermeals/core holds the review
session and meal eligibility, plus the GROCERY_PROVIDERS descriptors that supply the provider's
name in copy. @togethermeals/sync holds GroceryExportProvider (descriptor and an api), and
createGrocerySender, which keeps and replays attempts. Each app adds one adapter per provider
(createTogetherDoneGroceryProvider), plus its attempt storage and UI. Adding a provider means a
descriptor, an adapter and server routes; the review UI does not change.
Failure modes
| Failure | Behavior |
|---|---|
| No connection | 412 precondition_failed + connect prompt |
| Token refresh fails | connection → error, 412 with reconnect prompt |
| TogetherDone 4xx on items | partial results returned per item; nothing retried blindly |
| TogetherDone down / 5xx | 503 service_unavailable; the run stays pending so the same idempotency key can resume |
| The user's own TogetherDone Pro lapsed (API 403, or a refresh refused with TogetherDone's Pro message) | 412 precondition_failed naming TogetherDone Pro; the connection and refresh token are kept and the run stays pending for a same-key retry after renewal |
| Authorization code refused (expired, reused, or no TogetherDone API access) | 412 precondition_failed asking the user to connect again |
| Rate-limited by TogetherDone | surfaced with retry-after; no queueing in MVP |