diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2b59ae53019..4bd78c79785 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,6 +61,7 @@ jobs: - 'Cargo.lock' gpui: - '.gitattributes' + - 'packages/app-store/test/fixtures/**' - 'scripts/setup.js' - 'apps/desktop-gpui/**' - 'apps/media-server/src/__tests__/fixtures/**' @@ -99,6 +100,12 @@ jobs: run: | node --test scripts/bun-scripts.test.mjs + - name: Validate App Store apps + run: | + git fetch --no-tags --depth=1 origin main + bun app-store validate --base FETCH_HEAD + bun run --cwd packages/app-store test + - name: Test Loops profile sync run: | bun test scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts diff --git a/app-store/ARCHITECTURE.md b/app-store/ARCHITECTURE.md new file mode 100644 index 00000000000..266c579c9db --- /dev/null +++ b/app-store/ARCHITECTURE.md @@ -0,0 +1,141 @@ +# App Store architecture + +This is how Cap Apps work end to end: what an app is, where it lives, how it reaches people, and what keeps it safe and fast. If you want to build an app, start with [README.md](./README.md). This document is for people working on the store itself. + +## Principles + +1. **One app, one manifest, one store.** There is no separate web store and desktop store. An app lists what it contributes, and Cap works out where it runs from that. People install an app once and it works everywhere they use Cap. +2. **Apps declare, Cap draws.** No app ships UI code, on the web or on desktop. Apps describe settings fields, actions and content, and Cap renders all of it with its own components. Every app looks native, stays fast, and keeps working when Cap's design changes. +3. **Trust follows the code.** Content apps have no code at all. Connection apps run their code on their author's own server and only see what their declared permissions allow. Code that runs on the device (WebAssembly, in a later API version) gets its own sandbox and capability list. +4. **The repo is the registry.** Every app is a folder in `app-store/apps`. A pull request is a submission, CI is the first reviewer, and merging publishes. Cap's build turns the folder into a signed, content-addressed catalog. +5. **Guards are code, not prose.** Every rule in the guidelines that a machine can check is checked by `bun app-store validate`, in CI and again when the catalog is built. + +## Where things live + +``` +app-store/ + README.md Build an app (start here) + GUIDELINES.md Review rules + ARCHITECTURE.md This file + manifest.schema.json Generated from the manifest schema, for editor autocomplete + templates/ Starting points used by `bun app-store new` + apps// One folder per app + +packages/app-store/ @cap/app-store: manifest schema, validator, catalog builder, + CLI, request signing and verification +apps/web/ Store pages, install API, event delivery, actions +apps/desktop-gpui/ Store page in Settings, catalog sync, content and actions in the editor +``` + +## What an app can contribute (API version 1) + +| Contribution | Kind | Runs | Where it shows up | +|---|---|---|---| +| `backgrounds` | Content | Desktop | Editor background picker, in an Apps tab | +| `captionStyles` | Content | Desktop | Editor caption presets | +| `colorLooks` | Content | Desktop | Editor color presets | +| `connection.events` | Connection | Author's server | Signed event delivery after Cap events | +| `connection.actions` | Connection | Author's server | Cap menus on web and desktop ("Send to Notion") | +| `connection.settings` | Connection | Cap | A settings form Cap renders at install, on web and desktop | + +Where an app runs is worked out from its contributions and is never declared, so the badges in the store cannot drift from what the app does. + +Planned for later API versions, with the manifest reserving room for them: + +- **Transitions and effects** as WGSL shaders with a fixed uniform block, validated with naga in CI and on load. +- **Device code** as WebAssembly components (`wasm32-wasip2`), one frozen WIT world per API version, the way Zed does it. Device code will return the same declarative views connections use, so a slot never cares where its logic runs. +- **Scoped API tokens** for connections that need to call the Cap API, minted per install from the permissions the user granted. + +## Manifest + +Each app folder has a `manifest.json`. The schema lives in `packages/app-store/src/manifest.ts` and is the single source of truth: the validator, the catalog builder, the web app and the generated JSON Schema all come from it, and the desktop app parses every app in the repo in a test so its Rust types cannot drift. + +```json +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "discord", + "name": "Discord", + "version": "1.0.0", + "description": "Post new Caps to a Discord channel.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["communication"], + "connection": { + "url": "/api/app-store/first-party/discord", + "permissions": ["cap.transcript"], + "events": ["cap.ready"], + "settings": [ + { "key": "webhookUrl", "type": "secret", "label": "Webhook URL", "required": true } + ], + "actions": [{ "id": "post", "title": "Post to Discord", "target": "cap" }] + } +} +``` + +`apiVersion` works like Shopify's dated API versions and Zed's frozen WIT folders. Each Cap client accepts a range of API versions, and the catalog tells it which apps it can run, so an older desktop build never sees an app it does not understand. + +## Catalog + +`bun app-store build` runs before the web app builds. It validates every app, then writes: + +- `catalog.json`: every app's listing (name, description, icon, categories, derived platforms, permissions, contributions) plus the hash of each asset. +- `public/app-store//.`: every asset under a content hash, served from Cap's CDN with an immutable cache header. + +The web app reads the catalog in process. The desktop app fetches `GET /api/app-store/catalog` with an ETag, keeps the last copy on disk so the store works offline, downloads assets on install and checks each one against its hash before use. + +The catalog also carries a `blocked` list. A blocked app disappears from the store, its connection receives nothing, and the desktop app stops loading its content on the next catalog sync. That is the kill switch. + +## Installs + +An install belongs to an account, never a device. + +- **For me:** the app sees only Caps you own. +- **For my organization:** owners and admins install it, and it sees Caps their owners shared with that organization. A Cap that only belongs to the organization stays private to its owner. Owners can stop members from installing connection apps at all. + +Installs live in `app_store_installations`, one row per app and scope, with settings encrypted using the same app-layer encryption as storage integrations. The row records the permissions and events that were granted. When a new version of an app asks for more, Cap keeps delivering only what was granted and asks for a review in the store, the way Slack asks for re-consent on new scopes. + +Desktop content apps also work signed out. The desktop keeps a local install list, and when you sign in it merges that list with your account's installs. + +## Connections + +A connection is a server the app's author runs. Cap calls it, and it never calls into Cap's internals. All requests go to fixed paths under the declared `url`: + +| Request | Path | When | +|---|---|---| +| Lifecycle | `POST {url}/lifecycle` | Installed, settings changed, uninstalled | +| Events | `POST {url}/events` | A subscribed Cap event happened | +| Actions | `POST {url}/actions/{actionId}` | Someone ran an action from a Cap menu | + +Every request is signed with Ed25519, the way Discord signs interactions. Cap derives the signing key from its server secret, publishes the public key at `/.well-known/cap-app-store-keys.json`, and sends `Cap-Signature`, `Cap-Timestamp` and `Cap-Request-Id` headers. Apps verify with the public key, so no secret has to reach an author before the first request. `packages/app-store/src/signing.ts` has `verifyCapRequest`, which only needs Node's `crypto`, for authors to copy into a TypeScript server. + +Payloads carry only what the install was granted. Every Cap event includes the basics (id, title, share link, owner name, creation time, duration). `cap.transcript` adds the transcript text, `cap.summary` adds the AI title, summary and chapters, and `cap.comments` adds comment text. + +Delivery reuses the Infra webhook machinery: the same URL rules (https only, default port, public addresses only, no redirects), a 10 second timeout, retries with backoff over about a day on Vercel Workflow, and switching a connection off after sustained failures. Actions are synchronous with the same 10 second limit and return one of a fixed set of results (`toast` with a message, or `open` with an https URL) that Cap renders natively. + +First-party connections declare a relative URL and use exactly the same signed requests, dispatched in process by the Cap server that sends them, so a self-hosted Cap serves its own and nothing listens publicly for them. + +## Built-in apps + +Slack, Amazon S3 and Google Drive already exist as integrations with their own flows. They appear in the store as built-in apps (`"builtin": ""`), whose install button opens the existing setup. Only apps owned by Cap can declare `builtin`, and the validator enforces it. + +## Guards + +Checked by `bun app-store validate` in CI and again at catalog build: + +- The manifest matches the schema exactly. Unknown keys are errors. +- `id` is kebab-case, 3 to 40 characters, matches the folder name, is unique, and does not contain "cap". +- `version` is semver and must go up whenever anything in the folder changes. +- Required files are present: `manifest.json`, `icon.png` (512x512, at most 256 KB), `README.md` and a license the guidelines accept. +- Only files the manifest references, plus the required ones, may be in the folder. No hidden files, symlinks, executables or archives. +- Images are PNG, JPEG or WebP, with dimensions and file sizes inside the limits for their slot, and the whole folder stays under 25 MB. +- Connection URLs are https on the default port, with a public hostname and no credentials, query or fragment. +- Settings keys are unique, select options are non-empty, there are at most 20 fields, and secrets are only ever `secret` fields. +- Only apps owned by Cap can be built-in. + +Checked at runtime: + +- Catalog assets are verified by hash before use. +- Connections only ever receive what was granted, within the 10 second limit, and are switched off after sustained failures. +- Action results are a fixed set; `open` URLs must be https. +- Strings from apps are rendered as plain text only, never as HTML or markdown, except the app's README on its store page, which is sanitised markdown. diff --git a/app-store/GUIDELINES.md b/app-store/GUIDELINES.md new file mode 100644 index 00000000000..85f4b478dd9 --- /dev/null +++ b/app-store/GUIDELINES.md @@ -0,0 +1,35 @@ +# App Store guidelines + +`bun app-store validate` checks everything a machine can. A Cap maintainer checks the rest by hand before merging. These are the rules they use. + +## Every app + +- **One app, one job.** An app does one clear thing. Do not bundle unrelated content to look bigger, and do not publish near-copies of an existing app. +- **Honest listing.** The name, description, icon and README describe what the app really does. No keyword stuffing, no claims you cannot back up, no "best" or "#1". +- **Names.** Title Case nouns ("Aurora", "Notion Sync"), not sentences. Do not use "Cap" in the name or imply the app is made by Cap unless it is. +- **Icon.** Your own artwork, readable at 32 pixels, works on light and dark backgrounds. No default or placeholder icons. +- **README.** Starts with what the app does, then how to set it up. If it needs an account somewhere else, a paid plan, or sends data outside Cap, it says so. +- **You own what you ship.** Images, styles and names are yours or licensed for redistribution under the license you declare. No other companies' logos or trademarks unless you are that company or the app connects to their product. +- **Ownership.** The `author.github` account maintains the app. When someone else changes it, maintainers ask the author to review first, except for security fixes and broken builds. +- **Content.** Nothing hateful, sexual, violent, deceptive or illegal. + +## Content apps + +- Backgrounds look good behind a screen recording: no busy patterns that fight with text, no visible compression artefacts or banding, and no watermarks. +- Caption styles stay readable over light and dark video. +- Colour looks are subtle enough to use on real content. A look that only works on one clip is not a look. + +## Connections + +- **Ask for the least.** Request only the permissions and events the app uses. Reviewers check each one against the README. +- **No surprises.** Never post, publish or email anything on someone's behalf unless their settings or a click on your action asked for it. +- **Privacy policy.** Explain what you store, for how long, and how people delete it. Delete everything for an install when you receive `uninstalled`. +- **Verify every request** with Cap's public key and reject anything unsigned or stale. +- **Be fast.** Answer events within a few seconds and do slow work afterwards. Actions must answer within 10 seconds. +- **Secrets.** Collect API keys and tokens only through `secret` settings, never in a `text` field or by asking people to paste them anywhere else. +- **No tracking.** Do not use Cap data for advertising, profiling or training models, and do not add analytics that identify people. +- **Stay up.** Connections that fail for days are switched off. Apps that stay broken are removed from the store. + +## Removal + +Cap can remove an app, or block it remotely through `app-store/blocked.json`, if it breaks these guidelines, stops working, or puts people at risk. A blocked app disappears from the store, its connection stops receiving requests, and Cap Desktop stops loading its content. diff --git a/app-store/README.md b/app-store/README.md new file mode 100644 index 00000000000..184d8146793 --- /dev/null +++ b/app-store/README.md @@ -0,0 +1,173 @@ +# Build a Cap App + +Cap Apps add things to Cap: backgrounds and caption styles in the editor, color looks, and connections that send Caps to the tools people already use. Every app lives in this folder, and opening a pull request is how you publish one. + +People install an app once from the App Store, on the web or in Cap Desktop, and it works everywhere they use Cap. + +## Quick start + +```sh +bun install +bun app-store new my-app # content app (backgrounds, captions, looks) +bun app-store new my-app --template connection # app backed by your own server +bun app-store validate # run every check CI runs +``` + +Then edit `app-store/apps/my-app/manifest.json`, replace `icon.png` and `README.md`, and open a pull request. + +## What an app is + +A folder with a manifest, an icon and a README: + +``` +app-store/apps/my-app/ + manifest.json What the app is and what it adds + icon.png 512x512 PNG, at most 256 KB + README.md What it does and how to set it up + CHANGELOG.md Optional + ... Images the manifest references, such as backgrounds/ocean.jpg +``` + +Nothing else may be in the folder. Your editor autocompletes and checks `manifest.json` through its `$schema` line. + +## What an app can add + +### Backgrounds + +Images or gradients that appear in an Apps tab of the editor's background picker. + +```json +"backgrounds": [ + { "id": "ocean", "name": "Ocean", "image": "backgrounds/ocean.jpg" }, + { "id": "sunset", "name": "Sunset", "gradient": { "from": "#FF7E5F", "to": "#6A3093", "angle": 135 } }, + { "id": "ink", "name": "Ink", "color": "#111827" } +] +``` + +Images are PNG, JPEG or WebP, at least 1920x1080, at most 7680 pixels on a side and 8 MB each. 2560x1440 JPEG is the sweet spot: Cap renders backgrounds at up to 2560 pixels wide. Up to 24 per app. + +### Caption styles + +Presets in the editor's caption panel. Every field is required so a style always looks the same. + +```json +"captionStyles": [ + { + "id": "headline", "name": "Headline", "description": "Big and bold", + "fontWeight": 700, "size": 64, "color": "#FFFFFF", + "backgroundColor": "#000000", "backgroundOpacity": 0, + "outline": true, "outlineColor": "#000000", + "highlightColor": "#FFD43B", "activeWordHighlight": true, + "highlightStyle": "color", "animation": "pop", + "uppercase": true, "fadeDuration": 0.12 + } +] +``` + +### Color looks + +Presets in the editor's Color tab. Applying a look sets the whole grade, like Cap's built-in looks, so any value you leave out goes back to neutral. + +```json +"colorLooks": [ + { + "id": "golden-hour", "name": "Golden Hour", "description": "Warm highlights", + "values": { "contrast": 0.08, "saturation": 0.1, "temperature": 0.32, "vignette": 0.15 } + } +] +``` + +`intensity`, `fade`, `vignette` and `grain` go from 0 to 1. `exposure`, `contrast`, `saturation`, `temperature`, `tint` and `splitTone` go from -1 to 1. + +### Connections + +A connection is a server you run. Cap sends it signed requests when something happens to a Cap, and when someone runs one of your actions. You never ship UI: Cap draws your settings form and action buttons on the web and in Cap Desktop. + +```json +"privacyPolicy": "https://my-app.example.com/privacy", +"connection": { + "url": "https://my-app.example.com/cap", + "permissions": ["cap.transcript"], + "events": ["cap.ready", "cap.transcript.ready"], + "settings": [ + { "key": "apiKey", "type": "secret", "label": "API key", "required": true } + ], + "actions": [{ "id": "send", "title": "Send to My App", "target": "cap" }] +} +``` + +Cap calls three paths under `url`, always with `POST` and a JSON body: + +| Path | Body `kind` | When | +|---|---|---| +| `{url}/lifecycle` | `lifecycle` | `installed`, `settings.updated` or `uninstalled` | +| `{url}/events` | `event` | A subscribed event happened | +| `{url}/actions/{actionId}` | `action` | Someone ran your action on a Cap | + +Return any 2xx status for lifecycle and event requests. Cap retries failures with backoff for about a day, and switches a connection off if it keeps failing. Each event has a stable `id`, so use it to ignore repeats. + +For actions, reply within 10 seconds with one of: + +```json +{ "type": "toast", "message": "Sent to My App" } +{ "type": "open", "url": "https://my-app.example.com/item/123", "message": "Opening My App" } +``` + +**Events** + +| Event | Needs permission | +|---|---| +| `cap.ready` | none | +| `cap.transcript.ready` | `cap.transcript` | +| `cap.summary.ready` | `cap.summary` | +| `cap.comment.created` | `cap.comments` | + +Installed for one person, a connection hears about that person's Caps. Installed for an organization, it hears about Caps their owners shared with that organization, never private ones. + +**Permissions** decide what is in each payload. Every request includes the Cap's id, title, share link, owner name, length and creation time. `cap.transcript` adds the transcript, `cap.summary` adds the AI title, summary and chapters, and `cap.comments` adds comment text and author names. Ask only for what you use: people see this list before they install. + +**Settings** are a form Cap renders at install time. Field types are `text`, `url`, `secret`, `select` and `toggle`. Values arrive in every request as `settings`. Use `secret` for API keys and tokens: Cap encrypts them at rest and never shows them again after they are saved. + +### Verifying requests + +Every request is signed with Ed25519. Fetch Cap's public keys from `https://cap.so/.well-known/cap-app-store-keys.json` (or the same path on a self-hosted Cap), then check each request. When a request names a `kid` you do not have, fetch the keys again before refusing it. In TypeScript, copy [`packages/app-store/src/signing.ts`](../packages/app-store/src/signing.ts) and [`packages/app-store/src/constants.ts`](../packages/app-store/src/constants.ts) into your server (they only need Node's `crypto`) and call: + +```ts +import { verifyCapRequest } from "./signing"; + +const body = await request.text(); +const result = verifyCapRequest({ headers: request.headers, body, keys, appId: "my-app" }); +if (!result.ok) return new Response("Unauthorized", { status: 401 }); +``` + +Cap signs every app's requests with the same key, so always pass your `appId`: it refuses a request Cap signed for another app. Read the request kind and action from the signed body, not from headers or the URL, and ignore a `Cap-Request-Id` you have already handled, since a signed request stays valid for five minutes. + +Outside TypeScript, verify `v1.{Cap-Timestamp}.{Cap-Request-Id}.{body}` against the base64url `v1` value in `Cap-Signature` using the key whose `kid` matches, reject timestamps more than five minutes old, and check that the body's `app.id` is your app's id and its `kind` matches `Cap-Request-Kind`. + +## The rules + +CI runs `bun app-store validate` on every pull request. It checks: + +- `manifest.json` matches the schema exactly. Unknown keys are errors. +- `id` is lowercase kebab-case, 3 to 40 characters, matches the folder name and does not use the words "cap" or "official". +- `version` is `major.minor.patch` and goes up whenever anything in your folder changes. +- `name` is unique, 2 to 30 characters. `description` is one sentence of 10 to 140 characters. +- `icon.png` is exactly 512x512 and at most 256 KB. `README.md` explains what the app does and how to set it up. +- Every file in the folder is referenced by the manifest or is one of the standard files. No hidden files, symlinks or executables. +- Images are real PNG, JPEG or WebP files, inside the size limits for their slot. The folder is at most 25 MB. +- Connections use a public https URL on the default port with no query string, link a privacy policy, and ask for every permission their events need. +- Up to 20 settings and 5 actions, with unique keys and ids. + +Read [GUIDELINES.md](./GUIDELINES.md) for the rules a reviewer checks by hand. + +## Publishing and updates + +1. Open a pull request that touches only your app's folder. +2. CI validates it. A Cap maintainer reviews it against the guidelines. +3. Once merged, the app appears in the store with the next deploy of Cap. + +To update your app, change it and raise `version` in the same pull request. People get updates automatically. If an update asks for new permissions or events, Cap keeps sending only what people already approved until they review the change. + +## API versions + +`apiVersion` is the App Store API your app is written for. Cap only shows an app to clients that support its API version, so an older Cap Desktop never loads something it does not understand. Version 1 is the current API. diff --git a/app-store/apps/amazon-s3/README.md b/app-store/apps/amazon-s3/README.md new file mode 100644 index 00000000000..fec7e93f0f4 --- /dev/null +++ b/app-store/apps/amazon-s3/README.md @@ -0,0 +1,5 @@ +# Amazon S3 + +Keep every recording in a bucket you own. Works with Amazon S3 and S3-compatible storage such as Cloudflare R2, Backblaze B2 and MinIO. + +Available on Cap Pro. Set it up for yourself or, as an owner or admin, for your whole organization. diff --git a/app-store/apps/amazon-s3/icon.png b/app-store/apps/amazon-s3/icon.png new file mode 100644 index 00000000000..1b5814f1def Binary files /dev/null and b/app-store/apps/amazon-s3/icon.png differ diff --git a/app-store/apps/amazon-s3/manifest.json b/app-store/apps/amazon-s3/manifest.json new file mode 100644 index 00000000000..39c4556ce54 --- /dev/null +++ b/app-store/apps/amazon-s3/manifest.json @@ -0,0 +1,14 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "amazon-s3", + "name": "Amazon S3", + "version": "1.0.0", + "description": "Store your recordings in your own S3 or S3-compatible bucket, such as Cloudflare R2.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["storage"], + "keywords": ["bucket", "r2", "storage"], + "privacyPolicy": "https://cap.so/privacy", + "builtin": "amazon-s3" +} diff --git a/app-store/apps/aurora-backgrounds/README.md b/app-store/apps/aurora-backgrounds/README.md new file mode 100644 index 00000000000..b954a33daa7 --- /dev/null +++ b/app-store/apps/aurora-backgrounds/README.md @@ -0,0 +1,11 @@ +# Aurora + +Eight soft gradient backgrounds and two clean linear gradients, made for screen recordings. Each one is quiet enough to sit behind your content and bright enough to make it pop. + +## Use it + +1. Install Aurora from the App Store. +2. Open a recording in Cap Desktop. +3. In the Background tab, open Apps and pick a background. + +Backgrounds download once and then work offline. diff --git a/app-store/apps/aurora-backgrounds/backgrounds/dawn.jpg b/app-store/apps/aurora-backgrounds/backgrounds/dawn.jpg new file mode 100644 index 00000000000..98dad9d235c Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/dawn.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/dusk.jpg b/app-store/apps/aurora-backgrounds/backgrounds/dusk.jpg new file mode 100644 index 00000000000..5a4c5e899f9 Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/dusk.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/ember.jpg b/app-store/apps/aurora-backgrounds/backgrounds/ember.jpg new file mode 100644 index 00000000000..440adda1611 Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/ember.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/glacier.jpg b/app-store/apps/aurora-backgrounds/backgrounds/glacier.jpg new file mode 100644 index 00000000000..ee34794c7ca Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/glacier.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/lagoon.jpg b/app-store/apps/aurora-backgrounds/backgrounds/lagoon.jpg new file mode 100644 index 00000000000..a386edcb2aa Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/lagoon.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/meadow.jpg b/app-store/apps/aurora-backgrounds/backgrounds/meadow.jpg new file mode 100644 index 00000000000..0b3b9a832b5 Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/meadow.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/midnight.jpg b/app-store/apps/aurora-backgrounds/backgrounds/midnight.jpg new file mode 100644 index 00000000000..c7dfc73c1e6 Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/midnight.jpg differ diff --git a/app-store/apps/aurora-backgrounds/backgrounds/orchid.jpg b/app-store/apps/aurora-backgrounds/backgrounds/orchid.jpg new file mode 100644 index 00000000000..72249a27b27 Binary files /dev/null and b/app-store/apps/aurora-backgrounds/backgrounds/orchid.jpg differ diff --git a/app-store/apps/aurora-backgrounds/icon.png b/app-store/apps/aurora-backgrounds/icon.png new file mode 100644 index 00000000000..12ba5c22b68 Binary files /dev/null and b/app-store/apps/aurora-backgrounds/icon.png differ diff --git a/app-store/apps/aurora-backgrounds/manifest.json b/app-store/apps/aurora-backgrounds/manifest.json new file mode 100644 index 00000000000..ec123f81e30 --- /dev/null +++ b/app-store/apps/aurora-backgrounds/manifest.json @@ -0,0 +1,36 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "aurora-backgrounds", + "name": "Aurora", + "version": "1.0.0", + "description": "Ten soft, glowing gradient backgrounds that make any recording feel calm and polished.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["backgrounds"], + "keywords": ["gradient", "wallpaper", "mesh"], + "backgrounds": [ + { "id": "dawn", "name": "Dawn", "image": "backgrounds/dawn.jpg" }, + { "id": "lagoon", "name": "Lagoon", "image": "backgrounds/lagoon.jpg" }, + { "id": "ember", "name": "Ember", "image": "backgrounds/ember.jpg" }, + { "id": "meadow", "name": "Meadow", "image": "backgrounds/meadow.jpg" }, + { "id": "dusk", "name": "Dusk", "image": "backgrounds/dusk.jpg" }, + { "id": "glacier", "name": "Glacier", "image": "backgrounds/glacier.jpg" }, + { "id": "orchid", "name": "Orchid", "image": "backgrounds/orchid.jpg" }, + { + "id": "midnight", + "name": "Midnight", + "image": "backgrounds/midnight.jpg" + }, + { + "id": "sunset-fade", + "name": "Sunset Fade", + "gradient": { "from": "#FF7E5F", "to": "#6A3093", "angle": 135 } + }, + { + "id": "deep-sea", + "name": "Deep Sea", + "gradient": { "from": "#0F2027", "to": "#2C5364", "angle": 160 } + } + ] +} diff --git a/app-store/apps/discord/README.md b/app-store/apps/discord/README.md new file mode 100644 index 00000000000..464ffa5b924 --- /dev/null +++ b/app-store/apps/discord/README.md @@ -0,0 +1,13 @@ +# Discord + +Share Caps in a Discord channel. Post a single Cap from its menu, or turn on automatic posting so every new Cap lands in the channel as soon as it finishes uploading. + +## Set it up + +1. In Discord, open the channel's settings, then **Integrations**, **Webhooks**, **New Webhook**. +2. Copy the webhook URL. +3. Install Discord from the Cap App Store and paste the URL. + +## What Discord receives + +The Cap's title, share link and length. Nothing is sent until you post a Cap or turn on automatic posting. diff --git a/app-store/apps/discord/icon.png b/app-store/apps/discord/icon.png new file mode 100644 index 00000000000..09fdcb32c1d Binary files /dev/null and b/app-store/apps/discord/icon.png differ diff --git a/app-store/apps/discord/manifest.json b/app-store/apps/discord/manifest.json new file mode 100644 index 00000000000..005aac1ea6d --- /dev/null +++ b/app-store/apps/discord/manifest.json @@ -0,0 +1,36 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "discord", + "name": "Discord", + "version": "1.0.0", + "description": "Post new Caps to a Discord channel automatically, or share any Cap to Discord in one click.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["communication"], + "keywords": ["chat", "community", "notifications"], + "privacyPolicy": "https://cap.so/privacy", + "support": "https://cap.so/support", + "connection": { + "url": "/api/app-store/first-party/discord", + "events": ["cap.ready"], + "settings": [ + { + "key": "webhookUrl", + "type": "secret", + "label": "Channel webhook URL", + "description": "In Discord, open the channel's settings, then Integrations, Webhooks, New Webhook, and copy its URL.", + "placeholder": "https://discord.com/api/webhooks/...", + "required": true + }, + { + "key": "postNewCaps", + "type": "toggle", + "label": "Post every new Cap", + "description": "Share each new Cap in the channel as soon as it finishes uploading.", + "default": false + } + ], + "actions": [{ "id": "post", "title": "Post to Discord", "target": "cap" }] + } +} diff --git a/app-store/apps/film-looks/README.md b/app-store/apps/film-looks/README.md new file mode 100644 index 00000000000..0f56702bdbd --- /dev/null +++ b/app-store/apps/film-looks/README.md @@ -0,0 +1,14 @@ +# Film Looks + +Six color looks inspired by film stock. Each one is a starting point: apply it, then fine-tune any slider in the Color tab. + +- **Golden Hour**: warm highlights and soft contrast. +- **Night Shoot**: cool shadows with a teal cast. +- **Matte**: lifted blacks and muted color. +- **Noir**: high-contrast black and white. +- **Pop**: clean, punchy and colorful. +- **Super 8**: faded warmth with visible grain. + +## Use it + +Open a recording in Cap Desktop, go to the Color tab, and pick a look from the Apps row. diff --git a/app-store/apps/film-looks/icon.png b/app-store/apps/film-looks/icon.png new file mode 100644 index 00000000000..bc094940540 Binary files /dev/null and b/app-store/apps/film-looks/icon.png differ diff --git a/app-store/apps/film-looks/manifest.json b/app-store/apps/film-looks/manifest.json new file mode 100644 index 00000000000..cbf58bd5803 --- /dev/null +++ b/app-store/apps/film-looks/manifest.json @@ -0,0 +1,81 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "film-looks", + "name": "Film Looks", + "version": "1.0.0", + "description": "Six color looks inspired by film stock, from warm golden hour to cool night shoots.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["color"], + "keywords": ["grade", "lut", "cinematic"], + "colorLooks": [ + { + "id": "golden-hour", + "name": "Golden Hour", + "description": "Warm highlights and soft contrast", + "values": { + "contrast": 0.08, + "saturation": 0.1, + "temperature": 0.32, + "tint": 0.04, + "fade": 0.06, + "vignette": 0.15 + } + }, + { + "id": "night-shoot", + "name": "Night Shoot", + "description": "Cool shadows with a teal cast", + "values": { + "exposure": -0.06, + "contrast": 0.16, + "saturation": -0.08, + "temperature": -0.3, + "splitTone": 0.35, + "vignette": 0.25 + } + }, + { + "id": "matte", + "name": "Matte", + "description": "Lifted blacks and muted color", + "values": { + "contrast": -0.1, + "saturation": -0.18, + "fade": 0.35, + "grain": 0.08 + } + }, + { + "id": "noir", + "name": "Noir", + "description": "High contrast black and white", + "values": { + "contrast": 0.3, + "saturation": -1, + "vignette": 0.3, + "grain": 0.18 + } + }, + { + "id": "pop", + "name": "Pop", + "description": "Clean, punchy and colorful", + "values": { "exposure": 0.04, "contrast": 0.14, "saturation": 0.28 } + }, + { + "id": "super-8", + "name": "Super 8", + "description": "Faded warmth with visible grain", + "values": { + "contrast": -0.04, + "saturation": -0.1, + "temperature": 0.2, + "fade": 0.22, + "vignette": 0.35, + "grain": 0.4 + } + } + ] +} diff --git a/app-store/apps/google-drive/README.md b/app-store/apps/google-drive/README.md new file mode 100644 index 00000000000..174d0e74bd8 --- /dev/null +++ b/app-store/apps/google-drive/README.md @@ -0,0 +1,5 @@ +# Google Drive + +Save every recording to a Google Drive folder you choose, so your files stay with the rest of your work. + +Available on Cap Pro. Set it up for yourself or, as an owner or admin, for your whole organization. diff --git a/app-store/apps/google-drive/icon.png b/app-store/apps/google-drive/icon.png new file mode 100644 index 00000000000..15bf2fb6243 Binary files /dev/null and b/app-store/apps/google-drive/icon.png differ diff --git a/app-store/apps/google-drive/manifest.json b/app-store/apps/google-drive/manifest.json new file mode 100644 index 00000000000..aa63b04ba4f --- /dev/null +++ b/app-store/apps/google-drive/manifest.json @@ -0,0 +1,14 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "google-drive", + "name": "Google Drive", + "version": "1.0.0", + "description": "Save your recordings straight to a Google Drive folder you choose.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["storage"], + "keywords": ["drive", "google", "storage"], + "privacyPolicy": "https://cap.so/privacy", + "builtin": "google-drive" +} diff --git a/app-store/apps/slack/README.md b/app-store/apps/slack/README.md new file mode 100644 index 00000000000..9ff75fbc0ac --- /dev/null +++ b/app-store/apps/slack/README.md @@ -0,0 +1,5 @@ +# Slack + +Connect your Slack workspace and every Cap link you paste turns into a video people can play without leaving Slack. + +Your organization's owner or an admin connects Slack once for the whole workspace. diff --git a/app-store/apps/slack/icon.png b/app-store/apps/slack/icon.png new file mode 100644 index 00000000000..63d783bd561 Binary files /dev/null and b/app-store/apps/slack/icon.png differ diff --git a/app-store/apps/slack/manifest.json b/app-store/apps/slack/manifest.json new file mode 100644 index 00000000000..330f8170c17 --- /dev/null +++ b/app-store/apps/slack/manifest.json @@ -0,0 +1,14 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "slack", + "name": "Slack", + "version": "1.0.0", + "description": "Play Cap links right inside Slack with rich previews for everyone in your workspace.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["communication"], + "keywords": ["unfurl", "chat", "preview"], + "privacyPolicy": "https://cap.so/privacy", + "builtin": "slack" +} diff --git a/app-store/apps/studio-captions/README.md b/app-store/apps/studio-captions/README.md new file mode 100644 index 00000000000..1e8f9f8d836 --- /dev/null +++ b/app-store/apps/studio-captions/README.md @@ -0,0 +1,13 @@ +# Studio Captions + +Five caption styles you can apply in one click: + +- **Headline**: big, bold, uppercase, with a yellow highlight on the spoken word. +- **Whisper**: small, light subtitles that stay out of the way. +- **Neon**: a bright pink pill follows every spoken word. +- **Broadcast**: solid bar captions for talks and explainers. +- **Mint**: a fresh green highlight with a gentle bounce. + +## Use it + +Open a recording in Cap Desktop, generate captions, and pick a style from the Apps row in the caption presets. diff --git a/app-store/apps/studio-captions/icon.png b/app-store/apps/studio-captions/icon.png new file mode 100644 index 00000000000..d9a2d783eba Binary files /dev/null and b/app-store/apps/studio-captions/icon.png differ diff --git a/app-store/apps/studio-captions/manifest.json b/app-store/apps/studio-captions/manifest.json new file mode 100644 index 00000000000..5e4bb816b82 --- /dev/null +++ b/app-store/apps/studio-captions/manifest.json @@ -0,0 +1,104 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "studio-captions", + "name": "Studio Captions", + "version": "1.0.0", + "description": "Five caption styles for tutorials, social clips and talks, from quiet subtitles to bold highlights.", + "author": { "name": "Cap", "github": "CapSoftware" }, + "license": "MIT", + "categories": ["captions"], + "keywords": ["subtitles", "karaoke", "social"], + "captionStyles": [ + { + "id": "headline", + "name": "Headline", + "description": "Big, bold and uppercase with a yellow highlight", + "fontWeight": 700, + "size": 64, + "color": "#FFFFFF", + "backgroundColor": "#000000", + "backgroundOpacity": 0, + "outline": true, + "outlineColor": "#000000", + "highlightColor": "#FFD43B", + "activeWordHighlight": true, + "highlightStyle": "color", + "animation": "pop", + "uppercase": true, + "fadeDuration": 0.12 + }, + { + "id": "whisper", + "name": "Whisper", + "description": "Small, light subtitles that stay out of the way", + "fontWeight": 500, + "size": 36, + "color": "#F5F5F5", + "backgroundColor": "#000000", + "backgroundOpacity": 45, + "outline": false, + "outlineColor": "#000000", + "highlightColor": "#FFFFFF", + "activeWordHighlight": false, + "highlightStyle": "color", + "animation": "none", + "uppercase": false, + "fadeDuration": 0.25 + }, + { + "id": "neon", + "name": "Neon", + "description": "Bright pink pill on every spoken word", + "fontWeight": 700, + "size": 54, + "color": "#FFFFFF", + "backgroundColor": "#0B0B0F", + "backgroundOpacity": 70, + "outline": false, + "outlineColor": "#000000", + "highlightColor": "#FF2E93", + "activeWordHighlight": true, + "highlightStyle": "pill", + "animation": "bounce", + "uppercase": false, + "fadeDuration": 0.15 + }, + { + "id": "broadcast", + "name": "Broadcast", + "description": "Solid bar captions like the evening news", + "fontWeight": 500, + "size": 44, + "color": "#FFFFFF", + "backgroundColor": "#1A1A1A", + "backgroundOpacity": 92, + "outline": false, + "outlineColor": "#000000", + "highlightColor": "#FFFFFF", + "activeWordHighlight": false, + "highlightStyle": "color", + "animation": "none", + "uppercase": false, + "fadeDuration": 0.2 + }, + { + "id": "mint", + "name": "Mint", + "description": "Fresh green highlight with a gentle bounce", + "fontWeight": 700, + "size": 50, + "color": "#FFFFFF", + "backgroundColor": "#000000", + "backgroundOpacity": 0, + "outline": true, + "outlineColor": "#0B3D2E", + "highlightColor": "#5CF2B4", + "activeWordHighlight": true, + "highlightStyle": "color", + "animation": "bounce", + "uppercase": false, + "fadeDuration": 0.14 + } + ] +} diff --git a/app-store/blocked.json b/app-store/blocked.json new file mode 100644 index 00000000000..fe51488c706 --- /dev/null +++ b/app-store/blocked.json @@ -0,0 +1 @@ +[] diff --git a/app-store/manifest.schema.json b/app-store/manifest.schema.json new file mode 100644 index 00000000000..e4773346501 --- /dev/null +++ b/app-store/manifest.schema.json @@ -0,0 +1,826 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$defs": { + "CapAppManifest": { + "type": "object", + "required": [ + "apiVersion", + "id", + "name", + "version", + "description", + "author", + "license", + "categories" + ], + "properties": { + "$schema": { + "type": "string" + }, + "apiVersion": { + "type": "number", + "enum": [1], + "description": "The App Store API version this app is written for." + }, + "id": { + "type": "string", + "description": "Unique kebab-case id. Must match the folder name.", + "title": "maxLength(40)", + "minLength": 3, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "description": "Shown in the store. Title Case, 2 to 30 characters.", + "title": "maxLength(30)", + "minLength": 2, + "maxLength": 30 + }, + "version": { + "type": "string", + "description": "Semver like 1.2.3. Raise it whenever anything in the app folder changes.", + "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$" + }, + "description": { + "type": "string", + "description": "One sentence, 10 to 140 characters, ending with a full stop.", + "title": "maxLength(140)", + "minLength": 10, + "maxLength": 140 + }, + "author": { + "type": "object", + "required": ["name", "github"], + "properties": { + "name": { + "type": "string", + "description": "a string at most 60 character(s) long", + "title": "maxLength(60)", + "minLength": 1, + "maxLength": 60 + }, + "github": { + "type": "string", + "description": "a string matching the pattern ^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$", + "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$" + }, + "url": { + "type": "string", + "description": "a string matching the pattern ^https:\\/\\/[^\\s]+$", + "title": "maxLength(512)", + "maxLength": 512, + "pattern": "^https:\\/\\/[^\\s]+$" + } + }, + "additionalProperties": false + }, + "license": { + "type": "string", + "enum": [ + "MIT", + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "MPL-2.0", + "Unlicense", + "CC0-1.0", + "CC-BY-4.0" + ], + "description": "The license your app is published under." + }, + "categories": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "backgrounds", + "captions", + "color", + "communication", + "productivity", + "project-management", + "documentation", + "storage", + "automation", + "developer-tools", + "sales", + "education" + ] + }, + "description": "an array of at most 3 item(s)", + "title": "maxItems(3)", + "minItems": 1, + "maxItems": 3 + }, + "keywords": { + "type": "array", + "items": { + "type": "string", + "description": "a string at most 24 character(s) long", + "title": "maxLength(24)", + "minLength": 2, + "maxLength": 24 + }, + "description": "an array of at most 8 item(s)", + "title": "maxItems(8)", + "maxItems": 8 + }, + "homepage": { + "type": "string", + "description": "a string matching the pattern ^https:\\/\\/[^\\s]+$", + "title": "maxLength(512)", + "maxLength": 512, + "pattern": "^https:\\/\\/[^\\s]+$" + }, + "support": { + "type": "string", + "description": "a string matching the pattern ^https:\\/\\/[^\\s]+$", + "title": "maxLength(512)", + "maxLength": 512, + "pattern": "^https:\\/\\/[^\\s]+$" + }, + "privacyPolicy": { + "type": "string", + "description": "Required for apps with a connection, because Cap sends them data.", + "title": "maxLength(512)", + "maxLength": 512, + "pattern": "^https:\\/\\/[^\\s]+$" + }, + "screenshots": { + "type": "array", + "items": { + "type": "string", + "description": "a string matching the pattern ^(?:[a-z0-9][a-z0-9_-]*\\/)*[a-z0-9][a-z0-9_-]*\\.(?:png|jpg|jpeg|webp)$", + "pattern": "^(?:[a-z0-9][a-z0-9_-]*\\/)*[a-z0-9][a-z0-9_-]*\\.(?:png|jpg|jpeg|webp)$" + }, + "description": "an array of at most 6 item(s)", + "title": "maxItems(6)", + "maxItems": 6 + }, + "builtin": { + "type": "string", + "enum": ["slack", "amazon-s3", "google-drive"], + "description": "Only for apps published by Cap that use one of Cap's own integrations." + }, + "backgrounds": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "required": ["id", "name", "image"], + "properties": { + "id": { + "type": "string", + "description": "a string matching the pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "description": "a string at most 30 character(s) long", + "title": "maxLength(30)", + "minLength": 1, + "maxLength": 30 + }, + "image": { + "type": "string", + "description": "a string matching the pattern ^(?:[a-z0-9][a-z0-9_-]*\\/)*[a-z0-9][a-z0-9_-]*\\.(?:png|jpg|jpeg|webp)$", + "pattern": "^(?:[a-z0-9][a-z0-9_-]*\\/)*[a-z0-9][a-z0-9_-]*\\.(?:png|jpg|jpeg|webp)$" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["id", "name", "gradient"], + "properties": { + "id": { + "type": "string", + "description": "a string matching the pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "description": "a string at most 30 character(s) long", + "title": "maxLength(30)", + "minLength": 1, + "maxLength": 30 + }, + "gradient": { + "type": "object", + "required": ["from", "to", "angle"], + "properties": { + "from": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + }, + "to": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + }, + "angle": { + "$ref": "#/$defs/Int", + "description": "a number between 0 and 359", + "title": "between(0, 359)", + "minimum": 0, + "maximum": 359 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["id", "name", "color"], + "properties": { + "id": { + "type": "string", + "description": "a string matching the pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "description": "a string at most 30 character(s) long", + "title": "maxLength(30)", + "minLength": 1, + "maxLength": 30 + }, + "color": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + } + }, + "additionalProperties": false + } + ] + }, + "description": "an array of at most 24 item(s)", + "title": "maxItems(24)", + "minItems": 1, + "maxItems": 24 + }, + "captionStyles": { + "type": "array", + "items": { + "type": "object", + "required": [ + "id", + "name", + "fontWeight", + "size", + "color", + "backgroundColor", + "backgroundOpacity", + "outline", + "outlineColor", + "highlightColor", + "activeWordHighlight", + "highlightStyle", + "animation", + "uppercase", + "fadeDuration" + ], + "properties": { + "id": { + "type": "string", + "description": "a string matching the pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "description": "a string at most 30 character(s) long", + "title": "maxLength(30)", + "minLength": 1, + "maxLength": 30 + }, + "description": { + "type": "string", + "description": "a string at most 80 character(s) long", + "title": "maxLength(80)", + "minLength": 1, + "maxLength": 80 + }, + "fontWeight": { + "type": "number", + "enum": [400, 500, 700] + }, + "size": { + "$ref": "#/$defs/Int", + "description": "a number between 12 and 200", + "title": "between(12, 200)", + "minimum": 12, + "maximum": 200 + }, + "color": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + }, + "backgroundColor": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + }, + "backgroundOpacity": { + "$ref": "#/$defs/Int", + "description": "a number between 0 and 100", + "title": "between(0, 100)", + "minimum": 0, + "maximum": 100 + }, + "outline": { + "type": "boolean" + }, + "outlineColor": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + }, + "highlightColor": { + "type": "string", + "description": "a string matching the pattern ^#[0-9A-Fa-f]{6}$", + "pattern": "^#[0-9A-Fa-f]{6}$" + }, + "activeWordHighlight": { + "type": "boolean" + }, + "highlightStyle": { + "type": "string", + "enum": ["color", "pill"] + }, + "animation": { + "type": "string", + "enum": ["none", "bounce", "pop"] + }, + "uppercase": { + "type": "boolean" + }, + "fadeDuration": { + "type": "number", + "description": "a number between 0 and 1", + "title": "between(0, 1)", + "minimum": 0, + "maximum": 1 + } + }, + "additionalProperties": false + }, + "description": "an array of at most 12 item(s)", + "title": "maxItems(12)", + "minItems": 1, + "maxItems": 12 + }, + "colorLooks": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "name", "values"], + "properties": { + "id": { + "type": "string", + "description": "a string matching the pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "description": "a string at most 30 character(s) long", + "title": "maxLength(30)", + "minLength": 1, + "maxLength": 30 + }, + "description": { + "type": "string", + "description": "a string at most 80 character(s) long", + "title": "maxLength(80)", + "minLength": 1, + "maxLength": 80 + }, + "values": { + "type": "object", + "required": [], + "properties": { + "intensity": { + "type": "number", + "description": "a number between 0 and 1", + "title": "between(0, 1)", + "minimum": 0, + "maximum": 1 + }, + "exposure": { + "type": "number", + "description": "a number between -1 and 1", + "title": "between(-1, 1)", + "minimum": -1, + "maximum": 1 + }, + "contrast": { + "type": "number", + "description": "a number between -1 and 1", + "title": "between(-1, 1)", + "minimum": -1, + "maximum": 1 + }, + "saturation": { + "type": "number", + "description": "a number between -1 and 1", + "title": "between(-1, 1)", + "minimum": -1, + "maximum": 1 + }, + "temperature": { + "type": "number", + "description": "a number between -1 and 1", + "title": "between(-1, 1)", + "minimum": -1, + "maximum": 1 + }, + "tint": { + "type": "number", + "description": "a number between -1 and 1", + "title": "between(-1, 1)", + "minimum": -1, + "maximum": 1 + }, + "fade": { + "type": "number", + "description": "a number between 0 and 1", + "title": "between(0, 1)", + "minimum": 0, + "maximum": 1 + }, + "splitTone": { + "type": "number", + "description": "a number between -1 and 1", + "title": "between(-1, 1)", + "minimum": -1, + "maximum": 1 + }, + "vignette": { + "type": "number", + "description": "a number between 0 and 1", + "title": "between(0, 1)", + "minimum": 0, + "maximum": 1 + }, + "grain": { + "type": "number", + "description": "a number between 0 and 1", + "title": "between(0, 1)", + "minimum": 0, + "maximum": 1 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "description": "an array of at most 12 item(s)", + "title": "maxItems(12)", + "minItems": 1, + "maxItems": 12 + }, + "connection": { + "type": "object", + "required": ["url"], + "properties": { + "url": { + "type": "string", + "description": "Base URL of your server. Cap sends signed requests to {url}/lifecycle, {url}/events and {url}/actions/{actionId}.", + "title": "maxLength(512)", + "maxLength": 512, + "pattern": "^(?:https:\\/\\/[^\\s]+|\\/api\\/app-store\\/first-party\\/[a-z0-9-]+)$" + }, + "permissions": { + "type": "array", + "items": { + "type": "string", + "enum": ["cap.transcript", "cap.summary", "cap.comments"] + } + }, + "events": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "cap.ready", + "cap.transcript.ready", + "cap.summary.ready", + "cap.comment.created" + ] + } + }, + "settings": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "required": ["key", "label", "type"], + "properties": { + "key": { + "type": "string", + "description": "a string matching the pattern ^[a-z][a-zA-Z0-9]{0,39}$", + "pattern": "^[a-z][a-zA-Z0-9]{0,39}$" + }, + "label": { + "type": "string", + "description": "a string at most 40 character(s) long", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40 + }, + "description": { + "type": "string", + "description": "a string at most 160 character(s) long", + "title": "maxLength(160)", + "minLength": 1, + "maxLength": 160 + }, + "required": { + "type": "boolean" + }, + "type": { + "type": "string", + "enum": ["text"] + }, + "placeholder": { + "type": "string", + "description": "a string at most 80 character(s) long", + "title": "maxLength(80)", + "minLength": 1, + "maxLength": 80 + }, + "default": { + "type": "string", + "description": "a string at most 500 character(s) long", + "title": "maxLength(500)", + "maxLength": 500 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["key", "label", "type"], + "properties": { + "key": { + "type": "string", + "description": "a string matching the pattern ^[a-z][a-zA-Z0-9]{0,39}$", + "pattern": "^[a-z][a-zA-Z0-9]{0,39}$" + }, + "label": { + "type": "string", + "description": "a string at most 40 character(s) long", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40 + }, + "description": { + "type": "string", + "description": "a string at most 160 character(s) long", + "title": "maxLength(160)", + "minLength": 1, + "maxLength": 160 + }, + "required": { + "type": "boolean" + }, + "type": { + "type": "string", + "enum": ["url"] + }, + "placeholder": { + "type": "string", + "description": "a string at most 80 character(s) long", + "title": "maxLength(80)", + "minLength": 1, + "maxLength": 80 + }, + "default": { + "type": "string", + "description": "a string matching the pattern ^https:\\/\\/[^\\s]+$", + "title": "maxLength(512)", + "maxLength": 512, + "pattern": "^https:\\/\\/[^\\s]+$" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["key", "label", "type"], + "properties": { + "key": { + "type": "string", + "description": "a string matching the pattern ^[a-z][a-zA-Z0-9]{0,39}$", + "pattern": "^[a-z][a-zA-Z0-9]{0,39}$" + }, + "label": { + "type": "string", + "description": "a string at most 40 character(s) long", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40 + }, + "description": { + "type": "string", + "description": "a string at most 160 character(s) long", + "title": "maxLength(160)", + "minLength": 1, + "maxLength": 160 + }, + "required": { + "type": "boolean" + }, + "type": { + "type": "string", + "enum": ["secret"] + }, + "placeholder": { + "type": "string", + "description": "a string at most 80 character(s) long", + "title": "maxLength(80)", + "minLength": 1, + "maxLength": 80 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["key", "label", "type", "options"], + "properties": { + "key": { + "type": "string", + "description": "a string matching the pattern ^[a-z][a-zA-Z0-9]{0,39}$", + "pattern": "^[a-z][a-zA-Z0-9]{0,39}$" + }, + "label": { + "type": "string", + "description": "a string at most 40 character(s) long", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40 + }, + "description": { + "type": "string", + "description": "a string at most 160 character(s) long", + "title": "maxLength(160)", + "minLength": 1, + "maxLength": 160 + }, + "required": { + "type": "boolean" + }, + "type": { + "type": "string", + "enum": ["select"] + }, + "options": { + "type": "array", + "items": { + "type": "object", + "required": ["value", "label"], + "properties": { + "value": { + "type": "string", + "description": "a string at most 64 character(s) long", + "title": "maxLength(64)", + "minLength": 1, + "maxLength": 64 + }, + "label": { + "type": "string", + "description": "a string at most 40 character(s) long", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40 + } + }, + "additionalProperties": false + }, + "description": "an array of at most 50 item(s)", + "title": "maxItems(50)", + "minItems": 1, + "maxItems": 50 + }, + "default": { + "type": "string", + "description": "a string at most 64 character(s) long", + "title": "maxLength(64)", + "minLength": 1, + "maxLength": 64 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": ["key", "label", "type"], + "properties": { + "key": { + "type": "string", + "description": "a string matching the pattern ^[a-z][a-zA-Z0-9]{0,39}$", + "pattern": "^[a-z][a-zA-Z0-9]{0,39}$" + }, + "label": { + "type": "string", + "description": "a string at most 40 character(s) long", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40 + }, + "description": { + "type": "string", + "description": "a string at most 160 character(s) long", + "title": "maxLength(160)", + "minLength": 1, + "maxLength": 160 + }, + "type": { + "type": "string", + "enum": ["toggle"] + }, + "default": { + "type": "boolean" + } + }, + "additionalProperties": false + } + ] + }, + "description": "an array of at most 20 item(s)", + "title": "maxItems(20)", + "maxItems": 20 + }, + "actions": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "title", "target"], + "properties": { + "id": { + "type": "string", + "description": "a string matching the pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$", + "title": "maxLength(40)", + "minLength": 1, + "maxLength": 40, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "title": { + "type": "string", + "description": "a string at most 30 character(s) long", + "title": "maxLength(30)", + "minLength": 2, + "maxLength": 30 + }, + "target": { + "type": "string", + "enum": ["cap"] + } + }, + "additionalProperties": false + }, + "description": "an array of at most 5 item(s)", + "title": "maxItems(5)", + "maxItems": 5 + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false, + "description": "Describes a Cap App. See https://github.com/CapSoftware/Cap/tree/main/app-store", + "title": "Cap App manifest" + }, + "Int": { + "type": "integer", + "description": "an integer", + "title": "int" + } + }, + "$ref": "#/$defs/CapAppManifest" +} diff --git a/app-store/templates/connection/README.md b/app-store/templates/connection/README.md new file mode 100644 index 00000000000..3ba9e066df2 --- /dev/null +++ b/app-store/templates/connection/README.md @@ -0,0 +1,7 @@ +# My App + +Explain what your app does with Caps, what someone needs before they install it, and how to set it up. + +## What My App receives + +List the data your app receives and what it does with it. diff --git a/app-store/templates/connection/icon.png b/app-store/templates/connection/icon.png new file mode 100644 index 00000000000..39f6c3be2e3 Binary files /dev/null and b/app-store/templates/connection/icon.png differ diff --git a/app-store/templates/connection/manifest.json b/app-store/templates/connection/manifest.json new file mode 100644 index 00000000000..511c075dd9c --- /dev/null +++ b/app-store/templates/connection/manifest.json @@ -0,0 +1,27 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "my-app", + "name": "My App", + "version": "1.0.0", + "description": "Describe what your app does with Caps in one short sentence.", + "author": { "name": "Your Name", "github": "your-github-username" }, + "license": "MIT", + "categories": ["productivity"], + "privacyPolicy": "https://example.com/privacy", + "connection": { + "url": "https://my-app.example.com/cap", + "permissions": ["cap.transcript"], + "events": ["cap.ready", "cap.transcript.ready"], + "settings": [ + { + "key": "apiKey", + "type": "secret", + "label": "API key", + "description": "Find this in your account settings.", + "required": true + } + ], + "actions": [{ "id": "send", "title": "Send to My App", "target": "cap" }] + } +} diff --git a/app-store/templates/content/README.md b/app-store/templates/content/README.md new file mode 100644 index 00000000000..2152a5df424 --- /dev/null +++ b/app-store/templates/content/README.md @@ -0,0 +1,3 @@ +# My App + +Explain what your app adds to Cap, who it is for, and how to use it once it is installed. diff --git a/app-store/templates/content/icon.png b/app-store/templates/content/icon.png new file mode 100644 index 00000000000..39f6c3be2e3 Binary files /dev/null and b/app-store/templates/content/icon.png differ diff --git a/app-store/templates/content/manifest.json b/app-store/templates/content/manifest.json new file mode 100644 index 00000000000..a008cf29ed2 --- /dev/null +++ b/app-store/templates/content/manifest.json @@ -0,0 +1,18 @@ +{ + "$schema": "../../manifest.schema.json", + "apiVersion": 1, + "id": "my-app", + "name": "My App", + "version": "1.0.0", + "description": "Describe what your app adds to Cap in one short sentence.", + "author": { "name": "Your Name", "github": "your-github-username" }, + "license": "MIT", + "categories": ["backgrounds"], + "backgrounds": [ + { + "id": "ocean", + "name": "Ocean", + "gradient": { "from": "#0EA5E9", "to": "#1E3A8A", "angle": 135 } + } + ] +} diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index c96d36f22a2..51c3c6aa924 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -97,6 +97,7 @@ screenshot = "Bildschirmfoto" studio = "Studio" [settings.nav] +apps = "Apps" automations = "Automatisierungen" changelog = "Änderungsprotokoll" cli = "CLI" @@ -971,6 +972,7 @@ description = "Den Link zum Teilen an Slack, Discord oder Ihren eigenen Webhook name = "Slack beim Teilen benachrichtigen" [main] +app_action_done = "Fertig" delete_recording_confirm = "Möchten Sie diese Aufnahme wirklich löschen?" delete_screenshot_confirm = "Möchten Sie dieses Bildschirmfoto wirklich löschen?" @@ -2329,6 +2331,7 @@ cursor = "Cursor" keyboard = "Tastatur" [editor.sidebar.wallpaper_theme] +apps = "Apps" blue = "Blau" cities = "Städte" dark = "Dunkel" @@ -3283,4 +3286,28 @@ no_resumable_state = "Für diese Aufnahme gibt es keinen fortsetzbaren Upload" verification_failed = "Die Prüfung der Aufnahme ist fehlgeschlagen: {status}" [message.cli] -binary_missing = "Mitgelieferte CLI unter {path} nicht gefunden" \ No newline at end of file +binary_missing = "Mitgelieferte CLI unter {path} nicht gefunden" + +[settings.apps] +available_title = "Verfügbar" +browse_web = "Im Web öffnen" +description = "Fügen Sie Hintergründe, Untertitelstile, Farblooks und Verbindungen hinzu. Installierte Apps folgen Ihrem Konto ins Web und auf jedes Gerät." +empty = "Derzeit sind keine Apps verfügbar." +failed = "Der App Store konnte nicht geladen werden. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut." +install = "Installieren" +installed = "Installiert" +installed_title = "Installiert" +loading = "Apps werden geladen…" +managed_by_org = "Installiert für {organization}" +paused = "Pausiert" +platform_desktop = "Desktop" +platform_web = "Web" +remove = "Entfernen" +retry = "Erneut versuchen" +review = "Fordert mehr Zugriff an" +set_up = "Im Web einrichten" +sign_in_hint = "Melden Sie sich an, um Ihre Apps auf allen Geräten synchron zu halten und Apps zu nutzen, die sich mit anderen Diensten verbinden." +title = "Apps" + +[editor.app_store] +from_apps = "Aus Ihren Apps" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 29f268aa5c6..47cac38b4ec 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -99,6 +99,7 @@ studio = { text = "Studio", context = "Recording mode name." } [settings.nav] # The sidebar is 227px; the label gets what the 10px padding, 6px item padding, # 16px icon and 8px gap leave. +apps = { text = "Apps", max_px = 171, size = 13 } automations = { text = "Automations", max_px = 171, size = 13 } changelog = { text = "Changelog", max_px = 171, size = 13 } cli = { text = "CLI", max_px = 171, size = 13 } @@ -973,6 +974,7 @@ description = "Send the share link to Slack, Discord, or your own webhook." name = "Tell Slack when you share something" [main] +app_action_done = "Done" delete_recording_confirm = "Are you sure you want to delete this recording?" delete_screenshot_confirm = "Are you sure you want to delete this screenshot?" @@ -2331,6 +2333,7 @@ cursor = "Cursor" keyboard = "Keyboard" [editor.sidebar.wallpaper_theme] +apps = "Apps" blue = "Blue" cities = "Cities" dark = "Dark" @@ -3285,4 +3288,28 @@ no_resumable_state = "This recording has no resumable upload state" verification_failed = { text = "Recording verification failed: {status}", context = "{status} is a technical status, usually in English." } [message.cli] -binary_missing = { text = "Bundled CLI binary not found at {path}", context = "{path} is a file path." } \ No newline at end of file +binary_missing = { text = "Bundled CLI binary not found at {path}", context = "{path} is a file path." } + +[settings.apps] +available_title = "Available" +browse_web = "Open on the web" +description = "Add backgrounds, caption styles, color looks and connections. Apps you install follow your account to the web and every device." +empty = "No apps are available right now." +failed = "Could not load the App Store. Check your connection and try again." +install = "Install" +installed = "Installed" +installed_title = "Installed" +loading = "Loading apps…" +managed_by_org = { text = "Installed for {organization}", context = "{organization} is the name of the user's organization." } +paused = "Paused" +platform_desktop = "Desktop" +platform_web = "Web" +remove = "Remove" +retry = "Try again" +review = "Asks for more access" +set_up = "Set up on the web" +sign_in_hint = "Sign in to keep your apps in sync across devices and to use apps that connect to other services." +title = "Apps" + +[editor.app_store] +from_apps = "From your apps" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 27fbf306d17..3902254b51f 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -97,6 +97,7 @@ screenshot = "Captura de pantalla" studio = "Studio" [settings.nav] +apps = "Apps" automations = "Automatizaciones" changelog = "Novedades" cli = "CLI" @@ -971,6 +972,7 @@ description = "Envía el enlace para compartir a Slack, Discord o tu propio webh name = "Avisar a Slack cuando compartas algo" [main] +app_action_done = "Listo" delete_recording_confirm = "¿Seguro que quieres eliminar esta grabación?" delete_screenshot_confirm = "¿Seguro que quieres eliminar esta captura de pantalla?" @@ -2329,6 +2331,7 @@ cursor = "Cursor" keyboard = "Teclado" [editor.sidebar.wallpaper_theme] +apps = "Apps" blue = "Azul" cities = "Ciudades" dark = "Oscuro" @@ -3283,4 +3286,28 @@ no_resumable_state = "Esta grabación no tiene una subida que se pueda reanudar" verification_failed = "La verificación de la grabación ha fallado: {status}" [message.cli] -binary_missing = "No se encontró la CLI incluida en {path}" \ No newline at end of file +binary_missing = "No se encontró la CLI incluida en {path}" + +[settings.apps] +available_title = "Disponibles" +browse_web = "Abrir en la web" +description = "Añade fondos, estilos de subtítulos, looks de color y conexiones. Las apps que instalas siguen a tu cuenta en la web y en todos tus dispositivos." +empty = "No hay apps disponibles en este momento." +failed = "No se pudo cargar la App Store. Revisa tu conexión e inténtalo de nuevo." +install = "Instalar" +installed = "Instalada" +installed_title = "Instaladas" +loading = "Cargando apps…" +managed_by_org = "Instalada para {organization}" +paused = "En pausa" +platform_desktop = "Escritorio" +platform_web = "Web" +remove = "Quitar" +retry = "Reintentar" +review = "Pide más acceso" +set_up = "Configurar en la web" +sign_in_hint = "Inicia sesión para sincronizar tus apps entre dispositivos y usar apps que se conectan con otros servicios." +title = "Apps" + +[editor.app_store] +from_apps = "De tus apps" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 87b46c59460..380bd450632 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -97,6 +97,7 @@ screenshot = "Capture d'écran" studio = "Studio" [settings.nav] +apps = "Apps" automations = "Automatisations" changelog = "Nouveautés" cli = "CLI" @@ -971,6 +972,7 @@ description = "Envoyez le lien de partage à Slack, Discord ou votre propre webh name = "Prévenir Slack quand vous partagez" [main] +app_action_done = "Terminé" delete_recording_confirm = "Voulez-vous vraiment supprimer cet enregistrement ?" delete_screenshot_confirm = "Voulez-vous vraiment supprimer cette capture d'écran ?" @@ -2329,6 +2331,7 @@ cursor = "Curseur" keyboard = "Clavier" [editor.sidebar.wallpaper_theme] +apps = "Apps" blue = "Bleu" cities = "Villes" dark = "Sombre" @@ -3283,4 +3286,28 @@ no_resumable_state = "Cet enregistrement n'a pas d'envoi pouvant reprendre" verification_failed = "La vérification de l'enregistrement a échoué : {status}" [message.cli] -binary_missing = "CLI intégrée introuvable dans {path}" \ No newline at end of file +binary_missing = "CLI intégrée introuvable dans {path}" + +[settings.apps] +available_title = "Disponibles" +browse_web = "Ouvrir sur le web" +description = "Ajoutez des arrière-plans, des styles de sous-titres, des looks colorimétriques et des connexions. Les apps installées suivent votre compte sur le web et sur tous vos appareils." +empty = "Aucune app n’est disponible pour le moment." +failed = "Impossible de charger l’App Store. Vérifiez votre connexion et réessayez." +install = "Installer" +installed = "Installée" +installed_title = "Installées" +loading = "Chargement des apps…" +managed_by_org = "Installée pour {organization}" +paused = "En pause" +platform_desktop = "Bureau" +platform_web = "Web" +remove = "Retirer" +retry = "Réessayer" +review = "Demande plus d’accès" +set_up = "Configurer sur le web" +sign_in_hint = "Connectez-vous pour synchroniser vos apps entre vos appareils et utiliser les apps qui se connectent à d’autres services." +title = "Apps" + +[editor.app_store] +from_apps = "De vos apps" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 319ed6675bb..3bd551b803e 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -97,6 +97,7 @@ screenshot = "स्क्रीनशॉट" studio = "Studio" [settings.nav] +apps = "ऐप्स" automations = "ऑटोमेशन" changelog = "चेंजलॉग" cli = "CLI" @@ -971,6 +972,7 @@ description = "शेयर लिंक Slack, Discord या अपने व name = "कुछ शेयर करने पर Slack को बताएँ" [main] +app_action_done = "हो गया" delete_recording_confirm = "क्या आप वाकई यह रिकॉर्डिंग हटाना चाहते हैं?" delete_screenshot_confirm = "क्या आप वाकई यह स्क्रीनशॉट हटाना चाहते हैं?" @@ -2329,6 +2331,7 @@ cursor = "कर्सर" keyboard = "कीबोर्ड" [editor.sidebar.wallpaper_theme] +apps = "ऐप्स" blue = "नीला" cities = "शहर" dark = "डार्क" @@ -3283,4 +3286,28 @@ no_resumable_state = "इस रिकॉर्डिंग का कोई ऐ verification_failed = "रिकॉर्डिंग की जाँच विफल हुई: {status}" [message.cli] -binary_missing = "{path} पर बंडल की गई CLI नहीं मिली" \ No newline at end of file +binary_missing = "{path} पर बंडल की गई CLI नहीं मिली" + +[settings.apps] +available_title = "उपलब्ध" +browse_web = "वेब पर खोलें" +description = "बैकग्राउंड, कैप्शन स्टाइल, कलर लुक और कनेक्शन जोड़ें। आपके इंस्टॉल किए ऐप्स आपके खाते के साथ वेब और हर डिवाइस पर चलते हैं।" +empty = "अभी कोई ऐप उपलब्ध नहीं है।" +failed = "App Store लोड नहीं हो सका। अपना कनेक्शन जाँचें और फिर से कोशिश करें।" +install = "इंस्टॉल करें" +installed = "इंस्टॉल है" +installed_title = "इंस्टॉल किए गए" +loading = "ऐप्स लोड हो रहे हैं…" +managed_by_org = "{organization} के लिए इंस्टॉल किया गया" +paused = "रुका हुआ" +platform_desktop = "डेस्कटॉप" +platform_web = "वेब" +remove = "हटाएँ" +retry = "फिर से कोशिश करें" +review = "अधिक एक्सेस माँग रहा है" +set_up = "वेब पर सेट अप करें" +sign_in_hint = "अपने ऐप्स को सभी डिवाइस पर सिंक रखने और दूसरी सेवाओं से जुड़ने वाले ऐप्स इस्तेमाल करने के लिए साइन इन करें।" +title = "ऐप्स" + +[editor.app_store] +from_apps = "आपके ऐप्स से" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index d007debfd05..413ca37a637 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -97,6 +97,7 @@ screenshot = "スクリーンショット" studio = "Studio" [settings.nav] +apps = "アプリ" automations = "オートメーション" changelog = "変更履歴" cli = "CLI" @@ -971,6 +972,7 @@ description = "共有リンクをSlack、Discord、または独自のWebhookに name = "共有したらSlackに知らせる" [main] +app_action_done = "完了" delete_recording_confirm = "この録画を削除してもよろしいですか?" delete_screenshot_confirm = "このスクリーンショットを削除してもよろしいですか?" @@ -2329,6 +2331,7 @@ cursor = "カーソル" keyboard = "キーボード" [editor.sidebar.wallpaper_theme] +apps = "アプリ" blue = "ブルー" cities = "都市" dark = "ダーク" @@ -3283,4 +3286,28 @@ no_resumable_state = "この録画には再開できるアップロード状態 verification_failed = "録画の確認に失敗しました:{status}" [message.cli] -binary_missing = "{path}に同梱のCLIが見つかりません" \ No newline at end of file +binary_missing = "{path}に同梱のCLIが見つかりません" + +[settings.apps] +available_title = "利用可能" +browse_web = "Webで開く" +description = "背景、字幕スタイル、カラールック、連携を追加できます。インストールしたアプリはアカウントに紐づき、Webとすべてのデバイスで使えます。" +empty = "現在利用できるアプリはありません。" +failed = "App Storeを読み込めませんでした。接続を確認してもう一度お試しください。" +install = "インストール" +installed = "インストール済み" +installed_title = "インストール済み" +loading = "アプリを読み込んでいます…" +managed_by_org = "{organization}向けにインストール済み" +paused = "一時停止中" +platform_desktop = "デスクトップ" +platform_web = "Web" +remove = "削除" +retry = "再試行" +review = "追加のアクセスを求めています" +set_up = "Webで設定" +sign_in_hint = "サインインすると、アプリをすべてのデバイスで同期でき、他のサービスと連携するアプリも使えます。" +title = "アプリ" + +[editor.app_store] +from_apps = "インストールしたアプリ" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 922d4ee4a5d..ec6eecbfeb5 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -97,6 +97,7 @@ screenshot = "截图" studio = "Studio" [settings.nav] +apps = "应用" automations = "自动化" changelog = "更新日志" cli = "CLI" @@ -971,6 +972,7 @@ description = "将分享链接发送到 Slack、Discord 或你自己的 Webhook name = "分享内容时通知 Slack" [main] +app_action_done = "完成" delete_recording_confirm = "确定要删除这段录制吗?" delete_screenshot_confirm = "确定要删除这张截图吗?" @@ -2329,6 +2331,7 @@ cursor = "光标" keyboard = "键盘" [editor.sidebar.wallpaper_theme] +apps = "应用" blue = "蓝色" cities = "城市" dark = "深色" @@ -3283,4 +3286,28 @@ no_resumable_state = "此录制没有可继续的上传状态" verification_failed = "录制验证失败:{status}" [message.cli] -binary_missing = "未在 {path} 找到内置的 CLI 程序" \ No newline at end of file +binary_missing = "未在 {path} 找到内置的 CLI 程序" + +[settings.apps] +available_title = "可用" +browse_web = "在网页中打开" +description = "添加背景、字幕样式、色彩风格和连接。你安装的应用会跟随账户,在网页和每台设备上可用。" +empty = "目前没有可用的应用。" +failed = "无法加载 App Store。请检查网络连接后重试。" +install = "安装" +installed = "已安装" +installed_title = "已安装" +loading = "正在加载应用…" +managed_by_org = "已为 {organization} 安装" +paused = "已暂停" +platform_desktop = "桌面端" +platform_web = "网页" +remove = "移除" +retry = "重试" +review = "请求更多访问权限" +set_up = "在网页中设置" +sign_in_hint = "登录后,你的应用会在所有设备间同步,还能使用连接其他服务的应用。" +title = "应用" + +[editor.app_store] +from_apps = "来自你的应用" diff --git a/apps/desktop-gpui/src/app_store/catalog.rs b/apps/desktop-gpui/src/app_store/catalog.rs new file mode 100644 index 00000000000..80510f15b8a --- /dev/null +++ b/apps/desktop-gpui/src/app_store/catalog.rs @@ -0,0 +1,335 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const SUPPORTED_API_VERSION: u32 = 1; + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CatalogAsset { + pub url: String, + pub sha256: String, + pub bytes: u64, + pub width: u32, + pub height: u32, +} + +impl CatalogAsset { + pub fn extension(&self) -> &str { + self.url + .rsplit_once('.') + .map(|(_, extension)| extension) + .filter(|extension| matches!(*extension, "png" | "jpg" | "webp")) + .unwrap_or("bin") + } + + pub fn is_valid_hash(&self) -> bool { + self.sha256.len() == 64 && self.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Author { + pub name: String, + pub github: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum CatalogBackground { + Image { + id: String, + name: String, + image: CatalogAsset, + }, + Gradient { + id: String, + name: String, + from: String, + to: String, + angle: u16, + }, + Color { + id: String, + name: String, + color: String, + }, +} + +impl CatalogBackground { + pub fn id(&self) -> &str { + match self { + Self::Image { id, .. } | Self::Gradient { id, .. } | Self::Color { id, .. } => id, + } + } + + pub fn name(&self) -> &str { + match self { + Self::Image { name, .. } | Self::Gradient { name, .. } | Self::Color { name, .. } => { + name + } + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CaptionStyle { + pub id: String, + pub name: String, + #[serde(default)] + pub description: Option, + pub font_weight: u32, + pub size: u32, + pub color: String, + pub background_color: String, + pub background_opacity: u32, + pub outline: bool, + pub outline_color: String, + pub highlight_color: String, + pub active_word_highlight: bool, + pub highlight_style: String, + pub animation: String, + pub uppercase: bool, + pub fade_duration: f32, +} + +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct LookValues { + pub intensity: Option, + pub exposure: Option, + pub contrast: Option, + pub saturation: Option, + pub temperature: Option, + pub tint: Option, + pub fade: Option, + pub split_tone: Option, + pub vignette: Option, + pub grain: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ColorLook { + pub id: String, + pub name: String, + #[serde(default)] + pub description: Option, + pub values: LookValues, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ConnectionAction { + pub id: String, + pub title: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SettingField { + pub key: String, + #[serde(rename = "type")] + pub kind: String, + pub label: String, + #[serde(default)] + pub required: bool, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CatalogConnection { + #[serde(default)] + pub permissions: Vec, + #[serde(default)] + pub events: Vec, + #[serde(default)] + pub settings: Vec, + #[serde(default)] + pub actions: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CatalogApp { + pub api_version: u32, + pub id: String, + pub name: String, + pub version: String, + pub description: String, + pub author: Author, + pub first_party: bool, + #[serde(default)] + pub categories: Vec, + #[serde(default)] + pub keywords: Vec, + pub icon: CatalogAsset, + #[serde(default)] + pub platforms: Vec, + #[serde(default)] + pub builtin: Option, + #[serde(default)] + pub backgrounds: Vec, + #[serde(default)] + pub caption_styles: Vec, + #[serde(default)] + pub color_looks: Vec, + #[serde(default)] + pub connection: Option, + pub content_hash: String, +} + +impl CatalogApp { + #[cfg(test)] + pub fn has_content(&self) -> bool { + !self.backgrounds.is_empty() + || !self.caption_styles.is_empty() + || !self.color_looks.is_empty() + } + + #[cfg(test)] + pub fn runs_on_desktop(&self) -> bool { + self.platforms.iter().any(|platform| platform == "desktop") + } + + pub fn needs_web_setup(&self) -> bool { + self.builtin.is_some() + || self + .connection + .as_ref() + .is_some_and(|connection| connection.settings.iter().any(|field| field.required)) + } + + pub fn image_assets(&self) -> impl Iterator { + self.backgrounds + .iter() + .filter_map(|background| match background { + CatalogBackground::Image { image, .. } => Some(image), + _ => None, + }) + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Catalog { + pub revision: String, + pub apps: Vec, + pub blocked: Vec, +} + +impl Catalog { + /// Each app is read on its own, so one this build does not understand, + /// for example from a newer API version, is skipped instead of hiding the + /// whole store. + pub fn parse(value: &Value) -> Option { + let object = value.as_object()?; + if object.get("catalogVersion").and_then(Value::as_u64) != Some(1) { + return None; + } + let revision = object.get("revision")?.as_str()?.to_string(); + let blocked: Vec = object + .get("blocked") + .and_then(Value::as_array) + .map(|entries| { + entries + .iter() + .filter_map(|entry| entry.get("id").and_then(Value::as_str)) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + let apps = object + .get("apps") + .and_then(Value::as_array) + .map(|apps| { + apps.iter() + .filter_map(|app| serde_json::from_value::(app.clone()).ok()) + .filter(|app| app.api_version <= SUPPORTED_API_VERSION) + .filter(|app| !blocked.contains(&app.id)) + .collect() + }) + .unwrap_or_default(); + Some(Self { + revision, + apps, + blocked, + }) + } + + pub fn app(&self, id: &str) -> Option<&CatalogApp> { + self.apps.iter().find(|app| app.id == id) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Installation { + pub id: String, + pub app_id: String, + pub scope: String, + #[serde(default)] + pub organization_name: Option, + pub status: String, + #[serde(default)] + pub needs_review: bool, + #[serde(default)] + pub can_manage: bool, +} + +impl Installation { + pub fn is_active(&self) -> bool { + self.status == "active" + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct CachedInstallations { + pub account: String, + pub installations: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct InstallationsResponse { + pub installations: Vec, +} + +#[derive(Debug, Clone, Deserialize, PartialEq)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum ActionResult { + Toast { + message: String, + }, + Open { + url: String, + #[serde(default)] + message: Option, + }, +} + +impl ActionResult { + pub fn open_url(&self) -> Option<&str> { + match self { + Self::Open { url, .. } if url.starts_with("https://") => Some(url), + _ => None, + } + } + + pub fn message(&self) -> Option<&str> { + match self { + Self::Toast { message } => Some(message), + Self::Open { message, .. } => message.as_deref(), + } + } +} + +pub fn cap_id_from_share_url(url: &str) -> Option { + let (_, rest) = url.split_once("/s/")?; + let id = rest + .split(['?', '#', '/']) + .next() + .filter(|id| !id.is_empty())?; + id.chars() + .all(|character| character.is_ascii_alphanumeric() || character == '-' || character == '_') + .then(|| id.to_string()) +} diff --git a/apps/desktop-gpui/src/app_store/mod.rs b/apps/desktop-gpui/src/app_store/mod.rs new file mode 100644 index 00000000000..f9a54a25f43 --- /dev/null +++ b/apps/desktop-gpui/src/app_store/mod.rs @@ -0,0 +1,892 @@ +pub mod catalog; +pub mod settings_page; + +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use gpui::{App, AsyncApp, BorrowAppContext, Global, RenderImage}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; + +use crate::{auth, store}; +pub use catalog::*; + +const STORE_SECTION: &str = "appStore"; +const LOCAL_INSTALLS_KEY: &str = "localInstalls"; +const REFRESH_INTERVAL: Duration = Duration::from_secs(10 * 60); +const ICON_THUMBNAIL: u32 = 96; +const BACKGROUND_THUMBNAIL: u32 = 256; +const MAX_ASSET_BYTES: u64 = 16 * 1024 * 1024; +const CAP_ACTIONS_RETRY: Duration = Duration::from_secs(30); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SyncState { + #[default] + Idle, + Loading, + Failed, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CapAction { + pub installation_id: String, + pub app_id: String, + pub app_name: String, + pub action_id: String, + pub title: String, + pub icon_sha256: String, +} + +#[derive(Default)] +pub struct AppStore { + pub catalog: Option>, + pub installations: Vec, + pub local_installs: BTreeSet, + pub signed_in: bool, + pub state: SyncState, + pub pending: BTreeSet, + account: Option, + cap_actions: HashMap>, + cap_actions_pending: BTreeSet, + cap_actions_failed: HashMap, + assets: HashMap, + thumbnails: HashMap>, + last_refresh: Option, + generation: u64, +} + +impl Global for AppStore {} + +pub fn root_dir() -> PathBuf { + store::app_data_dir().join("app-store") +} + +fn catalog_cache_path() -> PathBuf { + root_dir().join("catalog.json") +} + +pub fn asset_path(asset: &CatalogAsset) -> Option { + asset.is_valid_hash().then(|| { + root_dir() + .join("assets") + .join(format!("{}.{}", asset.sha256, asset.extension())) + }) +} + +fn installations_cache_path() -> PathBuf { + root_dir().join("installations.json") +} + +fn current_account() -> Option { + let auth = store::auth_snapshot(); + let token = auth.token?; + Some(sha256_hex( + format!("{}\n{token}", auth::server_url()).as_bytes(), + )) +} + +fn read_cached_installations(account: &str) -> Option> { + let bytes = std::fs::read(installations_cache_path()).ok()?; + let cached: CachedInstallations = serde_json::from_slice(&bytes).ok()?; + (cached.account == account).then_some(cached.installations) +} + +fn write_cached_installations(account: &str, installations: &[Installation]) { + let path = installations_cache_path(); + let Ok(bytes) = serde_json::to_vec(&CachedInstallations { + account: account.to_string(), + installations: installations.to_vec(), + }) else { + return; + }; + if let Some(parent) = path.parent() + && std::fs::create_dir_all(parent).is_err() + { + return; + } + let temporary = path.with_extension("partial"); + if std::fs::write(&temporary, bytes).is_err() || std::fs::rename(&temporary, &path).is_err() { + tracing::warn!("Could not cache App Store installations"); + } +} + +fn read_local_installs() -> BTreeSet { + store::store_section(STORE_SECTION) + .get(LOCAL_INSTALLS_KEY) + .and_then(Value::as_array) + .map(|ids| { + ids.iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default() +} + +fn write_local_installs(ids: &BTreeSet) { + store::update_store_section(STORE_SECTION, |section| { + section.insert(LOCAL_INSTALLS_KEY.to_string(), json!(ids)); + true + }); +} + +fn read_cached_catalog() -> Option { + let bytes = std::fs::read(catalog_cache_path()).ok()?; + Catalog::parse(&serde_json::from_slice(&bytes).ok()?) +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +pub fn store_verified_asset(target: &Path, bytes: &[u8], expected: &str) -> Result<(), String> { + if sha256_hex(bytes) != expected { + return Err("downloaded asset does not match its hash".to_string()); + } + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + let temporary = target.with_extension("partial"); + std::fs::write(&temporary, bytes).map_err(|error| error.to_string())?; + std::fs::rename(&temporary, target).map_err(|error| error.to_string()) +} + +fn asset_url(server: &str, asset: &CatalogAsset) -> String { + if asset.url.starts_with("https://") || asset.url.starts_with("http://") { + asset.url.clone() + } else { + format!("{server}{}", asset.url) + } +} + +impl AppStore { + pub fn init(cx: &mut App) { + let catalog = read_cached_catalog().map(Arc::new); + let account = current_account(); + let installations = account + .as_deref() + .and_then(read_cached_installations) + .unwrap_or_default(); + let mut state = AppStore { + catalog, + installations, + account, + local_installs: read_local_installs(), + signed_in: store::auth_snapshot().token.is_some(), + ..Default::default() + }; + state.index_cached_assets(); + cx.set_global(state); + // Icons and thumbnails already on disk show at once, without waiting + // for a sync that can take two connect timeouts when the server is + // unreachable. + cx.spawn(async move |cx: &mut AsyncApp| load_assets(cx, true).await) + .detach(); + let sign_in = crate::sign_in::SignIn::global(cx); + cx.subscribe(&sign_in, |_, event, cx| { + if matches!( + event, + crate::sign_in::SignInEvent::Finished { .. } + | crate::sign_in::SignInEvent::AccountRefreshed + ) { + refresh(cx); + } + }) + .detach(); + refresh(cx); + } + + fn index_cached_assets(&mut self) { + let Some(catalog) = self.catalog.clone() else { + return; + }; + for app in &catalog.apps { + for asset in std::iter::once(&app.icon).chain(app.image_assets()) { + if let Some(path) = asset_path(asset) + && path.is_file() + { + self.assets.insert(asset.sha256.clone(), path); + } + } + } + } + + // Installs belong to the account they were fetched for. Auth can be + // cleared from several places (sign out, an upload rejecting the key), so + // they are checked against the current account instead of trusting that + // every one of those places resets the store. + pub fn account_installations(&self) -> &[Installation] { + self.installations_for(current_account().as_deref()) + } + + fn installations_for(&self, account: Option<&str>) -> &[Installation] { + match (&self.account, account) { + (Some(stored), Some(current)) if stored == current => &self.installations, + _ => &[], + } + } + + pub fn installed_ids(&self) -> BTreeSet { + let mut ids: BTreeSet = self + .account_installations() + .iter() + .filter(|installation| installation.is_active()) + .map(|installation| installation.app_id.clone()) + .collect(); + ids.extend(self.local_installs.iter().cloned()); + ids + } + + pub fn installed_apps(&self) -> Vec<&CatalogApp> { + let Some(catalog) = self.catalog.as_deref() else { + return Vec::new(); + }; + let ids = self.installed_ids(); + catalog + .apps + .iter() + .filter(|app| ids.contains(&app.id)) + .collect() + } + + pub fn asset_file(&self, asset: &CatalogAsset) -> Option<&PathBuf> { + self.assets.get(&asset.sha256) + } + + pub fn thumbnail(&self, sha256: &str) -> Option> { + self.thumbnails.get(sha256).cloned() + } + + pub fn backgrounds(&self) -> Vec<(String, CatalogBackground)> { + self.installed_apps() + .into_iter() + .flat_map(|app| { + app.backgrounds + .iter() + .filter(|background| match background { + CatalogBackground::Image { image, .. } => { + self.assets.contains_key(&image.sha256) + } + _ => true, + }) + .map(|background| (app.id.clone(), background.clone())) + }) + .collect() + } + + pub fn caption_styles(&self) -> Vec<(String, CaptionStyle)> { + self.installed_apps() + .into_iter() + .flat_map(|app| { + app.caption_styles + .iter() + .map(|style| (app.id.clone(), style.clone())) + }) + .collect() + } + + pub fn color_looks(&self) -> Vec<(String, ColorLook)> { + self.installed_apps() + .into_iter() + .flat_map(|app| { + app.color_looks + .iter() + .map(|look| (app.id.clone(), look.clone())) + }) + .collect() + } + + pub fn has_cap_actions(&self) -> bool { + self.has_cap_actions_in(self.account_installations()) + } + + fn has_cap_actions_in(&self, installations: &[Installation]) -> bool { + let Some(catalog) = self.catalog.as_deref() else { + return false; + }; + installations.iter().any(|installation| { + installation.is_active() + && catalog + .app(&installation.app_id) + .and_then(|app| app.connection.as_ref()) + .is_some_and(|connection| !connection.actions.is_empty()) + }) + } + + pub fn actions_for_cap(&self, cap_id: &str) -> Option<&Vec> { + self.cap_actions.get(cap_id) + } +} + +#[derive(Clone, Default)] +pub struct AppStoreSnapshot { + pub catalog: Option>, + pub installations: Vec, + pub local_installs: BTreeSet, + pub pending: BTreeSet, + pub signed_in: bool, + pub state: SyncState, + pub thumbnails: HashMap>, +} + +impl AppStoreSnapshot { + pub fn installation(&self, app_id: &str) -> Option<&Installation> { + self.installations + .iter() + .find(|installation| installation.app_id == app_id && installation.scope == "user") + .or_else(|| { + self.installations + .iter() + .find(|installation| installation.app_id == app_id) + }) + } + + pub fn is_installed(&self, app_id: &str) -> bool { + self.local_installs.contains(app_id) || self.installation(app_id).is_some() + } +} + +impl AppStore { + pub fn snapshot(&self) -> AppStoreSnapshot { + AppStoreSnapshot { + catalog: self.catalog.clone(), + installations: self.account_installations().to_vec(), + local_installs: self.local_installs.clone(), + pending: self.pending.clone(), + signed_in: self.signed_in, + state: self.state, + thumbnails: self.thumbnails.clone(), + } + } +} + +pub fn snapshot(cx: &App) -> AppStoreSnapshot { + cx.try_global::() + .map(AppStore::snapshot) + .unwrap_or_default() +} + +pub fn try_get(cx: &App) -> Option<&AppStore> { + cx.try_global::() +} + +pub fn refresh_if_stale(cx: &mut App) { + let stale = cx.try_global::().is_none_or(|store| { + store.state != SyncState::Loading + && store + .last_refresh + .is_none_or(|last| last.elapsed() >= REFRESH_INTERVAL) + }); + if stale { + refresh(cx); + } +} + +struct SyncResult { + catalog: Option, + installations: Option>, + account: Option, + signed_in: bool, + failed: bool, +} + +pub fn refresh(cx: &mut App) { + if !cx.has_global::() { + return; + } + let generation = cx.update_global::(|store, _| { + store.state = SyncState::Loading; + store.generation += 1; + store.generation + }); + let local = read_local_installs(); + cx.spawn(async move |cx: &mut AsyncApp| { + let task = cx.update(|cx| gpui_tokio::Tokio::spawn(cx, sync(local))); + let result = task.await.unwrap_or(SyncResult { + catalog: None, + installations: None, + account: None, + signed_in: false, + failed: true, + }); + let applied = cx.update(|cx| { + cx.update_global::(|store, _| { + if store.generation != generation { + return false; + } + if let Some(catalog) = result.catalog { + store.catalog = Some(Arc::new(catalog)); + } + if let Some(installations) = result.installations { + store.installations = installations; + store.account = result.account; + } + store.cap_actions.clear(); + store.signed_in = result.signed_in; + store.local_installs = read_local_installs(); + store.state = if result.failed { + SyncState::Failed + } else { + SyncState::Idle + }; + store.last_refresh = Some(Instant::now()); + true + }) + }); + if applied { + load_assets(cx, false).await; + } + }) + .detach(); +} + +async fn sync(local: BTreeSet) -> SyncResult { + let server = auth::server_url(); + let mut failed = false; + let catalog = match fetch_catalog(&server).await { + Ok(catalog) => catalog, + Err(error) => { + tracing::warn!(%error, "App Store catalog refresh failed"); + failed = true; + None + } + }; + let signed_in = store::auth_snapshot().token.is_some(); + let account = current_account(); + let mut installations = None; + if signed_in { + if !local.is_empty() { + adopt_local_installs(&local).await; + } + match fetch_installations().await { + Ok(list) => { + if let Some(account) = &account { + write_cached_installations(account, &list); + } + installations = Some(list); + } + Err(error) => { + tracing::warn!(%error, "App Store installations refresh failed"); + failed = true; + } + } + } else { + installations = Some(Vec::new()); + } + SyncResult { + catalog, + installations, + account, + signed_in, + failed, + } +} + +async fn fetch_catalog(server: &str) -> Result, String> { + let client = auth::api_client().map_err(|error| error.to_string())?; + let url = format!("{server}/api/app-store/catalog?apiVersion={SUPPORTED_API_VERSION}"); + let response = auth::apply_desktop_headers(client.get(url)) + .send() + .await + .map_err(|error| error.to_string())?; + if !response.status().is_success() { + return Err(format!("catalog returned {}", response.status())); + } + let bytes = response.bytes().await.map_err(|error| error.to_string())?; + let value: Value = serde_json::from_slice(&bytes).map_err(|error| error.to_string())?; + let catalog = Catalog::parse(&value).ok_or("catalog has an unknown format")?; + // A full or read-only disk only costs the offline copy: the catalog that + // just arrived is still the one to show. + let path = catalog_cache_path(); + let temporary = path.with_extension("partial"); + let cached = path + .parent() + .is_none_or(|parent| std::fs::create_dir_all(parent).is_ok()) + && std::fs::write(&temporary, &bytes).is_ok() + && std::fs::rename(&temporary, &path).is_ok(); + if !cached { + let _ = std::fs::remove_file(&temporary); + tracing::warn!("Could not cache the App Store catalog"); + } + Ok(Some(catalog)) +} + +async fn fetch_installations() -> Result, String> { + let response = auth::authed_request(reqwest::Method::GET, "/api/app-store/installations", None) + .await + .map_err(|error| error.to_string())?; + if !response.status().is_success() { + return Err(format!("installations returned {}", response.status())); + } + let body: InstallationsResponse = response.json().await.map_err(|error| error.to_string())?; + Ok(body.installations) +} + +async fn adopt_local_installs(local: &BTreeSet) { + let mut kept = BTreeSet::new(); + for app_id in local { + let response = auth::authed_request( + reqwest::Method::POST, + "/api/app-store/installations", + Some(json!({ "appId": app_id, "scope": "user" })), + ) + .await; + match response { + Ok(response) + if response.status().is_success() + || response.status() == reqwest::StatusCode::CONFLICT + || response.status() == reqwest::StatusCode::NOT_FOUND => {} + _ => { + kept.insert(app_id.clone()); + } + } + } + write_local_installs(&kept); +} + +async fn load_assets(cx: &mut AsyncApp, cached_only: bool) { + let Some((catalog, installed, known)) = cx.update(|cx| { + cx.try_global::().and_then(|store| { + store.catalog.clone().map(|catalog| { + ( + catalog, + store.installed_ids(), + store.thumbnails.keys().cloned().collect::>(), + ) + }) + }) + }) else { + return; + }; + let server = auth::server_url(); + let mut wanted: Vec<(CatalogAsset, u32)> = Vec::new(); + for app in &catalog.apps { + wanted.push((app.icon.clone(), ICON_THUMBNAIL)); + if installed.contains(&app.id) { + for image in app.image_assets() { + wanted.push((image.clone(), BACKGROUND_THUMBNAIL)); + } + } + } + wanted.retain(|(asset, _)| !known.contains(&asset.sha256)); + if wanted.is_empty() { + return; + } + let task = cx.update(|cx| { + gpui_tokio::Tokio::spawn(cx, async move { + let client = auth::api_client().ok()?; + let mut loaded = Vec::new(); + for (asset, size) in wanted { + if asset.bytes > MAX_ASSET_BYTES { + continue; + } + let Some(path) = asset_path(&asset) else { + continue; + }; + if !path.is_file() { + if cached_only { + continue; + } + let response = auth::apply_desktop_headers(client.get(asset_url(&server, &asset))) + .send() + .await; + let Ok(response) = response else { continue }; + if !response.status().is_success() { + continue; + } + let Ok(bytes) = response.bytes().await else { + continue; + }; + if let Err(error) = store_verified_asset(&path, &bytes, &asset.sha256) { + tracing::warn!(%error, sha256 = %asset.sha256, "Rejected an App Store asset"); + continue; + } + } + let thumbnail = crate::editor_sidebar::decode_scaled_rgba(&path, size) + .map(crate::library::rgba_to_render_image); + loaded.push((asset.sha256.clone(), path, thumbnail)); + } + Some(loaded) + }) + }); + let Ok(Some(loaded)) = task.await else { + return; + }; + cx.update(|cx| { + cx.update_global::(|store, _| { + for (sha256, path, thumbnail) in loaded { + store.assets.insert(sha256.clone(), path); + if let Some(thumbnail) = thumbnail { + store.thumbnails.insert(sha256, thumbnail); + } + } + }); + }); +} + +#[derive(Debug, Clone, PartialEq)] +pub enum InstallOutcome { + Installed, + OpenedWeb, +} + +pub fn install(app_id: String, cx: &mut App) -> Option { + let store = cx.try_global::()?; + let app = store.catalog.as_deref()?.app(&app_id)?.clone(); + let signed_in = store::auth_snapshot().token.is_some(); + if app.needs_web_setup() || (app.connection.is_some() && !signed_in) { + cx.open_url(&format!("{}/dashboard/apps/{}", auth::server_url(), app.id)); + return Some(InstallOutcome::OpenedWeb); + } + if !signed_in { + let mut local = read_local_installs(); + local.insert(app.id.clone()); + write_local_installs(&local); + cx.update_global::(|store, _| store.local_installs = local); + refresh(cx); + return Some(InstallOutcome::Installed); + } + cx.update_global::(|store, _| { + store.pending.insert(app.id.clone()); + }); + let id = app.id.clone(); + cx.spawn(async move |cx: &mut AsyncApp| { + let body = json!({ "appId": id, "scope": "user" }); + let task = cx.update(|cx| { + gpui_tokio::Tokio::spawn(cx, async move { + auth::authed_request( + reqwest::Method::POST, + "/api/app-store/installations", + Some(body), + ) + .await + .map(|response| response.status()) + }) + }); + let status = task.await.ok().and_then(Result::ok); + if !status.is_some_and(|status| status.is_success() || status.as_u16() == 409) { + tracing::warn!(?status, app = %id, "App Store install failed"); + } + cx.update(|cx| { + cx.update_global::(|store, _| { + store.pending.remove(&id); + }); + refresh(cx); + }); + }) + .detach(); + Some(InstallOutcome::Installed) +} + +pub fn uninstall(app_id: String, cx: &mut App) { + let Some(store) = cx.try_global::() else { + return; + }; + let was_local = store.local_installs.contains(&app_id); + let installation = store + .account_installations() + .iter() + .find(|installation| { + installation.app_id == app_id && installation.scope == "user" && installation.can_manage + }) + .cloned(); + if was_local { + let mut local = read_local_installs(); + local.remove(&app_id); + write_local_installs(&local); + cx.update_global::(|store, _| store.local_installs = local); + } + let Some(installation) = installation else { + return; + }; + cx.update_global::(|store, _| { + store.pending.insert(app_id.clone()); + }); + cx.spawn(async move |cx: &mut AsyncApp| { + let path = format!("/api/app-store/installations/{}", installation.id); + let task = cx.update(|cx| { + gpui_tokio::Tokio::spawn(cx, async move { + auth::authed_request(reqwest::Method::DELETE, &path, None) + .await + .map(|response| response.status()) + }) + }); + let status = task.await.ok().and_then(Result::ok); + if !status.is_some_and(|status| status.is_success()) { + tracing::warn!(?status, app = %app_id, "App Store uninstall failed"); + } + cx.update(|cx| { + cx.update_global::(|store, _| { + store.pending.remove(&app_id); + }); + refresh(cx); + }); + }) + .detach(); +} + +pub fn account_changed(cx: &mut App) { + if !cx.has_global::() { + return; + } + cx.update_global::(|store, _| { + store.installations.clear(); + store.account = None; + store.cap_actions.clear(); + store.cap_actions_pending.clear(); + store.cap_actions_failed.clear(); + }); + refresh(cx); +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct ServerCapAction { + installation_id: String, + app_id: String, + app_name: String, + action_id: String, + title: String, +} + +#[derive(serde::Deserialize)] +struct ServerCapActions { + actions: Vec, +} + +pub fn request_cap_actions(cap_ids: Vec, cx: &mut App) { + let Some(store) = cx.try_global::() else { + return; + }; + if !store.has_cap_actions() { + return; + } + let wanted: Vec = cap_ids + .into_iter() + .filter(|id| { + !store.cap_actions.contains_key(id) + && !store.cap_actions_pending.contains(id) + && store + .cap_actions_failed + .get(id) + .is_none_or(|failed| failed.elapsed() >= CAP_ACTIONS_RETRY) + }) + .collect(); + if wanted.is_empty() { + return; + } + let icons: HashMap = store + .catalog + .as_deref() + .map(|catalog| { + catalog + .apps + .iter() + .map(|app| (app.id.clone(), app.icon.sha256.clone())) + .collect() + }) + .unwrap_or_default(); + cx.update_global::(|store, _| { + store.cap_actions_pending.extend(wanted.iter().cloned()); + }); + let requested = wanted.clone(); + cx.spawn(async move |cx: &mut AsyncApp| { + let task = cx.update(|cx| { + gpui_tokio::Tokio::spawn(cx, async move { + let mut loaded = Vec::new(); + for cap_id in wanted { + let path = format!("/api/app-store/caps/{cap_id}/actions"); + let actions = + match auth::authed_request(reqwest::Method::GET, &path, None).await { + Ok(response) if response.status().is_success() => response + .json::() + .await + .ok() + .map(|body| body.actions), + _ => None, + }; + loaded.push((cap_id, actions)); + } + loaded + }) + }); + let loaded = task.await.unwrap_or_else(|_| { + requested + .iter() + .map(|cap_id| (cap_id.clone(), None)) + .collect() + }); + cx.update(|cx| { + cx.update_global::(|store, _| { + for cap_id in &requested { + store.cap_actions_pending.remove(cap_id); + } + for (cap_id, actions) in loaded { + let Some(actions) = actions else { + store.cap_actions_failed.insert(cap_id, Instant::now()); + continue; + }; + store.cap_actions_failed.remove(&cap_id); + store.cap_actions.insert( + cap_id, + actions + .into_iter() + .map(|action| CapAction { + icon_sha256: icons.get(&action.app_id).cloned().unwrap_or_default(), + installation_id: action.installation_id, + app_id: action.app_id, + app_name: action.app_name, + action_id: action.action_id, + title: action.title, + }) + .collect(), + ); + } + }); + }); + }) + .detach(); +} + +pub async fn run_cap_action(action: CapAction, cap_id: String) -> Result { + let path = format!("/api/app-store/caps/{cap_id}/actions"); + let response = auth::authed_request( + reqwest::Method::POST, + &path, + Some(json!({ + "installationId": action.installation_id, + "actionId": action.action_id, + })), + ) + .await + .map_err(|error| error.to_string())?; + let status = response.status(); + let body = response.bytes().await.map_err(|error| error.to_string())?; + read_action_response(status, &body) +} + +// A proxy or gateway in front of Cap can answer with an HTML page, so a body +// that is not JSON reads as no body instead of surfacing the decoder's error. +pub(crate) fn read_action_response( + status: reqwest::StatusCode, + body: &[u8], +) -> Result { + let body: Value = serde_json::from_slice(body).unwrap_or(Value::Null); + if !status.is_success() { + return Err(body + .get("error") + .and_then(Value::as_str) + .unwrap_or("The app could not complete this action") + .to_string()); + } + serde_json::from_value(body.get("result").cloned().unwrap_or(Value::Null)) + .map_err(|_| "The app sent a response Cap could not read".to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/apps/desktop-gpui/src/app_store/settings_page.rs b/apps/desktop-gpui/src/app_store/settings_page.rs new file mode 100644 index 00000000000..933a3bfbfa2 --- /dev/null +++ b/apps/desktop-gpui/src/app_store/settings_page.rs @@ -0,0 +1,280 @@ +use gpui::prelude::*; +use gpui::{AnyElement, Context, SharedString, div, img, px}; + +use super::{AppStoreSnapshot, CatalogApp, SyncState}; +use crate::i18n::tr; +use crate::settings_window::SettingsWindow; +use crate::{auth, store, ui}; + +impl SettingsWindow { + pub(crate) fn render_apps(&self, cx: &mut Context) -> Vec { + let theme = self.theme; + let browse = self + .button( + "apps-open-web", + (ui::ButtonVariant::Outline, None), + tr::settings::apps::browse_web(), + false, + cx, + |_, _, cx| cx.open_url(&format!("{}/dashboard/apps", auth::server_url())), + ) + .into_any_element(); + + let state = super::snapshot(cx); + + let Some(catalog) = state.catalog.clone() else { + let (message, retry) = match state.state { + SyncState::Failed => (tr::settings::apps::failed(), true), + _ => (tr::settings::apps::loading(), false), + }; + let mut card = self.card(true).flex().flex_col().gap(px(10.)).child( + div() + .text_size(px(12.)) + .text_color(theme.settings_muted()) + .child(message), + ); + if retry { + card = card.child(self.button( + "apps-retry", + (ui::ButtonVariant::Outline, None), + tr::settings::apps::retry(), + false, + cx, + |_, _, cx| super::refresh(cx), + )); + } + return vec![ + self.section( + tr::settings::apps::title(), + Some(tr::settings::apps::description()), + Some(browse), + vec![card.into_any_element()], + ) + .into_any_element(), + ]; + }; + + let (installed, available): (Vec<&CatalogApp>, Vec<&CatalogApp>) = catalog + .apps + .iter() + .partition(|app| state.is_installed(&app.id)); + + let mut sections = Vec::new(); + let mut intro = Vec::new(); + if !state.signed_in { + intro.push( + div() + .text_size(px(12.)) + .text_color(theme.settings_muted()) + .child(tr::settings::apps::sign_in_hint()) + .into_any_element(), + ); + } + sections.push( + self.section( + tr::settings::apps::title(), + Some(tr::settings::apps::description()), + Some(browse), + intro, + ) + .into_any_element(), + ); + + if !installed.is_empty() { + let rows = installed + .iter() + .map(|app| self.app_row(app, &state, cx)) + .collect(); + sections.push( + self.section( + tr::settings::apps::installed_title(), + None, + None, + vec![self.rows(rows).into_any_element()], + ) + .into_any_element(), + ); + } + + if available.is_empty() && installed.is_empty() { + sections.push( + self.card(true) + .text_size(px(12.)) + .text_color(theme.settings_muted()) + .child(tr::settings::apps::empty()) + .into_any_element(), + ); + } else if !available.is_empty() { + let rows = available + .iter() + .map(|app| self.app_row(app, &state, cx)) + .collect(); + sections.push( + self.section( + tr::settings::apps::available_title(), + None, + None, + vec![self.rows(rows).into_any_element()], + ) + .into_any_element(), + ); + } + + sections + } + + fn app_row( + &self, + app: &CatalogApp, + state: &AppStoreSnapshot, + cx: &mut Context, + ) -> AnyElement { + let theme = self.theme; + let id = app.id.clone(); + let pending = state.pending.contains(&app.id); + let installation = state.installation(&app.id); + let local = state.local_installs.contains(&app.id); + let installed = local || installation.is_some(); + let removable = local + || installation.is_some_and(|installation| { + installation.scope == "user" && installation.can_manage + }); + let org_name = installation + .filter(|installation| installation.scope == "organization") + .and_then(|installation| installation.organization_name.clone()); + let paused = installation.is_some_and(|installation| !installation.is_active()); + let needs_review = installation.is_some_and(|installation| installation.needs_review); + + let icon = state.thumbnails.get(&app.icon.sha256).cloned(); + let author = if app.first_party { + "Cap".to_string() + } else { + app.author.name.clone() + }; + let platforms = app + .platforms + .iter() + .map(|platform| match platform.as_str() { + "web" => tr::settings::apps::platform_web(), + _ => tr::settings::apps::platform_desktop(), + }) + .collect::>() + .join(" · "); + + let status: Option = if paused { + Some(tr::settings::apps::paused().into()) + } else if needs_review { + Some(tr::settings::apps::review().into()) + } else { + org_name.map(|organization| tr::settings::apps::managed_by_org(&organization).into()) + }; + + let action: AnyElement = if installed { + if removable && !pending { + let remove_id = id.clone(); + self.button( + SharedString::from(format!("app-remove-{id}")), + (ui::ButtonVariant::Outline, None), + tr::settings::apps::remove(), + false, + cx, + move |_, _, cx| super::uninstall(remove_id.clone(), cx), + ) + .into_any_element() + } else { + div() + .text_size(px(12.)) + .text_color(theme.settings_muted()) + .child(tr::settings::apps::installed()) + .into_any_element() + } + } else { + let label = if app.needs_web_setup() + || (app.connection.is_some() && store::auth_snapshot().token.is_none()) + { + tr::settings::apps::set_up() + } else { + tr::settings::apps::install() + }; + let install_id = id.clone(); + self.button( + SharedString::from(format!("app-install-{id}")), + (ui::ButtonVariant::Primary, None), + label, + pending, + cx, + move |_, _, cx| { + super::install(install_id.clone(), cx); + }, + ) + .into_any_element() + }; + + div() + .flex() + .flex_row() + .items_center() + .gap(px(12.)) + .px(px(14.)) + .py(px(12.)) + .child( + div() + .size(px(36.)) + .flex_shrink_0() + .rounded(px(8.)) + .overflow_hidden() + .bg(theme.settings_fill()) + // A dark icon would otherwise vanish into a dark card. + .border_1() + .border_color(theme.settings_border()) + .children(icon.map(|icon| img(icon).size_full().rounded(px(8.)))), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(2.)) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(6.)) + .child( + div() + .text_size(px(13.)) + .text_color(theme.settings_text()) + .child(app.name.clone()), + ) + .child( + div() + .text_size(px(11.)) + .text_color(theme.settings_muted()) + .child(author), + ), + ) + .child( + div() + .text_size(px(12.)) + .line_height(px(16.)) + .text_color(theme.settings_muted()) + .child(app.description.clone()), + ) + .child( + div() + .text_size(px(11.)) + .text_color(theme.settings_muted()) + .child(match status { + Some(status) => { + SharedString::from(format!("{platforms} · {status}")) + } + None => SharedString::from(platforms), + }), + ), + ) + .child(div().flex_shrink_0().child(action)) + .into_any_element() + } +} diff --git a/apps/desktop-gpui/src/app_store/tests.rs b/apps/desktop-gpui/src/app_store/tests.rs new file mode 100644 index 00000000000..49f593f1ea6 --- /dev/null +++ b/apps/desktop-gpui/src/app_store/tests.rs @@ -0,0 +1,238 @@ +use super::*; + +const GOLDEN: &str = + include_str!("../../../../packages/app-store/test/fixtures/catalog.golden.json"); + +fn golden() -> Catalog { + Catalog::parse(&serde_json::from_str(GOLDEN).expect("golden catalog is JSON")) + .expect("golden catalog parses") +} + +#[test] +fn parses_the_catalog_the_web_app_builds() { + let catalog = golden(); + assert_eq!(catalog.apps.len(), 2); + + let content = catalog.app("fixture-content").expect("content app"); + assert!(content.has_content()); + assert!(content.runs_on_desktop()); + assert!(!content.needs_web_setup()); + assert_eq!(content.backgrounds.len(), 3); + assert!(matches!( + content.backgrounds[0], + CatalogBackground::Image { ref image, .. } if image.is_valid_hash() && image.extension() == "jpg" + )); + assert!(matches!( + content.backgrounds[1], + CatalogBackground::Gradient { angle: 135, .. } + )); + assert!(matches!( + content.backgrounds[2], + CatalogBackground::Color { .. } + )); + assert_eq!(content.caption_styles[0].highlight_style, "pill"); + assert_eq!(content.color_looks[0].values.temperature, Some(0.3)); + assert_eq!(content.color_looks[0].values.split_tone, Some(-0.1)); + assert_eq!(content.color_looks[0].values.exposure, None); + + let connection = catalog.app("fixture-connection").expect("connection app"); + assert!(connection.needs_web_setup()); + let details = connection.connection.as_ref().expect("connection"); + assert_eq!(details.actions[0].id, "send"); + assert_eq!(details.settings.len(), 3); + assert!(details.settings[0].required); +} + +#[test] +fn skips_apps_it_cannot_read_and_blocked_apps() { + let mut value: Value = serde_json::from_str(GOLDEN).unwrap(); + let apps = value["apps"].as_array_mut().unwrap(); + let mut future = apps[0].clone(); + future["id"] = json!("from-the-future"); + future["apiVersion"] = json!(99); + apps.push(future); + let mut broken = apps[0].clone(); + broken["id"] = json!("broken"); + broken["icon"] = json!("not an asset"); + apps.push(broken); + value["blocked"] = json!([{ "id": "fixture-connection", "reason": "test" }]); + + let catalog = Catalog::parse(&value).unwrap(); + let ids: Vec<&str> = catalog.apps.iter().map(|app| app.id.as_str()).collect(); + assert_eq!(ids, ["fixture-content"]); + assert_eq!(catalog.blocked, ["fixture-connection"]); +} + +#[test] +fn rejects_unknown_catalog_versions() { + assert!(Catalog::parse(&json!({ "catalogVersion": 2, "revision": "x", "apps": [] })).is_none()); + assert!(Catalog::parse(&json!([])).is_none()); +} + +#[test] +fn reads_cap_ids_from_share_links() { + assert_eq!( + cap_id_from_share_url("https://cap.so/s/abc123def456ghi").as_deref(), + Some("abc123def456ghi") + ); + assert_eq!( + cap_id_from_share_url("https://team.example.com/s/abc123?t=10").as_deref(), + Some("abc123") + ); + assert_eq!(cap_id_from_share_url("https://cap.so/dashboard"), None); + assert_eq!(cap_id_from_share_url("https://cap.so/s/"), None); + assert_eq!(cap_id_from_share_url("https://cap.so/s/..%2f"), None); +} + +#[test] +fn only_stores_assets_that_match_their_hash() { + let dir = std::env::temp_dir().join(format!("cap-app-store-test-{}", std::process::id())); + let target = dir.join("asset.png"); + let bytes = b"hello world"; + let expected = sha256_hex(bytes); + assert_eq!( + expected, + "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9" + ); + assert!(store_verified_asset(&target, b"tampered", &expected).is_err()); + assert!(!target.exists()); + store_verified_asset(&target, bytes, &expected).unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), bytes); + assert!(!target.with_extension("partial").exists()); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn asset_paths_only_come_from_valid_hashes() { + let mut asset = CatalogAsset { + url: "/app-store/x/abc.jpg".into(), + sha256: "f".repeat(64), + bytes: 1, + width: 1, + height: 1, + }; + let path = asset_path(&asset).unwrap(); + assert!(path.ends_with(format!("{}.jpg", "f".repeat(64)))); + asset.sha256 = "../../etc/passwd".into(); + assert!(asset_path(&asset).is_none()); + asset.sha256 = "f".repeat(64); + asset.url = "/app-store/x/abc.exe".into(); + assert!( + asset_path(&asset) + .unwrap() + .to_string_lossy() + .ends_with(".bin") + ); +} + +#[test] +fn action_results_only_open_https() { + let open: ActionResult = + serde_json::from_value(json!({ "type": "open", "url": "https://example.com/x" })).unwrap(); + assert_eq!(open.open_url(), Some("https://example.com/x")); + let unsafe_open: ActionResult = + serde_json::from_value(json!({ "type": "open", "url": "file:///etc/passwd" })).unwrap(); + assert_eq!(unsafe_open.open_url(), None); + let toast: ActionResult = + serde_json::from_value(json!({ "type": "toast", "message": "Posted" })).unwrap(); + assert_eq!(toast.message(), Some("Posted")); + assert!(serde_json::from_value::(json!({ "type": "html" })).is_err()); +} + +#[test] +fn action_responses_that_are_not_json_read_as_plain_failures() { + use reqwest::StatusCode; + let gateway = b"Bad gateway"; + assert_eq!( + read_action_response(StatusCode::BAD_GATEWAY, gateway), + Err("The app could not complete this action".to_string()) + ); + assert_eq!( + read_action_response(StatusCode::OK, gateway), + Err("The app sent a response Cap could not read".to_string()) + ); + assert_eq!( + read_action_response( + StatusCode::BAD_GATEWAY, + br#"{"error":"Discord rejected the post"}"# + ), + Err("Discord rejected the post".to_string()) + ); + assert_eq!( + read_action_response( + StatusCode::OK, + br#"{"result":{"type":"toast","message":"Posted"}}"# + ), + Ok(ActionResult::Toast { + message: "Posted".to_string() + }) + ); +} + +#[test] +fn contributions_come_only_from_installed_apps() { + let catalog = golden(); + let mut store = AppStore { + catalog: Some(Arc::new(catalog)), + ..Default::default() + }; + assert!(store.backgrounds().is_empty()); + assert!(store.caption_styles().is_empty()); + assert!(!store.has_cap_actions_in(&[])); + + store.local_installs.insert("fixture-content".into()); + let backgrounds = store.backgrounds(); + assert_eq!( + backgrounds + .iter() + .map(|(_, background)| background.id()) + .collect::>(), + ["sunset", "ink"], + "the image waits until its file is downloaded and verified" + ); + assert_eq!(store.caption_styles().len(), 1); + assert_eq!(store.color_looks().len(), 1); + + store.installations.push(Installation { + id: "inst_1".into(), + app_id: "fixture-connection".into(), + scope: "user".into(), + organization_name: None, + status: "active".into(), + needs_review: false, + can_manage: true, + }); + assert!(store.installations_for(Some("account-a")).is_empty()); + store.account = Some("account-a".into()); + assert_eq!(store.installations_for(Some("account-a")).len(), 1); + assert!( + store.installations_for(Some("account-b")).is_empty(), + "installs never leak to another account" + ); + assert!(store.installations_for(None).is_empty()); + assert!(store.has_cap_actions_in(store.installations_for(Some("account-a")))); + + store.installations[0].status = "disabled".into(); + assert!(!store.has_cap_actions_in(store.installations_for(Some("account-a")))); +} + +#[test] +fn installation_cache_round_trips_for_its_account() { + let installation = Installation { + id: "inst_1".into(), + app_id: "fixture-content".into(), + scope: "organization".into(), + organization_name: Some("Acme".into()), + status: "active".into(), + needs_review: false, + can_manage: false, + }; + let cached = CachedInstallations { + account: "account-a".into(), + installations: vec![installation.clone()], + }; + let parsed: CachedInstallations = + serde_json::from_slice(&serde_json::to_vec(&cached).unwrap()).unwrap(); + assert_eq!(parsed.installations, vec![installation]); + assert_eq!(parsed.account, "account-a"); +} diff --git a/apps/desktop-gpui/src/assets.rs b/apps/desktop-gpui/src/assets.rs index dd5b0b22cc7..51199e2de3c 100644 --- a/apps/desktop-gpui/src/assets.rs +++ b/apps/desktop-gpui/src/assets.rs @@ -44,6 +44,7 @@ const ICONS: &[(&str, &[u8])] = assets!("icons": "app-window.svg", "ban.svg", "globe.svg", + "grid.svg", "area.svg", "arrows.svg", "audio-on.svg", diff --git a/apps/desktop-gpui/src/editor_color.rs b/apps/desktop-gpui/src/editor_color.rs index 62fb4bcc69c..12018581ad1 100644 --- a/apps/desktop-gpui/src/editor_color.rs +++ b/apps/desktop-gpui/src/editor_color.rs @@ -445,6 +445,73 @@ pub fn preset_preview(preset: &ColorPreset, width: u32, height: u32) -> Arc GradeValues { + let bipolar = |value: Option| value.unwrap_or(0.).clamp(-1., 1.); + let unipolar = |value: Option| value.unwrap_or(0.).clamp(0., 1.); + GradeValues { + intensity: values.intensity.unwrap_or(1.).clamp(0., 1.), + exposure: bipolar(values.exposure), + contrast: bipolar(values.contrast), + saturation: bipolar(values.saturation), + temperature: bipolar(values.temperature), + tint: bipolar(values.tint), + fade: unipolar(values.fade), + split_tone: bipolar(values.split_tone), + vignette: unipolar(values.vignette), + grain: unipolar(values.grain), + } +} + +pub fn look_filters(values: &GradeValues) -> Vec { + let amount = |value: f32| value * values.intensity; + let temperature = amount(values.temperature); + let mut filters = vec![ + Filter::Brightness(1. + amount(values.exposure) * 0.5), + Filter::Contrast(1. + amount(values.contrast) - amount(values.fade) * 0.25), + Filter::Saturate((1. + amount(values.saturation)).max(0.)), + ]; + if temperature > 0. { + filters.push(Filter::Sepia(temperature * 0.5)); + } + let hue = (if temperature < 0. { + temperature * 25. + } else { + 0. + }) - amount(values.tint) * 12.; + if hue.abs() > f32::EPSILON { + filters.push(Filter::HueRotate(hue)); + } + filters +} + +fn app_look_image(key: &str, values: &GradeValues) -> Arc { + static CACHE: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); + let mut cache = CACHE.lock().unwrap_or_else(|error| error.into_inner()); + if let Some((_, _, image)) = cache + .iter() + .find(|(cached_key, cached_values, _)| cached_key == key && cached_values == values) + { + return image.clone(); + } + let rgba = cap_gpui_kernels::texture::preset_preview_bgra( + &look_filters(values), + None, + values.vignette * values.intensity, + values.grain, + PREVIEW_WIDTH, + PREVIEW_HEIGHT, + ); + let image = Arc::new(RenderImage::new(smallvec::smallvec![image::Frame::new( + rgba + )])); + if cache.len() >= 64 { + cache.remove(0); + } + cache.push((key.to_string(), *values, image.clone())); + image +} + // --------------------------------------------------------------------------- // Wiring // --------------------------------------------------------------------------- @@ -476,12 +543,21 @@ impl EditorWindow { let Some(preset) = COLOR_CORRECTION_PRESETS.get(index) else { return; }; - let values = preset.values; - let id = preset.id; + self.apply_color_values(target, preset.id.to_string(), preset.values, window, cx); + } + + fn apply_color_values( + &mut self, + target: GradeTarget, + id: String, + values: GradeValues, + window: &mut Window, + cx: &mut Context, + ) { self.edit_project("color-preset", window, cx, move |project| { let grade = Self::grade_mut(project, target); let next = ColorCorrection { - preset: id.to_string(), + preset: id, intensity: values.intensity, exposure: values.exposure, contrast: values.contrast, @@ -625,17 +701,117 @@ impl EditorWindow { }), ); - let mut section = div() - .flex() - .flex_col() - .gap(px(14.)) - .child(ui::Field::section(&theme, tr::editor::color::title()).child(tiles)) - .child(self.slider_field( - GradeSlider::Grain.label(), - crate::editor_sidebar::SliderKey::Grade(target, GradeSlider::Grain), - "%", - cx, - )); + let app_looks: Vec<(String, SharedString, Option, GradeValues)> = + crate::app_store::try_get(cx) + .map(|store| { + store + .color_looks() + .into_iter() + .map(|(app_id, look)| { + ( + format!("app:{app_id}:{}", look.id), + SharedString::from(look.name), + look.description.map(SharedString::from), + look_grade(&look.values), + ) + }) + .collect() + }) + .unwrap_or_default(); + let mut field = ui::Field::section(&theme, tr::editor::color::title()).child(tiles); + if !app_looks.is_empty() { + field = field + .child( + div() + .pt(px(4.)) + .text_size(px(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.gray_10)) + .child(tr::editor::app_store::from_apps()), + ) + .child( + div().flex().flex_row().flex_wrap().gap(px(8.)).children( + app_looks + .into_iter() + .map(|(id, name, description, values)| { + let selected = active == id; + let image = app_look_image(&id, &values); + let apply_id = id.clone(); + div() + .id(SharedString::from(format!("grade-{}-{id}", target.key()))) + .w(px(122.)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(6.)) + .rounded(px(8.)) + .bg(self.panel_bg()) + .border_1() + .border_color(if selected { + Hsla::from(theme.blue_9) + } else { + Hsla::from(theme.gray_3) + }) + .when(selected, |this| { + this.shadow(vec![gpui::BoxShadow { + color: Hsla::from(theme.blue_9), + offset: gpui::point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(1.), + inset: false, + }]) + }) + .child( + div() + .w_full() + .h(px(60.75)) + .rounded(px(6.)) + .overflow_hidden() + .child( + img(image) + .size_full() + .object_fit(gpui::ObjectFit::Fill), + ), + ) + .child( + div() + .px(px(2.)) + .text_size(px(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.gray_12)) + .child(name), + ) + .when_some(description, |this, description| { + this.tooltip(move |_window, cx| { + ui::Tooltip::new(&theme, description.clone()).view(cx) + }) + }) + .on_click(cx.listener(move |this, _, window, cx| { + this.apply_color_values( + target, + apply_id.clone(), + values, + window, + cx, + ); + })) + }), + ), + ); + } + + let mut section = + div() + .flex() + .flex_col() + .gap(px(14.)) + .child(field) + .child(self.slider_field( + GradeSlider::Grain.label(), + crate::editor_sidebar::SliderKey::Grade(target, GradeSlider::Grain), + "%", + cx, + )); // `` (`:151`). if target == GradeTarget::Screen { diff --git a/apps/desktop-gpui/src/editor_sidebar.rs b/apps/desktop-gpui/src/editor_sidebar.rs index bfe920dfe79..c776d1504a3 100644 --- a/apps/desktop-gpui/src/editor_sidebar.rs +++ b/apps/desktop-gpui/src/editor_sidebar.rs @@ -64,6 +64,7 @@ use crate::{ }; mod animated_gradient; +mod app_backgrounds; mod cursor; // --------------------------------------------------------------------------- @@ -2011,7 +2012,7 @@ impl EditorWindow { /// Decode an image for a thumbnail slot, at most `max` pixels on its longest /// side. The same rule as `library::decode_thumbnail`: the atlas would /// otherwise hold a multi-megapixel original per tile. -fn decode_scaled_rgba(path: &Path, max: u32) -> Option { +pub(crate) fn decode_scaled_rgba(path: &Path, max: u32) -> Option { let bytes = std::fs::read(path).ok()?; let format = image::guess_format(&bytes).ok()?; let (decoded, width, height) = if format == image::ImageFormat::Jpeg { @@ -2250,7 +2251,9 @@ impl EditorWindow { /// near-free, and a cold theme batch takes one image's latency instead of /// eighteen), landing in batches of whatever has finished per notify. fn ensure_wallpapers(&mut self, window: &mut Window, cx: &mut Context) { - let theme = BACKGROUND_THEMES[self.sidebar.wallpaper_theme].0; + let Some((theme, _)) = BACKGROUND_THEMES.get(self.sidebar.wallpaper_theme) else { + return; + }; let wanted: Vec<&'static str> = wallpapers_for_theme(theme) .into_iter() .filter(|id| !self.sidebar.wallpapers.contains_key(id)) @@ -3022,7 +3025,15 @@ impl EditorWindow { fn render_wallpaper_pane(&self, cx: &mut Context) -> impl IntoElement { let theme = self.theme; - let selected_theme = self.sidebar.wallpaper_theme; + let app_tiles = app_backgrounds::app_background_tiles(cx); + let selected_theme = if self.sidebar.wallpaper_theme == app_backgrounds::APPS_THEME + && app_tiles.is_empty() + { + 0 + } else { + self.sidebar.wallpaper_theme + }; + let apps_selected = selected_theme == app_backgrounds::APPS_THEME; let selected_id = match &self.project.background.source { BackgroundSource::Wallpaper { path: Some(path) } if !is_current_desktop_background_path(Some(path)) => @@ -3031,7 +3042,10 @@ impl EditorWindow { } _ => None, }; - let ids = wallpapers_for_theme(BACKGROUND_THEMES[selected_theme].0); + let ids = BACKGROUND_THEMES + .get(selected_theme) + .map(|(id, _)| wallpapers_for_theme(id)) + .unwrap_or_default(); // Floored, with a pixel to spare: a cell that divides the pane exactly // wraps the last tile onto its own row. let cell = ((CONTENT_WIDTH - WALLPAPER_GAP * (WALLPAPER_COLUMNS - 1.)) / WALLPAPER_COLUMNS) @@ -3086,9 +3100,39 @@ impl EditorWindow { this.ensure_wallpapers(window, cx); cx.notify(); })) - }), + }) + .chain((!app_tiles.is_empty()).then(|| { + div() + .id("wallpaper-theme-apps") + .flex() + .flex_1() + .justify_center() + .items_center() + .h(px(24.)) + .px(px(8.)) + .rounded(px(6.)) + .font_weight(FontWeight::MEDIUM) + .when(apps_selected, |this| { + this.bg(Hsla::from(theme.editor.ctl_hover)) + .text_color(Hsla::from(theme.editor.text_1)) + }) + .when(!apps_selected, |this| { + this.text_color(Hsla::from(theme.editor.text_2)) + .cursor_pointer() + .hover(|this| this.bg(Hsla::from(theme.editor.ctl))) + }) + .child(tr::editor::sidebar::wallpaper_theme::apps()) + .on_click(cx.listener(|this, _, _window, cx| { + this.sidebar.wallpaper_theme = app_backgrounds::APPS_THEME; + crate::app_store::refresh_if_stale(cx); + cx.notify(); + })) + })), ), ) + .when(apps_selected, |this| { + this.child(self.render_app_backgrounds(app_tiles, cell, cx)) + }) .child( div() .flex() diff --git a/apps/desktop-gpui/src/editor_sidebar/app_backgrounds.rs b/apps/desktop-gpui/src/editor_sidebar/app_backgrounds.rs new file mode 100644 index 00000000000..8636adea0a3 --- /dev/null +++ b/apps/desktop-gpui/src/editor_sidebar/app_backgrounds.rs @@ -0,0 +1,287 @@ +use gpui::App; + +use super::*; +use crate::app_store::{CatalogBackground, try_get}; + +pub(super) const APPS_THEME: usize = BACKGROUND_THEMES.len(); + +pub(super) struct AppBackgroundTile { + key: String, + background: CatalogBackground, + path: Option, + thumbnail: Option>, +} + +fn rgb(hex: &str) -> Option { + hex_to_rgb(hex).map(|[r, g, b, _]| [u16::from(r), u16::from(g), u16::from(b)]) +} + +fn hsla(hex: &str) -> Hsla { + hex_to_rgb(hex) + .map(|rgba| Hsla::from(gpui::rgba(u32::from_be_bytes(rgba)))) + .unwrap_or_else(gpui::transparent_black) +} + +pub(super) fn app_background_tiles(cx: &App) -> Vec { + let Some(store) = try_get(cx) else { + return Vec::new(); + }; + store + .backgrounds() + .into_iter() + .map(|(app_id, background)| { + let (path, thumbnail) = match &background { + CatalogBackground::Image { image, .. } => ( + store.asset_file(image).cloned(), + store.thumbnail(&image.sha256), + ), + _ => (None, None), + }; + AppBackgroundTile { + key: format!("{app_id}-{}", background.id()), + background, + path, + thumbnail, + } + }) + .collect() +} + +fn is_selected(source: &BackgroundSource, tile: &AppBackgroundTile) -> bool { + match (&tile.background, source) { + (CatalogBackground::Image { .. }, BackgroundSource::Wallpaper { path: Some(path) }) => tile + .path + .as_ref() + .is_some_and(|tile_path| tile_path.to_string_lossy() == path.as_str()), + ( + CatalogBackground::Gradient { + from, to, angle, .. + }, + BackgroundSource::Gradient { + from: current_from, + to: current_to, + angle: current_angle, + .. + }, + ) => { + rgb(from).as_ref() == Some(current_from) + && rgb(to).as_ref() == Some(current_to) + && angle == current_angle + } + (CatalogBackground::Color { color, .. }, BackgroundSource::Color { value, .. }) => { + rgb(color).as_ref() == Some(value) + } + _ => false, + } +} + +impl EditorWindow { + pub(super) fn render_app_backgrounds( + &self, + tiles: Vec, + cell: f32, + cx: &mut Context, + ) -> gpui::Div { + let theme = self.theme; + let source = self.project.background.source.clone(); + div() + .flex() + .flex_row() + .flex_wrap() + .gap(px(WALLPAPER_GAP)) + .children(tiles.into_iter().map(|tile| { + let selected = is_selected(&source, &tile); + let name = SharedString::from(tile.background.name().to_string()); + let fill = match &tile.background { + CatalogBackground::Image { .. } => div() + .size_full() + .rounded(px(6.)) + .overflow_hidden() + .bg(Hsla::from(theme.editor.ctl_hover)) + .children(tile.thumbnail.clone().map(|image| { + img(image) + .size_full() + .object_fit(gpui::ObjectFit::Cover) + .rounded(px(6.)) + })), + CatalogBackground::Gradient { + from, to, angle, .. + } => div().size_full().rounded(px(6.)).bg(linear_gradient( + f32::from(*angle), + linear_color_stop(hsla(from), 0.), + linear_color_stop(hsla(to), 1.), + )), + CatalogBackground::Color { color, .. } => { + div().size_full().rounded(px(6.)).bg(hsla(color)) + } + }; + let background = tile.background.clone(); + let path = tile.path.clone(); + div() + .id(SharedString::from(format!("app-background-{}", tile.key))) + .w(px(cell)) + .h(px(WALLPAPER_TILE_HEIGHT + 2. * (RING_WIDTH + RING_GAP))) + .rounded(px(8.)) + .cursor_pointer() + .selection_ring(self.panel_bg(), theme.editor.accent, selected) + .child(fill) + .tooltip(move |_window, cx| ui::Tooltip::new(&theme, name.clone()).view(cx)) + .on_click(cx.listener(move |this, _, window, cx| { + this.apply_app_background(&background, path.clone(), window, cx); + })) + })) + } + + fn apply_app_background( + &mut self, + background: &CatalogBackground, + path: Option, + window: &mut Window, + cx: &mut Context, + ) { + match background { + CatalogBackground::Image { .. } => { + let Some(path) = path.filter(|path| path.is_file()) else { + tracing::warn!("App background is not downloaded yet"); + return; + }; + self.set_wallpaper_source(path.to_string_lossy().into_owned(), window, cx); + } + CatalogBackground::Gradient { + from, to, angle, .. + } => { + let (Some(from), Some(to)) = (rgb(from), rgb(to)) else { + return; + }; + let angle = *angle; + self.edit_background( + "app-gradient", + move |project| { + project.background.source = BackgroundSource::Gradient { + from, + to, + angle, + noise_intensity: None, + noise_scale: None, + animated: None, + animation_speed: None, + }; + true + }, + window, + cx, + ); + self.ensure_preview(window, cx); + } + CatalogBackground::Color { color, .. } => { + let Some(value) = rgb(color) else { + return; + }; + self.edit_background( + "app-color", + move |project| { + project.background.source = BackgroundSource::Color { value, alpha: 255 }; + true + }, + window, + cx, + ); + self.ensure_preview(window, cx); + } + } + if self.ensure_background_presentation(false) { + self.project_changed(window, cx); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tile(background: CatalogBackground, path: Option<&str>) -> AppBackgroundTile { + AppBackgroundTile { + key: "app-x".into(), + background, + path: path.map(PathBuf::from), + thumbnail: None, + } + } + + #[test] + fn app_backgrounds_are_selected_by_what_they_apply() { + let gradient = tile( + CatalogBackground::Gradient { + id: "g".into(), + name: "G".into(), + from: "#FF7E5F".into(), + to: "#6A3093".into(), + angle: 135, + }, + None, + ); + let applied = BackgroundSource::Gradient { + from: [255, 126, 95], + to: [106, 48, 147], + angle: 135, + noise_intensity: None, + noise_scale: None, + animated: None, + animation_speed: None, + }; + assert!(is_selected(&applied, &gradient)); + let other_angle = BackgroundSource::Gradient { + from: [255, 126, 95], + to: [106, 48, 147], + angle: 90, + noise_intensity: None, + noise_scale: None, + animated: None, + animation_speed: None, + }; + assert!(!is_selected(&other_angle, &gradient)); + + let image = tile( + CatalogBackground::Image { + id: "i".into(), + name: "I".into(), + image: crate::app_store::CatalogAsset { + url: "/app-store/x/a.jpg".into(), + sha256: "a".repeat(64), + bytes: 1, + width: 1, + height: 1, + }, + }, + Some("/tmp/a.jpg"), + ); + assert!(is_selected( + &BackgroundSource::Wallpaper { + path: Some("/tmp/a.jpg".into()) + }, + &image + )); + assert!(!is_selected( + &BackgroundSource::Wallpaper { + path: Some("/tmp/b.jpg".into()) + }, + &image + )); + + let color = tile( + CatalogBackground::Color { + id: "c".into(), + name: "C".into(), + color: "#111827".into(), + }, + None, + ); + assert!(is_selected( + &BackgroundSource::Color { + value: [17, 24, 39], + alpha: 255 + }, + &color + )); + } +} diff --git a/apps/desktop-gpui/src/editor_tabs.rs b/apps/desktop-gpui/src/editor_tabs.rs index 61b1dd8d43b..7c527d075d2 100644 --- a/apps/desktop-gpui/src/editor_tabs.rs +++ b/apps/desktop-gpui/src/editor_tabs.rs @@ -276,6 +276,66 @@ pub struct CaptionPreset { pub fade_duration: f32, } +#[derive(Debug, Clone, PartialEq)] +pub struct CaptionPresetValues { + pub id: String, + pub font_weight: u32, + pub size: u32, + pub color: String, + pub background_color: String, + pub background_opacity: u32, + pub outline: bool, + pub outline_color: String, + pub highlight_color: String, + pub active_word_highlight: bool, + pub highlight_style: String, + pub animation: String, + pub uppercase: bool, + pub fade_duration: f32, +} + +impl From<&CaptionPreset> for CaptionPresetValues { + fn from(preset: &CaptionPreset) -> Self { + Self { + id: preset.id.to_string(), + font_weight: preset.font_weight, + size: preset.size, + color: preset.color.to_string(), + background_color: preset.background_color.to_string(), + background_opacity: preset.background_opacity, + outline: preset.outline, + outline_color: preset.outline_color.to_string(), + highlight_color: preset.highlight_color.to_string(), + active_word_highlight: preset.active_word_highlight, + highlight_style: preset.highlight_style.to_string(), + animation: preset.animation.to_string(), + uppercase: preset.uppercase, + fade_duration: preset.fade_duration, + } + } +} + +impl CaptionPresetValues { + pub fn from_app(app_id: &str, style: &crate::app_store::CaptionStyle) -> Self { + Self { + id: format!("app:{app_id}:{}", style.id), + font_weight: style.font_weight, + size: style.size, + color: style.color.clone(), + background_color: style.background_color.clone(), + background_opacity: style.background_opacity.min(100), + outline: style.outline, + outline_color: style.outline_color.clone(), + highlight_color: style.highlight_color.clone(), + active_word_highlight: style.active_word_highlight, + highlight_style: style.highlight_style.clone(), + animation: style.animation.clone(), + uppercase: style.uppercase, + fade_duration: style.fade_duration.clamp(0., 1.), + } + } +} + pub static CAPTION_PRESETS: &[CaptionPreset] = &[ CaptionPreset { id: "classic", @@ -3406,13 +3466,25 @@ impl EditorWindow { ) -> AnyElement { let theme = self.theme; let active = settings.preset.clone(); + let app_styles: Vec<(CaptionPresetValues, SharedString, Option)> = + crate::app_store::try_get(cx) + .map(|store| { + store + .caption_styles() + .into_iter() + .map(|(app_id, style)| { + ( + CaptionPresetValues::from_app(&app_id, &style), + SharedString::from(style.name), + style.description.map(SharedString::from), + ) + }) + .collect() + }) + .unwrap_or_default(); - div() - .flex() - .flex_row() - .flex_wrap() - .gap(px(8.)) - .children(CAPTION_PRESETS.iter().enumerate().map(|(index, preset)| { + let built_in = div().flex().flex_row().flex_wrap().gap(px(8.)).children( + CAPTION_PRESETS.iter().enumerate().map(|(index, preset)| { let selected = active == preset.id; div() .id(SharedString::from(format!("caption-preset-{}", preset.id))) @@ -3440,7 +3512,7 @@ impl EditorWindow { inset: false, }]) }) - .child(self.caption_preset_preview(preset)) + .child(self.caption_preset_preview(&CaptionPresetValues::from(preset))) .child( div() .px(px(2.)) @@ -3456,20 +3528,91 @@ impl EditorWindow { .on_click(cx.listener(move |this, _, window, cx| { this.apply_caption_preset(index, window, cx); })) - })) + }), + ); + + if app_styles.is_empty() { + return built_in.into_any_element(); + } + + let from_apps = + div() + .flex() + .flex_row() + .flex_wrap() + .gap(px(8.)) + .children(app_styles.into_iter().map(|(values, name, description)| { + let selected = active == values.id; + let preview = self.caption_preset_preview(&values); + div() + .id(SharedString::from(format!("caption-preset-{}", values.id))) + .w(px(187.)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(6.)) + .rounded(px(8.)) + .bg(self.panel_bg()) + .border_1() + .border_color(if selected { + Hsla::from(theme.blue_9) + } else { + Hsla::from(theme.gray_3) + }) + .when(selected, |this| { + this.shadow(vec![gpui::BoxShadow { + color: Hsla::from(theme.blue_9), + offset: gpui::point(px(0.), px(0.)), + blur_radius: px(0.), + spread_radius: px(1.), + inset: false, + }]) + }) + .child(preview) + .child( + div() + .px(px(2.)) + .text_size(px(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.gray_12)) + .child(name.clone()), + ) + .when_some(description, |this, description| { + this.tooltip(move |_window, cx| { + ui::Tooltip::new(&theme, description.clone()).view(cx) + }) + }) + .on_click(cx.listener(move |this, _, window, cx| { + this.apply_caption_values(values.clone(), window, cx); + })) + })); + + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(built_in) + .child( + div() + .text_size(px(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.gray_10)) + .child(tr::editor::app_store::from_apps()), + ) + .child(from_apps) .into_any_element() } /// `CaptionPresetPreview` (`CaptionsTab.tsx:182-238`). - fn caption_preset_preview(&self, preset: &CaptionPreset) -> AnyElement { + fn caption_preset_preview(&self, preset: &CaptionPresetValues) -> AnyElement { let words = ["Make", "it", "pop"]; - let color = crate::editor_sidebar::hex_to_rgb(preset.color) + let color = crate::editor_sidebar::hex_to_rgb(&preset.color) .map(|rgba| gpui::rgba(u32::from_be_bytes(rgba))) .unwrap_or_else(|| gpui::rgba(0xffffffff)); - let highlight = crate::editor_sidebar::hex_to_rgb(preset.highlight_color) + let highlight = crate::editor_sidebar::hex_to_rgb(&preset.highlight_color) .map(|rgba| gpui::rgba(u32::from_be_bytes(rgba))) .unwrap_or_else(|| gpui::rgba(0xffffffff)); - let background = crate::editor_sidebar::hex_to_rgb(preset.background_color) + let background = crate::editor_sidebar::hex_to_rgb(&preset.background_color) .map(|rgba| { let mut colour = Hsla::from(gpui::rgba(u32::from_be_bytes(rgba))); colour.a = preset.background_opacity as f32 / 100.; @@ -3530,6 +3673,15 @@ impl EditorWindow { let Some(preset) = CAPTION_PRESETS.get(index) else { return; }; + self.apply_caption_values(CaptionPresetValues::from(preset), window, cx); + } + + fn apply_caption_values( + &mut self, + preset: CaptionPresetValues, + window: &mut Window, + cx: &mut Context, + ) { self.edit_project("caption-preset", window, cx, move |project| { // Unlike the keyboard tab, the source's caption setters bail when // there is no captions block. `applyCaptionPreset` goes through the @@ -3538,18 +3690,18 @@ impl EditorWindow { return false; }; let settings = &mut captions.settings; - settings.preset = preset.id.to_string(); + settings.preset = preset.id; settings.font_weight = preset.font_weight; settings.size = preset.size; - settings.color = preset.color.to_string(); - settings.background_color = preset.background_color.to_string(); + settings.color = preset.color; + settings.background_color = preset.background_color; settings.background_opacity = preset.background_opacity; settings.outline = preset.outline; - settings.outline_color = preset.outline_color.to_string(); - settings.highlight_color = preset.highlight_color.to_string(); + settings.outline_color = preset.outline_color; + settings.highlight_color = preset.highlight_color; settings.active_word_highlight = preset.active_word_highlight; - settings.highlight_style = preset.highlight_style.to_string(); - settings.animation = preset.animation.to_string(); + settings.highlight_style = preset.highlight_style; + settings.animation = preset.animation; settings.uppercase = preset.uppercase; settings.fade_duration = preset.fade_duration; true diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index d19371448c6..de9d5aadef1 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -2018,6 +2018,14 @@ struct OpenTextMenu { impl EditorWindow { pub fn new(project_path: PathBuf, window: &mut Window, cx: &mut Context) -> Self { crate::theme::bind_window(window, cx); + if cx.has_global::() { + cx.observe_global_in::(window, |_, window, cx| { + cx.notify(); + window.refresh(); + }) + .detach(); + crate::app_store::refresh_if_stale(cx); + } cx.observe_window_activation(window, |this, window, cx| { if !window.is_window_active() { if let Some(crop) = this.crop.as_mut() diff --git a/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs b/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs index 7a4d1de8bcc..12972350f8f 100644 --- a/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_panels_surface_tests.rs @@ -481,6 +481,7 @@ fn editor_panels_match_the_literals_they_replaced() { (tr::editor::sidebar::source::animated(), "Animated"), (tr::editor::sidebar::source::none(), "None"), (tr::editor::sidebar::wallpaper_theme::dark(), "Dark"), + (tr::editor::sidebar::wallpaper_theme::apps(), "Apps"), (tr::editor::sidebar::wallpaper_theme::blue(), "Blue"), (tr::editor::sidebar::wallpaper_theme::cities(), "Cities"), (tr::editor::sidebar::wallpaper_theme::purple(), "Purple"), diff --git a/apps/desktop-gpui/src/i18n/surface_tests.rs b/apps/desktop-gpui/src/i18n/surface_tests.rs index 1ef8b8d6d4f..aee6a43dc56 100644 --- a/apps/desktop-gpui/src/i18n/surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/surface_tests.rs @@ -174,6 +174,7 @@ fn main_surfaces_match_the_literals_they_replaced() { tr::main::delete_recording_confirm(), "Are you sure you want to delete this recording?", ), + (tr::main::app_action_done(), "Done"), ( tr::main::delete_screenshot_confirm(), "Are you sure you want to delete this screenshot?", diff --git a/apps/desktop-gpui/src/i18n/tests.rs b/apps/desktop-gpui/src/i18n/tests.rs index 94539acfa56..0ea3e96ba70 100644 --- a/apps/desktop-gpui/src/i18n/tests.rs +++ b/apps/desktop-gpui/src/i18n/tests.rs @@ -107,7 +107,27 @@ fn english_matches_the_literals_it_replaced() { (tr::settings::nav::experimental(), "Experimental".into()), (tr::settings::nav::feedback(), "Feedback".into()), (tr::settings::nav::general(), "General".into()), + (tr::settings::nav::apps(), "Apps".into()), (tr::settings::nav::integrations(), "Integrations".into()), + (tr::settings::apps::available_title(), "Available".into()), + (tr::settings::apps::browse_web(), "Open on the web".into()), + (tr::settings::apps::description(), "Add backgrounds, caption styles, color looks and connections. Apps you install follow your account to the web and every device.".into()), + (tr::settings::apps::empty(), "No apps are available right now.".into()), + (tr::settings::apps::failed(), "Could not load the App Store. Check your connection and try again.".into()), + (tr::settings::apps::install(), "Install".into()), + (tr::settings::apps::installed(), "Installed".into()), + (tr::settings::apps::installed_title(), "Installed".into()), + (tr::settings::apps::loading(), "Loading apps…".into()), + (tr::settings::apps::paused(), "Paused".into()), + (tr::settings::apps::platform_desktop(), "Desktop".into()), + (tr::settings::apps::platform_web(), "Web".into()), + (tr::settings::apps::remove(), "Remove".into()), + (tr::settings::apps::retry(), "Try again".into()), + (tr::settings::apps::review(), "Asks for more access".into()), + (tr::settings::apps::set_up(), "Set up on the web".into()), + (tr::settings::apps::sign_in_hint(), "Sign in to keep your apps in sync across devices and to use apps that connect to other services.".into()), + (tr::settings::apps::title(), "Apps".into()), + (tr::editor::app_store::from_apps(), "From your apps".into()), (tr::settings::nav::license(), "Plan & license".into()), (tr::settings::nav::quality(), "Recording quality".into()), (tr::settings::nav::recordings(), "Recordings".into()), @@ -517,8 +537,9 @@ fn english_matches_the_literals_it_replaced() { }) .count() // `tray.version`, `excluded_windows.missing_body`, `self_host.confirm_change`, - // `menu.update.badge_progress` and `menu.update.badge_version` take arguments. - - 5; + // `menu.update.badge_progress`, `menu.update.badge_version` and + // `settings.apps.managed_by_org` take arguments. + - 6; assert_eq!( pairs.len(), plain_keys, diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index acdd53da302..03053292f6b 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -4,6 +4,7 @@ #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] mod app_sounds; +mod app_store; mod app_windows; mod assets; mod auth; @@ -407,6 +408,7 @@ fn main() { let session = RecordingSession::init(cx); crate::sign_in::SignIn::init(cx); crate::feeds::Feeds::init(cx); + crate::app_store::AppStore::init(cx); crate::media_access::MediaAccess::init(cx); crate::target_overlay::TargetSelect::init(cx); diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs index 928b64406e1..ba69fdaeeb0 100644 --- a/apps/desktop-gpui/src/main_window.rs +++ b/apps/desktop-gpui/src/main_window.rs @@ -945,6 +945,8 @@ pub struct MainWindow { mode: Mode, mode_hover: ModeHoverState, mode_hover_task: Option>, + app_action_notice: Option<(std::path::PathBuf, SharedString)>, + app_action_task: Option>, mode_hover_bounds: [Rc>>>; 3], target: Option, devices: DeviceSnapshot, @@ -1048,6 +1050,10 @@ impl MainWindow { cx: &mut Context, ) -> Self { crate::theme::bind_window(window, cx); + if cx.has_global::() { + cx.observe_global_in::(window, |_, _, cx| cx.notify()) + .detach(); + } window.on_window_should_close(cx, |_, cx| { // The custom Windows X hides to the tray; native close requests must still quit. #[cfg(target_os = "windows")] @@ -1246,6 +1252,8 @@ impl MainWindow { mode: Mode::from_store(), mode_hover: ModeHoverState::default(), mode_hover_task: None, + app_action_notice: None, + app_action_task: None, mode_hover_bounds: std::array::from_fn(|_| Rc::new(Cell::new(None))), target: None, devices: DeviceSnapshot::default(), @@ -4984,6 +4992,51 @@ impl MainWindow { let path = item.path.clone(); let mode = item.mode; let sharing = item.sharing.clone(); + if let Some((notice_path, message)) = &self.app_action_notice + && notice_path == &path + { + // An app's error can be longer than the card is wide: show its + // start with an ellipsis and the whole message on hover. + let theme = self.theme; + let full = message.clone(); + return div() + .h(px(26.)) + .flex() + .items_center() + .justify_center() + .px(px(6.)) + .text_size(px(11.)) + .text_color(self.theme.gray_11) + .overflow_hidden() + .child( + div() + .id(SharedString::from(format!( + "lib-rec-app-notice-{}", + path.display() + ))) + .min_w_0() + .truncate() + .tooltip(move |_, cx| ui::Tooltip::new(&theme, full.clone()).view(cx)) + .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY) + .child(message.clone()), + ); + } + let app_actions = sharing + .as_deref() + .and_then(crate::app_store::cap_id_from_share_url) + .and_then(|cap_id| { + let store = crate::app_store::try_get(cx)?; + if !store.has_cap_actions() { + return None; + } + let Some(actions) = store.actions_for_cap(&cap_id).cloned() else { + let pending = cap_id.clone(); + cx.defer(move |cx| crate::app_store::request_cap_actions(vec![pending], cx)); + return None; + }; + let icons = crate::app_store::snapshot(cx).thumbnails; + Some((cap_id, actions, icons)) + }); let mut row = div() .flex() .flex_row() @@ -5015,6 +5068,18 @@ impl MainWindow { move |_, _, cx| cx.open_url(&url), )); } + if let Some((cap_id, actions, icons)) = app_actions { + for action in actions { + let icon = icons.get(&action.icon_sha256).cloned(); + row = row.child(self.app_action_button( + path.clone(), + cap_id.clone(), + action, + icon, + cx, + )); + } + } if item .upload .as_ref() @@ -5068,6 +5133,106 @@ impl MainWindow { )) } + fn app_action_button( + &self, + path: std::path::PathBuf, + cap_id: String, + action: crate::app_store::CapAction, + icon: Option>, + cx: &mut Context, + ) -> impl IntoElement { + let theme = self.theme; + let label = SharedString::from(action.title.clone()); + div() + .id(SharedString::from(format!( + "lib-rec-app-{}-{}", + action.installation_id, action.action_id + ))) + .role(gpui::Role::Button) + .aria_label(label.clone()) + .tooltip(move |_, cx| ui::Tooltip::new(&theme, label.clone()).view(cx)) + .tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY) + .flex_1() + .h(px(26.)) + .flex() + .items_center() + .justify_center() + .rounded(px(8.)) + .cursor_pointer() + .hover(move |style| style.bg(glass_hover(theme))) + .active(move |style| style.bg(glass_press(theme))) + .child( + div() + .size(px(14.)) + .rounded(px(3.)) + .overflow_hidden() + .bg(theme.gray_5) + .children(icon.map(|icon| img(icon).size_full())), + ) + .on_click(cx.listener(move |this, _, window, cx| { + this.run_app_action(path.clone(), cap_id.clone(), action.clone(), window, cx); + })) + } + + fn run_app_action( + &mut self, + path: std::path::PathBuf, + cap_id: String, + action: crate::app_store::CapAction, + window: &mut Window, + cx: &mut Context, + ) { + let working = SharedString::from(format!("{}...", action.title)); + self.app_action_notice = Some((path.clone(), working)); + cx.notify(); + self.app_action_task = Some(cx.spawn_in(window, async move |this, cx| { + let Ok(task) = cx.update(|_, cx| { + gpui_tokio::Tokio::spawn(cx, crate::app_store::run_cap_action(action, cap_id)) + }) else { + return; + }; + let result = task.await.unwrap_or_else(|error| Err(error.to_string())); + let message: SharedString = match &result { + Ok(result) => result + .message() + .unwrap_or(tr::main::app_action_done()) + .to_string() + .into(), + Err(error) => error.clone().into(), + }; + let open = result + .as_ref() + .ok() + .and_then(|result| result.open_url().map(str::to_string)); + if this + .update(cx, |this, cx| { + this.app_action_notice = Some((path.clone(), message)); + if let Some(url) = &open { + cx.open_url(url); + } + cx.notify(); + }) + .is_err() + { + return; + } + cx.background_executor() + .timer(std::time::Duration::from_secs(4)) + .await; + this.update(cx, |this, cx| { + if this + .app_action_notice + .as_ref() + .is_some_and(|(notice_path, _)| notice_path == &path) + { + this.app_action_notice = None; + cx.notify(); + } + }) + .ok(); + })); + } + fn render_screenshot_card( &self, row: &LibraryRow, diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs index 4a5895074ac..93e10364347 100644 --- a/apps/desktop-gpui/src/settings_pages.rs +++ b/apps/desktop-gpui/src/settings_pages.rs @@ -519,6 +519,7 @@ impl SettingsWindow { let input = self.pages.license_input.clone(); input.update(cx, |input, cx| input.set_text("", cx)); } + Page::Apps => crate::app_store::refresh(cx), Page::Integrations => { self.pages.integrations_view = IntegrationsView::Index; self.integrations_fetch_storage(false, window, cx); diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs index a58677d7266..1862776829a 100644 --- a/apps/desktop-gpui/src/settings_window.rs +++ b/apps/desktop-gpui/src/settings_window.rs @@ -96,6 +96,7 @@ pub enum Page { Screenshots, Automations, Transcription, + Apps, Integrations, License, Experimental, @@ -113,6 +114,7 @@ impl Page { Page::Screenshots, Page::Automations, Page::Transcription, + Page::Apps, Page::Integrations, Page::License, Page::Experimental, @@ -132,6 +134,7 @@ impl Page { Self::Screenshots => tr::settings::nav::screenshots(), Self::Automations => tr::settings::nav::automations(), Self::Transcription => tr::settings::nav::transcription(), + Self::Apps => tr::settings::nav::apps(), Self::Integrations => tr::settings::nav::integrations(), Self::License => tr::settings::nav::license(), Self::Experimental => tr::settings::nav::experimental(), @@ -151,6 +154,7 @@ impl Page { Self::Screenshots => "screenshots", Self::Automations => "automations", Self::Transcription => "transcription", + Self::Apps => "apps", Self::Integrations => "integrations", Self::License => "license", Self::Experimental => "experimental", @@ -174,6 +178,7 @@ impl Page { Self::Screenshots => "icons/image.svg", Self::Automations => "icons/zap.svg", Self::Transcription => "icons/captions.svg", + Self::Apps => "icons/grid.svg", Self::Integrations => "icons/unplug.svg", Self::License => "icons/gift.svg", Self::Feedback => "icons/message-square-plus.svg", @@ -762,6 +767,7 @@ pub struct SettingsWindow { profile_image: Option>, keyboard_nav: bool, _keyboard_nav: gpui::Subscription, + _app_store: Option, } impl SettingsWindow { @@ -840,6 +846,15 @@ impl SettingsWindow { ), ]; + let app_store = cx.has_global::().then(|| { + cx.observe_global_in::(window, |this, window, cx| { + if this.page == Page::Apps { + cx.notify(); + window.refresh(); + } + }) + }); + let sign_in = SignIn::global(cx); let sign_in_subscriptions = [ cx.observe_in(&sign_in, window, |_, _, window, cx| { @@ -902,6 +917,7 @@ impl SettingsWindow { profile_image: None, keyboard_nav: false, _keyboard_nav: keyboard_nav, + _app_store: app_store, } } @@ -2232,6 +2248,7 @@ impl SettingsWindow { } self.has_cap_pro = store::auth_snapshot().is_upgraded(); self.instant_quality_notice = None; + crate::app_store::account_changed(cx); if !store::set_store_value("user_profile", Value::Null) { tracing::error!("failed to clear the cached user profile"); } @@ -2389,6 +2406,7 @@ impl SettingsWindow { Page::Cli => self.render_cli(cx), Page::Automations => self.render_automations(cx), Page::Transcription => self.render_transcription(cx), + Page::Apps => self.render_apps(cx), Page::Integrations => self.render_integrations(cx), Page::License => self.render_license(cx), Page::Experimental => self.render_experimental(cx), @@ -5116,11 +5134,12 @@ mod tests { /// addresses by slug. #[test] fn every_page_round_trips_through_its_slug() { - assert_eq!(Page::ALL.len(), 13); + assert_eq!(Page::ALL.len(), 14); for page in Page::ALL { assert_eq!(Page::from_slug(page.slug()), Some(*page)); } assert_eq!(Page::Shortcuts.slug(), "hotkeys"); + assert_eq!(Page::from_slug("apps"), Some(Page::Apps)); assert_eq!(Page::from_slug("nope"), None); } diff --git a/apps/desktop-gpui/src/settings_window/recording_action_tests.rs b/apps/desktop-gpui/src/settings_window/recording_action_tests.rs index 7ddeb9ff730..e98911913dc 100644 --- a/apps/desktop-gpui/src/settings_window/recording_action_tests.rs +++ b/apps/desktop-gpui/src/settings_window/recording_action_tests.rs @@ -49,6 +49,7 @@ fn settings_fixture(window: &mut Window, cx: &mut Context) -> Se profile_image: None, keyboard_nav: false, _keyboard_nav: gpui::Subscription::new(|| {}), + _app_store: None, } } diff --git a/apps/web/.gitignore b/apps/web/.gitignore index dec0b2d2108..c3fd64a9d1e 100644 --- a/apps/web/.gitignore +++ b/apps/web/.gitignore @@ -40,3 +40,7 @@ next-env.d.ts # workflow devkit (generated) public/.well-known/workflow/ /.swc + +# generated by `bun run app-store:catalog` +/lib/app-store/generated/ +/public/app-store/ diff --git a/apps/web/__tests__/unit/app-store-announce.test.ts b/apps/web/__tests__/unit/app-store-announce.test.ts new file mode 100644 index 00000000000..0a8a1fb7e66 --- /dev/null +++ b/apps/web/__tests__/unit/app-store-announce.test.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + emitAppStoreEvent: vi.fn(async () => 0), + pending: [] as unknown[], + inRequest: { value: true }, +})); + +vi.mock("@/lib/app-store/events", () => ({ + emitAppStoreEvent: mocks.emitAppStoreEvent, +})); + +vi.mock("next/server", () => ({ + after: (task: unknown) => { + if (!mocks.inRequest.value) throw new Error("outside a request scope"); + mocks.pending.push(task); + }, +})); + +import { announceAppStoreEvent } from "@/lib/app-store/announce"; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 10)); + +describe("announceAppStoreEvent", () => { + beforeEach(() => { + mocks.pending.length = 0; + mocks.emitAppStoreEvent.mockClear(); + mocks.inRequest.value = true; + }); + + it("waits for the response before it looks up installations", async () => { + announceAppStoreEvent("cap.comment.created", "video-1" as never, { + commentId: "comment-1", + }); + await flush(); + + expect(mocks.emitAppStoreEvent).not.toHaveBeenCalled(); + expect(mocks.pending).toHaveLength(1); + expect(typeof mocks.pending[0]).toBe("function"); + + await (mocks.pending[0] as () => Promise)(); + expect(mocks.emitAppStoreEvent).toHaveBeenCalledWith( + "cap.comment.created", + "video-1", + { commentId: "comment-1" }, + ); + }); + + it("emits straight away outside a request scope", async () => { + mocks.inRequest.value = false; + announceAppStoreEvent("cap.ready", "video-2" as never); + await flush(); + + expect(mocks.emitAppStoreEvent).toHaveBeenCalledTimes(1); + expect(mocks.emitAppStoreEvent).toHaveBeenCalledWith( + "cap.ready", + "video-2", + {}, + ); + }); + + it("never throws when the emitter fails", async () => { + mocks.inRequest.value = false; + mocks.emitAppStoreEvent.mockRejectedValueOnce(new Error("db down")); + const errors = vi.spyOn(console, "error").mockImplementation(() => {}); + expect(() => + announceAppStoreEvent("cap.ready", "video-3" as never), + ).not.toThrow(); + await flush(); + expect(errors).toHaveBeenCalled(); + errors.mockRestore(); + }); +}); diff --git a/apps/web/__tests__/unit/app-store-cleanup.test.ts b/apps/web/__tests__/unit/app-store-cleanup.test.ts new file mode 100644 index 00000000000..06f41b87d73 --- /dev/null +++ b/apps/web/__tests__/unit/app-store-cleanup.test.ts @@ -0,0 +1,75 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + batches: [] as number[], + cutoffs: [] as Date[], + limits: [] as number[], +})); + +vi.mock("drizzle-orm", () => ({ + lt: (_column: unknown, value: Date) => value, +})); + +vi.mock("@cap/database/schema", () => ({ + appStoreEvents: { createdAt: "createdAt" }, +})); + +vi.mock("@cap/database", () => ({ + db: () => ({ + delete: () => ({ + where: (cutoff: Date) => { + mocks.cutoffs.push(cutoff); + return { + limit: async (limit: number) => { + mocks.limits.push(limit); + return [{ affectedRows: mocks.batches.shift() ?? 0 }]; + }, + }; + }, + }), + }), +})); + +import { + APP_STORE_EVENT_RETENTION_MS, + cleanupAppStoreEvents, +} from "@/lib/app-store/cleanup"; + +describe("cleanupAppStoreEvents", () => { + beforeEach(() => { + mocks.batches = []; + mocks.cutoffs = []; + mocks.limits = []; + }); + + it("deletes rows older than the retention window in batches until one is short", async () => { + mocks.batches = [2, 2, 1, 2]; + const now = new Date("2026-11-16T00:00:00Z"); + + const deleted = await cleanupAppStoreEvents({ now, batchSize: 2 }); + + expect(deleted).toBe(5); + expect(mocks.limits).toEqual([2, 2, 2]); + expect(mocks.cutoffs[0]?.getTime()).toBe( + now.getTime() - APP_STORE_EVENT_RETENTION_MS, + ); + }); + + it("stops after the batch budget", async () => { + mocks.batches = [3, 3, 3, 3]; + + const deleted = await cleanupAppStoreEvents({ + batchSize: 3, + maxBatches: 2, + }); + + expect(deleted).toBe(6); + expect(mocks.limits).toHaveLength(2); + }); + + it("keeps a month of rows, longer than cap.ready can fire", () => { + expect(APP_STORE_EVENT_RETENTION_MS).toBeGreaterThan( + 7 * 24 * 60 * 60 * 1000, + ); + }); +}); diff --git a/apps/web/__tests__/unit/app-store.test.ts b/apps/web/__tests__/unit/app-store.test.ts new file mode 100644 index 00000000000..a8b1fd3fcde --- /dev/null +++ b/apps/web/__tests__/unit/app-store.test.ts @@ -0,0 +1,344 @@ +import { signCapRequest } from "@cap/app-store/signing"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); +vi.mock("@cap/env", () => ({ + NODE_ENV: "test", + buildEnv: {}, + serverEnv: () => ({ + NEXTAUTH_SECRET: "test-secret-that-is-long-enough-for-hkdf", + WEB_URL: "https://cap.test", + }), +})); + +const { getAppStoreCatalog, getCatalogApp, catalogForClient } = await import( + "@/lib/app-store/catalog" +); +const { + publicSettings, + resolveSettings, + defaultSettings, + storedSettings, + parseStoredSettings, +} = await import("@/lib/app-store/settings"); +const { appStoreEventId, isNewRecording } = await import( + "@/lib/app-store/events" +); +const { appStoreSigningKey, appStorePublicKeys } = await import( + "@/lib/app-store/signing" +); +const { discordConnection, isDiscordWebhookUrl, discordMessage } = await import( + "@/lib/app-store/first-party/discord" +); +const { sendConnectionRequest } = await import("@/lib/app-store/connection"); + +const WEBHOOK = + "https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz_ABCDEF-123"; + +const cap = { + id: "abc123def456ghi", + title: "Quarterly **plan** review", + url: "https://cap.test/s/abc123def456ghi", + ownerName: "Sam", + organizationId: null, + createdAt: "2026-11-14T00:00:00.000Z", + durationSeconds: 42, +}; + +const base = { + app: { id: "discord", version: "1.0.0" }, + installation: { + id: "inst_1", + scope: "user" as const, + organizationId: null, + installedByUserId: "user_1", + }, +}; + +function signedRequest(path: string, payload: unknown, tamper = false) { + const body = JSON.stringify(payload); + const kind = (payload as { kind: "event" | "action" | "lifecycle" }).kind; + const headers = signCapRequest({ + key: appStoreSigningKey(), + body, + requestId: "req_test", + kind, + }); + return new Request( + `https://cap.test/api/app-store/first-party/discord/${path}`, + { + method: "POST", + headers, + body: tamper ? body.replace("Quarterly", "Monthly") : body, + }, + ); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("app store catalog", () => { + it("loads the generated catalog with first-party apps", () => { + const catalog = getAppStoreCatalog(); + expect(catalog.catalogVersion).toBe(1); + const discord = getCatalogApp("discord"); + expect(discord?.connection?.url).toBe("/api/app-store/first-party/discord"); + expect(discord?.platforms).toEqual(["web", "desktop"]); + expect(getCatalogApp("aurora-backgrounds")?.backgrounds.length).toBe(10); + expect(getCatalogApp("missing")).toBeNull(); + expect(catalogForClient(0).apps).toEqual([]); + }); +}); + +describe("installation settings", () => { + const fields = getCatalogApp("discord")?.connection?.settings ?? []; + + it("requires required fields and applies defaults", () => { + expect(resolveSettings(fields, {}, null)).toEqual({ + ok: false, + errors: { webhookUrl: "Channel webhook URL is required" }, + }); + expect(defaultSettings(fields)).toEqual({ postNewCaps: false }); + expect( + resolveSettings( + fields, + { webhookUrl: ` ${WEBHOOK} `, surprise: "x" }, + null, + ), + ).toEqual({ + ok: true, + settings: { webhookUrl: WEBHOOK, postNewCaps: false }, + }); + }); + + it("keeps a saved secret when the field is left empty and never exposes it", () => { + const saved = { webhookUrl: WEBHOOK, postNewCaps: true }; + const result = resolveSettings(fields, { webhookUrl: "" }, saved); + expect(result).toEqual({ ok: true, settings: saved }); + expect(publicSettings(fields, storedSettings(fields, saved, null))).toEqual( + { + values: { postNewCaps: true }, + secretsSet: ["webhookUrl"], + }, + ); + }); + + it("keeps a saved secret hidden when an app update turns it into plain text", () => { + const before = [{ key: "token", type: "secret" as const, label: "Token" }]; + const after = [{ key: "token", type: "text" as const, label: "Token" }]; + const stored = storedSettings(before, { token: "s3cr3t" }, null); + expect(publicSettings(after, stored)).toEqual({ + values: {}, + secretsSet: ["token"], + }); + const resaved = storedSettings(after, { token: "s3cr3t" }, stored); + expect(resaved.secretKeys).toEqual(["token"]); + expect(parseStoredSettings(JSON.stringify(resaved))).toEqual(resaved); + }); + + it("validates urls, selects and toggles", () => { + const custom = [ + { key: "site", type: "url" as const, label: "Site" }, + { + key: "mode", + type: "select" as const, + label: "Mode", + options: [{ value: "a", label: "A" }], + }, + { key: "on", type: "toggle" as const, label: "On" }, + ]; + const result = resolveSettings( + custom, + { site: "http://example.com", mode: "b", on: "yes" }, + null, + ); + expect(result).toEqual({ + ok: false, + errors: { + site: "Site must be an https:// URL", + mode: "Choose one of the options for Mode", + on: "Must be on or off", + }, + }); + }); +}); + +describe("app store events", () => { + it("makes stable, distinct event ids", () => { + expect(appStoreEventId("cap.ready", "v1")).toBe( + appStoreEventId("cap.ready", "v1"), + ); + expect(appStoreEventId("cap.ready", "v1")).not.toBe( + appStoreEventId("cap.ready", "v2"), + ); + expect(appStoreEventId("cap.comment.created", "v1", "c1")).not.toBe( + appStoreEventId("cap.comment.created", "v1", "c2"), + ); + expect(appStoreEventId("cap.ready", "v1")).toMatch(/^evt_[0-9a-f]{32}$/); + }); + + it("only treats recent, recorded Caps as new", () => { + const now = Date.parse("2026-11-14T12:00:00Z"); + const recent = new Date(now - 60_000); + expect(isNewRecording({ createdAt: recent, metadata: null }, now)).toBe( + true, + ); + expect( + isNewRecording( + { createdAt: new Date(now - 8 * 24 * 3600_000), metadata: null }, + now, + ), + ).toBe(false); + expect( + isNewRecording( + { + createdAt: recent, + metadata: { loomImportRun: { runId: "r" } } as never, + }, + now, + ), + ).toBe(false); + }); +}); + +describe("public keys", () => { + it("publishes the key Cap signs with", () => { + expect(appStorePublicKeys().keys[0]).toEqual( + appStoreSigningKey().publicKey, + ); + }); +}); + +describe("Discord connection", () => { + it("accepts only Discord webhook urls", () => { + expect(isDiscordWebhookUrl(WEBHOOK)).toBe(true); + expect( + isDiscordWebhookUrl(WEBHOOK.replace("discord.com", "evil.example")), + ).toBe(false); + expect(isDiscordWebhookUrl(`${WEBHOOK}?wait=true`)).toBe(false); + expect(isDiscordWebhookUrl(undefined)).toBe(false); + }); + + it("posts plain text with mentions disabled", () => { + expect(discordMessage(cap)).toEqual({ + content: "**Quarterly plan review**\nhttps://cap.test/s/abc123def456ghi", + username: "Cap", + allowed_mentions: { parse: [] }, + }); + }); + + it("rejects unsigned and tampered requests", async () => { + const unsigned = await discordConnection( + new Request("https://cap.test/api/app-store/first-party/discord/events", { + method: "POST", + body: "{}", + }), + ); + expect(unsigned.status).toBe(401); + const tampered = await discordConnection( + signedRequest( + "actions/post", + { + kind: "action", + action: "post", + ...base, + settings: { webhookUrl: WEBHOOK }, + user: { id: "user_1", name: "Sam" }, + data: { cap }, + }, + true, + ), + ); + expect(tampered.status).toBe(401); + }); + + it("posts on the action and reports the result", async () => { + const fetchMock = vi.fn( + async (_url: string, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal("fetch", fetchMock); + const response = await discordConnection( + signedRequest("actions/post", { + kind: "action", + action: "post", + ...base, + settings: { webhookUrl: WEBHOOK }, + user: { id: "user_1", name: "Sam" }, + data: { cap }, + }), + ); + expect(await response.json()).toEqual({ + type: "toast", + message: "Posted to Discord", + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0]?.[0]).toBe(WEBHOOK); + }); + + it("only posts new Caps when the setting is on, and asks Cap to retry when Discord is busy", async () => { + const fetchMock = vi.fn( + async (_url: string, _init?: RequestInit) => + new Response(null, { status: 429 }), + ); + vi.stubGlobal("fetch", fetchMock); + const event = (postNewCaps: boolean) => + signedRequest("events", { + kind: "event", + id: "evt_1", + type: "cap.ready", + createdAt: cap.createdAt, + ...base, + settings: { webhookUrl: WEBHOOK, postNewCaps }, + data: { cap }, + }); + const skipped = await discordConnection(event(false)); + expect(skipped.status).toBe(200); + expect(fetchMock).not.toHaveBeenCalled(); + const busy = await discordConnection(event(true)); + expect(busy.status).toBe(503); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("is reached in process through the signed connection protocol", async () => { + const fetchMock = vi.fn( + async (_url: string, _init?: RequestInit) => + new Response(null, { status: 204 }), + ); + vi.stubGlobal("fetch", fetchMock); + const result = await sendConnectionRequest( + { appId: "discord", url: "/api/app-store/first-party/discord" }, + { + kind: "action", + action: "post", + ...base, + settings: { webhookUrl: WEBHOOK }, + user: { id: "user_1", name: "Sam" }, + data: { cap }, + }, + { readBody: true }, + ); + expect(result.ok).toBe(true); + expect(result.ok && JSON.parse(result.body ?? "")).toEqual({ + type: "toast", + message: "Posted to Discord", + }); + }); + + it("refuses private and plain http third-party connections", async () => { + const fetcher = vi.fn(); + const result = await sendConnectionRequest( + { appId: "someone", url: "https://127.0.0.1/cap" }, + { + kind: "lifecycle", + type: "installed", + ...base, + settings: {}, + }, + { fetcher }, + ); + expect(result).toMatchObject({ ok: false, errorCode: "private_address" }); + expect(fetcher).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/__tests__/unit/cap-app-action-label.test.ts b/apps/web/__tests__/unit/cap-app-action-label.test.ts new file mode 100644 index 00000000000..f35e5795906 --- /dev/null +++ b/apps/web/__tests__/unit/cap-app-action-label.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { capActionLabel } from "@/app/(org)/dashboard/caps/components/CapCard/cap-action-label"; + +const action = ( + installationId: string, + scope: "user" | "organization", + title = "Post to Discord", +) => ({ + installationId, + appName: "Discord", + iconUrl: "/app-store/discord/icon.png", + actionId: "post", + title, + scope, +}); + +describe("capActionLabel", () => { + it("keeps a unique title as it is", () => { + const only = action("ins_1", "user"); + expect(capActionLabel(only, [only])).toBe("Post to Discord"); + }); + + it("names the install when the same action appears for you and your organization", () => { + const mine = action("ins_1", "user"); + const team = action("ins_2", "organization"); + const notes = action("ins_3", "user", "Send to Notes"); + const all = [mine, team, notes]; + expect(capActionLabel(mine, all)).toBe("Post to Discord · Just me"); + expect(capActionLabel(team, all)).toBe("Post to Discord · Organization"); + expect(capActionLabel(notes, all)).toBe("Send to Notes"); + }); +}); diff --git a/apps/web/__tests__/unit/dashboard-titles.test.ts b/apps/web/__tests__/unit/dashboard-titles.test.ts index ceb40fe29f7..19c8d8d6c66 100644 --- a/apps/web/__tests__/unit/dashboard-titles.test.ts +++ b/apps/web/__tests__/unit/dashboard-titles.test.ts @@ -15,6 +15,13 @@ describe("dashboard top bar titles", () => { ]); }); + it("titles the App Store and links app pages back to it", () => { + expect(labels("/dashboard/apps")).toEqual(["Apps"]); + expect(dashboardTitle("/dashboard/apps/discord")).toEqual([ + { label: "Apps", href: "/dashboard/apps" }, + ]); + }); + it("names browse spaces the same as the space breadcrumb parent", () => { expect(labels("/dashboard/spaces/browse")).toEqual(["Spaces"]); }); diff --git a/apps/web/__tests__/unit/organization-switcher-item-values.test.ts b/apps/web/__tests__/unit/organization-switcher-item-values.test.ts index 37cf8908acd..b18e34150f7 100644 --- a/apps/web/__tests__/unit/organization-switcher-item-values.test.ts +++ b/apps/web/__tests__/unit/organization-switcher-item-values.test.ts @@ -34,6 +34,7 @@ vi.mock("@/components/Tooltip", () => ({ })); vi.mock("@/components/UsageButton", () => ({ UsageButton: () => null })); vi.mock("@/app/(org)/dashboard/_components/AnimatedIcons", () => ({ + AppsIcon: () => null, CapIcon: () => null, ChartLineIcon: () => null, CodeIcon: () => null, diff --git a/apps/web/actions/app-store.ts b/apps/web/actions/app-store.ts new file mode 100644 index 00000000000..77ba1bcc05e --- /dev/null +++ b/apps/web/actions/app-store.ts @@ -0,0 +1,124 @@ +"use server"; + +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { organizations } from "@cap/database/schema"; +import type { Organisation } from "@cap/web-domain"; +import { eq, sql } from "drizzle-orm"; +import { revalidatePath } from "next/cache"; +import { requireOrganizationSettingsManager } from "@/actions/organization/authorization"; +import { sendUninstalled } from "@/lib/app-store/delivery"; +import { + announceInBackground, + announceLifecycle, +} from "@/lib/app-store/events"; +import { + AppStoreError, + type InstallationView, + type InstallScope, + installApp, + uninstallApp, + updateInstallation, +} from "@/lib/app-store/installations"; +import type { SettingsInput } from "@/lib/app-store/settings"; + +export type AppStoreActionResult = + | { ok: true; value: T } + | { ok: false; error: string; fieldErrors?: Record }; + +async function run( + work: () => Promise, +): Promise> { + try { + return { ok: true, value: await work() }; + } catch (error) { + if (error instanceof AppStoreError) { + return { + ok: false, + error: error.message, + fieldErrors: error.fieldErrors, + }; + } + console.error("[app-store] Action failed", error); + return { ok: false, error: "Something went wrong. Try again." }; + } +} + +async function requireUser() { + const user = await getCurrentUser(); + if (!user) throw new AppStoreError("forbidden", "Sign in to manage apps"); + return user; +} + +export async function installAppAction(input: { + appId: string; + scope: InstallScope; + organizationId?: string | null; + settings?: SettingsInput; +}): Promise> { + return run(async () => { + const user = await requireUser(); + const { view, row } = await installApp(user.id, { + ...input, + activeOrganizationId: user.activeOrganizationId, + }); + announceLifecycle(row.id, "installed"); + revalidatePath("/dashboard/apps", "layout"); + return view; + }); +} + +export async function updateInstallationAction( + installationId: string, + input: { settings?: SettingsInput; acceptUpdate?: boolean; resume?: boolean }, +): Promise> { + return run(async () => { + const user = await requireUser(); + const result = await updateInstallation(user.id, installationId, input); + if (result.settingsChanged) { + announceLifecycle(result.row.id, "settings.updated"); + } + revalidatePath("/dashboard/apps", "layout"); + return result.view; + }); +} + +export async function uninstallAppAction( + installationId: string, +): Promise> { + return run(async () => { + const user = await requireUser(); + const { row, settings } = await uninstallApp(user.id, installationId); + announceInBackground( + `uninstalled for ${row.id}`, + sendUninstalled(row, settings), + ); + revalidatePath("/dashboard/apps", "layout"); + return null; + }); +} + +export async function setAppStoreAdminsOnlyAction( + organizationId: Organisation.OrganisationId, + adminsOnly: boolean, +): Promise> { + return run(async () => { + const user = await requireUser(); + await requireOrganizationSettingsManager(user.id, organizationId).catch( + () => { + throw new AppStoreError( + "forbidden", + "Only owners and admins can change this setting", + ); + }, + ); + await db() + .update(organizations) + .set({ + settings: sql`JSON_MERGE_PATCH(COALESCE(${organizations.settings}, JSON_OBJECT()), CAST(${JSON.stringify({ appStoreAdminsOnly: adminsOnly })} AS JSON))`, + }) + .where(eq(organizations.id, organizationId)); + revalidatePath("/dashboard/apps", "layout"); + return adminsOnly; + }); +} diff --git a/apps/web/app/(org)/dashboard/_components/AnimatedIcons/Apps.tsx b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/Apps.tsx new file mode 100644 index 00000000000..622865a2276 --- /dev/null +++ b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/Apps.tsx @@ -0,0 +1,98 @@ +"use client"; + +import type { Transition } from "motion/react"; +import { motion, useAnimation } from "motion/react"; +import type { HTMLAttributes } from "react"; +import { forwardRef, useCallback, useImperativeHandle, useRef } from "react"; +import { cn } from "@/lib/utils"; + +export interface AppsIconHandle { + startAnimation: () => void; + stopAnimation: () => void; +} + +interface AppsIconProps extends HTMLAttributes { + size?: number; +} + +const transition: Transition = { + type: "spring", + stiffness: 260, + damping: 18, +}; + +const AppsIcon = forwardRef( + ({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => { + const controls = useAnimation(); + const isControlledRef = useRef(false); + + useImperativeHandle(ref, () => { + isControlledRef.current = true; + return { + startAnimation: () => controls.start("animate"), + stopAnimation: () => controls.start("normal"), + }; + }); + + const handleMouseEnter = useCallback( + (e: React.MouseEvent) => { + if (!isControlledRef.current) controls.start("animate"); + else onMouseEnter?.(e); + }, + [controls, onMouseEnter], + ); + + const handleMouseLeave = useCallback( + (e: React.MouseEvent) => { + if (!isControlledRef.current) controls.start("normal"); + else onMouseLeave?.(e); + }, + [controls, onMouseLeave], + ); + + return ( +
+ +
+ ); + }, +); + +AppsIcon.displayName = "AppsIcon"; + +export default AppsIcon; diff --git a/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts index f3570be3a5f..a02bee25953 100644 --- a/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts +++ b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts @@ -1,3 +1,4 @@ +import AppsIcon from "./Apps"; import ArrowUpIcon from "./ArrowUp"; import CapIcon from "./Cap"; import ChartLineIcon from "./ChartLine"; @@ -16,6 +17,7 @@ import RecordIcon from "./Record"; import ReferIcon from "./Refer"; import SettingsGearIcon from "./Settings"; export { + AppsIcon, ArrowUpIcon, CapIcon, MessageCircleMoreIcon, diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx index 6b6ea844e82..33c2a1e9982 100644 --- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx +++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx @@ -54,6 +54,7 @@ import { } from "@/lib/permissions/roles"; import { useDashboardContext } from "../../Contexts"; import { + AppsIcon, CapIcon, ChartLineIcon, CodeIcon, @@ -109,6 +110,13 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => { icon: , subNav: [], }, + { + name: "Apps", + href: "/dashboard/apps", + matchChildren: true, + icon: , + subNav: [], + }, { name: "Organization Settings", href: `/dashboard/settings/organization`, diff --git a/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts b/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts index 28d317bb257..66c57b4205d 100644 --- a/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts +++ b/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts @@ -4,6 +4,7 @@ const exact: Record = { "/dashboard/caps": [{ label: "My Caps" }], "/dashboard/caps/record": [{ label: "Record a Cap" }], "/dashboard/analytics": [{ label: "Analytics" }], + "/dashboard/apps": [{ label: "Apps" }], "/dashboard/import": [{ label: "Import Media" }], "/dashboard/import/file": [ { label: "Import Media", href: "/dashboard/import" }, @@ -23,6 +24,7 @@ const exact: Record = { const prefixes: [string, DashboardCrumb[]][] = [ ["/dashboard/settings/organization", [{ label: "Organization Settings" }]], ["/dashboard/folder/", [{ label: "My Caps", href: "/dashboard/caps" }]], + ["/dashboard/apps/", [{ label: "Apps", href: "/dashboard/apps" }]], ]; export function dashboardTitle(pathname: string | null): DashboardCrumb[] { diff --git a/apps/web/app/(org)/dashboard/apps/[appId]/page.tsx b/apps/web/app/(org)/dashboard/apps/[appId]/page.tsx new file mode 100644 index 00000000000..e3b8303b5d6 --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/[appId]/page.tsx @@ -0,0 +1,52 @@ +import { getCurrentUser } from "@cap/database/auth/session"; +import type { Metadata } from "next"; +import { notFound, redirect } from "next/navigation"; +import { userOrganizations } from "@/lib/app-store/access"; +import { getCatalogApp } from "@/lib/app-store/catalog"; +import { listInstallations } from "@/lib/app-store/installations"; +import { canManageOrganizationSettings } from "@/lib/permissions/roles"; +import { AppDetail } from "../_components/AppDetail"; + +export async function generateMetadata({ + params, +}: { + params: Promise<{ appId: string }>; +}): Promise { + const { appId } = await params; + const app = getCatalogApp(appId); + return { title: app ? `${app.name} | Cap Apps` : "Apps | Cap" }; +} + +export default async function AppDetailPage({ + params, +}: { + params: Promise<{ appId: string }>; +}) { + const { appId } = await params; + const app = getCatalogApp(appId); + if (!app) notFound(); + + const user = await getCurrentUser(); + if (!user) redirect("/login"); + + const [installations, organizations] = await Promise.all([ + listInstallations(user.id), + userOrganizations(user.id), + ]); + + return ( + installation.appId === app.id, + )} + organizations={organizations.map((organization) => ({ + id: organization.id, + name: organization.name, + canManage: canManageOrganizationSettings(organization.role), + adminsOnly: organization.adminsOnly, + }))} + activeOrganizationId={user.activeOrganizationId ?? null} + /> + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/AppDetail.tsx b/apps/web/app/(org)/dashboard/apps/_components/AppDetail.tsx new file mode 100644 index 00000000000..5fb77d3853d --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/AppDetail.tsx @@ -0,0 +1,582 @@ +"use client"; + +import { + APP_CATEGORY_LABELS, + type AppCategory, + BASE_PERMISSION_DESCRIPTION, + CAP_EVENT_DESCRIPTIONS, + type CatalogApp, + CONNECTION_PERMISSION_DESCRIPTIONS, + isFirstPartyConnectionUrl, +} from "@cap/app-store"; +import { Button } from "@cap/ui"; +import clsx from "clsx"; +import { ArrowLeft, Check, ExternalLink } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useState, useTransition } from "react"; +import ReactMarkdown from "react-markdown"; +import { toast } from "sonner"; +import { + installAppAction, + uninstallAppAction, + updateInstallationAction, +} from "@/actions/app-store"; +import type { InstallationView } from "@/lib/app-store/installations"; +import { AppIcon } from "./AppIcon"; +import { ContentPreview } from "./ContentPreview"; +import { PlatformBadges } from "./PlatformBadges"; +import { initialDraft, type SettingsDraft, SettingsForm } from "./SettingsForm"; +import type { OrganizationOption } from "./types"; + +const BUILTIN_SETUP_PATH = "/dashboard/settings/organization/integrations"; + +type Scope = + | { scope: "user" } + | { scope: "organization"; organizationId: string }; + +const scopeKey = (scope: Scope) => + scope.scope === "user" ? "user" : `org:${scope.organizationId}`; + +export function AppDetail({ + app, + installations, + organizations, + activeOrganizationId, +}: { + app: CatalogApp; + installations: InstallationView[]; + organizations: OrganizationOption[]; + activeOrganizationId: string | null; +}) { + const connectionHost = app.connection + ? isFirstPartyConnectionUrl(app.connection.url) + ? "Cap" + : new URL(app.connection.url).hostname + : null; + const author = app.firstParty ? "Cap" : app.author.name; + + return ( +
+ + + All apps + + +
+ +
+

{app.name}

+

{app.description}

+
+ + By{" "} + {app.firstParty ? ( + author + ) : ( + + {author} + + )} + + · + +
+
+
+ +
+
+ + {app.screenshots.length > 0 && ( +
+ {app.screenshots.map((screenshot) => ( + + ))} +
+ )} + +
+ + +
+
+ ); +} + +function PermissionItem({ children }: { children: React.ReactNode }) { + return ( +
  • + + {children} +
  • + ); +} + +function withoutTitle(markdown: string, name: string) { + const [first, ...rest] = markdown.trimStart().split("\n"); + return first?.replace(/^#\s+/, "").trim() === name + ? rest.join("\n").trimStart() + : markdown; +} + +function Readme({ markdown }: { markdown: string }) { + return ( + + ); +} + +function InstallPanel({ + app, + installations, + organizations, + activeOrganizationId, +}: { + app: CatalogApp; + installations: InstallationView[]; + organizations: OrganizationOption[]; + activeOrganizationId: string | null; +}) { + const router = useRouter(); + const [pending, startTransition] = useTransition(); + const fields = app.connection?.settings ?? []; + const [draft, setDraft] = useState(() => initialDraft(fields)); + const [errors, setErrors] = useState>(); + + const managed = organizations + .filter((organization) => organization.canManage) + .sort((a, b) => + a.id === activeOrganizationId + ? -1 + : b.id === activeOrganizationId + ? 1 + : 0, + ); + const active = organizations.find((org) => org.id === activeOrganizationId); + const userBlocked = + !!app.connection && !!active?.adminsOnly && !active.canManage; + + const installedKeys = new Set( + installations.map((installation) => + installation.scope === "user" + ? "user" + : `org:${installation.organizationId}`, + ), + ); + const scopes: (Scope & { label: string })[] = [ + ...(userBlocked ? [] : [{ scope: "user" as const, label: "Just me" }]), + ...managed.map((organization) => ({ + scope: "organization" as const, + organizationId: organization.id, + label: `Everyone in ${organization.name}`, + })), + ].filter((scope) => !installedKeys.has(scopeKey(scope))); + const [selected, setSelected] = useState(0); + const scope = scopes[Math.min(selected, scopes.length - 1)]; + + if (app.builtin) { + const canSetUp = active?.canManage; + return ( +
    +

    + {app.name} is built into Cap.{" "} + {canSetUp + ? "Set it up from your organization settings." + : "Ask an owner or admin of your organization to set it up."} +

    + {canSetUp && ( + + )} +
    + ); + } + + const install = () => { + if (!scope) return; + setErrors(undefined); + startTransition(async () => { + const result = await installAppAction({ + appId: app.id, + scope: scope.scope, + organizationId: + scope.scope === "organization" ? scope.organizationId : null, + settings: draft, + }); + if (!result.ok) { + setErrors(result.fieldErrors); + toast.error(result.error); + return; + } + toast.success(`${app.name} installed`); + setDraft(initialDraft(fields)); + setSelected(0); + router.refresh(); + }); + }; + + return ( +
    + {installations.map((installation) => ( + + ))} + + {scopes.length > 0 && scope && ( +
    +
    +

    + {installations.length > 0 + ? "Install for more people" + : `Install ${app.name}`} +

    +

    + {app.connection + ? "Works on the web and in Cap Desktop as soon as it is installed." + : "Appears in Cap Desktop the next time it opens."} +

    +
    + + {scopes.length > 1 && ( +
    + Install for + {scopes.map((option, index) => ( + + ))} +
    + )} + + {fields.length > 0 && ( + + )} + + +
    + )} + + {scopes.length === 0 && installations.length === 0 && userBlocked && ( +
    + {active?.name} only lets owners and admins install apps that connect + to other services. Ask one of them to install {app.name}. +
    + )} +
    + ); +} + +function InstalledCard({ + app, + installation, +}: { + app: CatalogApp; + installation: InstallationView; +}) { + const router = useRouter(); + const [pending, startTransition] = useTransition(); + const fields = app.connection?.settings ?? []; + const [draft, setDraft] = useState(() => + initialDraft(fields, installation.settings.values), + ); + const [errors, setErrors] = useState>(); + const who = + installation.scope === "user" + ? "Installed for you" + : `Installed for ${installation.organizationName ?? "your organization"}`; + + const update = ( + input: Parameters[1], + success: string, + ) => { + setErrors(undefined); + startTransition(async () => { + const result = await updateInstallationAction(installation.id, input); + if (!result.ok) { + setErrors(result.fieldErrors); + toast.error(result.error); + return; + } + toast.success(success); + setDraft(initialDraft(fields, result.value.settings.values)); + router.refresh(); + }); + }; + + const uninstall = () => { + const target = + installation.scope === "user" + ? `Uninstall ${app.name}?` + : `Uninstall ${app.name} for everyone in ${installation.organizationName}?`; + if (!window.confirm(target)) return; + startTransition(async () => { + const result = await uninstallAppAction(installation.id); + if (!result.ok) { + toast.error(result.error); + return; + } + toast.success(`${app.name} uninstalled`); + router.refresh(); + }); + }; + + const newPermissions = [ + ...(app.connection?.permissions ?? []) + .filter( + (permission) => !installation.grantedPermissions.includes(permission), + ) + .map((permission) => CONNECTION_PERMISSION_DESCRIPTIONS[permission]), + ...(app.connection?.events ?? []) + .filter((event) => !installation.grantedEvents.includes(event)) + .map((event) => CAP_EVENT_DESCRIPTIONS[event]), + ]; + + return ( +
    +
    + + + {who} + + {installation.status === "disabled" && ( + + Paused + + )} +
    + + {installation.status === "disabled" && ( +
    + Cap paused this connection because {app.name} stopped responding for + several days. + {installation.canManage && ( + + )} +
    + )} + + {installation.needsReview && ( +
    +

    + {app.name} asks for more access +

    +
      + {newPermissions.map((item) => ( +
    • {item}
    • + ))} +
    +

    + Until you accept, Cap keeps sending only what you approved before. +

    + {installation.canManage && ( + + )} +
    + )} + + {fields.length > 0 && installation.canManage && ( + <> + + + + )} + + {installation.canManage ? ( + + ) : ( +

    + Owners and admins manage apps installed for the organization. +

    + )} +
    + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/AppIcon.tsx b/apps/web/app/(org)/dashboard/apps/_components/AppIcon.tsx new file mode 100644 index 00000000000..dd7278bce64 --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/AppIcon.tsx @@ -0,0 +1,29 @@ +import clsx from "clsx"; + +export function AppIcon({ + src, + name, + size = 44, + className, +}: { + src: string; + name: string; + size?: number; + className?: string; +}) { + return ( + {`${name} + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/AppStoreBrowser.tsx b/apps/web/app/(org)/dashboard/apps/_components/AppStoreBrowser.tsx new file mode 100644 index 00000000000..2f5aac6f16b --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/AppStoreBrowser.tsx @@ -0,0 +1,240 @@ +"use client"; + +import { APP_CATEGORY_LABELS, type AppCategory } from "@cap/app-store"; +import { Switch } from "@cap/ui"; +import clsx from "clsx"; +import { Check, Search } from "lucide-react"; +import Link from "next/link"; +import { useId, useMemo, useState, useTransition } from "react"; +import { toast } from "sonner"; +import { setAppStoreAdminsOnlyAction } from "@/actions/app-store"; +import type { InstallationView } from "@/lib/app-store/installations"; +import { AppIcon } from "./AppIcon"; +import { PlatformBadges } from "./PlatformBadges"; +import type { AppListing, OrganizationOption } from "./types"; + +const INSTALLED = "installed"; +const ALL = "all"; + +export function AppStoreBrowser({ + apps, + installations, + activeOrganization, +}: { + apps: AppListing[]; + installations: InstallationView[]; + activeOrganization: OrganizationOption | null; +}) { + const [query, setQuery] = useState(""); + const [filter, setFilter] = useState(ALL); + const installedIds = useMemo( + () => new Set(installations.map((installation) => installation.appId)), + [installations], + ); + + const categories = useMemo(() => { + const present = new Set(apps.flatMap((app) => app.categories)); + return (Object.keys(APP_CATEGORY_LABELS) as AppCategory[]).filter( + (category) => present.has(category), + ); + }, [apps]); + + const visible = useMemo(() => { + const needle = query.trim().toLowerCase(); + return apps.filter((app) => { + if (filter === INSTALLED && !installedIds.has(app.id)) return false; + if ( + filter !== ALL && + filter !== INSTALLED && + !app.categories.includes(filter) + ) + return false; + if (!needle) return true; + return [app.name, app.description, app.author.name, ...app.keywords] + .join(" ") + .toLowerCase() + .includes(needle); + }); + }, [apps, filter, installedIds, query]); + + const filters = [ + { id: ALL, label: "All" }, + { + id: INSTALLED, + label: `Installed${installedIds.size ? ` ${installedIds.size}` : ""}`, + }, + ...categories.map((category) => ({ + id: category, + label: APP_CATEGORY_LABELS[category], + })), + ]; + + return ( +
    +
    +
    +

    Apps

    +

    + Add backgrounds, caption styles and connections to the tools you + already use. Install an app once and it works on the web and in Cap + Desktop. +

    +
    + +
    + +
    + {filters.map((item) => ( + + ))} +
    + + {visible.length === 0 ? ( +
    +

    + {filter === INSTALLED && !query + ? "You have not installed any apps yet" + : "No apps match your search"} +

    +

    + Anyone can build a Cap App.{" "} + + Learn how + +

    +
    + ) : ( +
    + {visible.map((app) => ( + + ))} +
    + )} + +
    +

    + Want to build one? Apps are open source and live in the{" "} + + Cap repository + + . +

    + {activeOrganization?.canManage && ( + + )} +
    +
    + ); +} + +function AppCard({ app, installed }: { app: AppListing; installed: boolean }) { + return ( + +
    + +
    +

    + {app.name} +

    +

    + {app.firstParty ? "Cap" : app.author.name} +

    +
    + {installed && ( + + + Installed + + )} +
    +

    + {app.description} +

    + + + ); +} + +function AdminsOnlyToggle({ + organization, +}: { + organization: OrganizationOption; +}) { + const labelId = useId(); + const [checked, setChecked] = useState(organization.adminsOnly); + const [pending, startTransition] = useTransition(); + return ( +
    + + Only owners and admins of {organization.name} can install apps that + connect to other services + + { + setChecked(next); + startTransition(async () => { + const result = await setAppStoreAdminsOnlyAction( + organization.id, + next, + ); + if (!result.ok) { + setChecked(!next); + toast.error(result.error); + } + }); + }} + /> +
    + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/ContentPreview.tsx b/apps/web/app/(org)/dashboard/apps/_components/ContentPreview.tsx new file mode 100644 index 00000000000..8bbe3d508fa --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/ContentPreview.tsx @@ -0,0 +1,211 @@ +import type { + CaptionStyle, + CatalogBackground, + ColorLook, +} from "@cap/app-store"; +import Image from "next/image"; +import type { CSSProperties } from "react"; + +function hexToRgba(hex: string, alpha: number) { + const value = Number.parseInt(hex.slice(1), 16); + return `rgba(${(value >> 16) & 255}, ${(value >> 8) & 255}, ${value & 255}, ${alpha})`; +} + +function backgroundStyle(background: CatalogBackground): CSSProperties { + if (background.kind === "image") return {}; + if (background.kind === "gradient") { + return { + backgroundImage: `linear-gradient(${background.angle}deg, ${background.from}, ${background.to})`, + }; + } + return { backgroundColor: background.color }; +} + +function Tile({ + label, + children, + style, +}: { + label: string; + children?: React.ReactNode; + style?: CSSProperties; +}) { + return ( +
    +
    + {children} +
    +
    + {label} +
    +
    + ); +} + +const SAMPLE_WORDS = ["Every", "word", "lands"]; + +function CaptionTile({ style }: { style: CaptionStyle }) { + const textStyle: CSSProperties = { + color: style.color, + fontWeight: style.fontWeight, + fontSize: Math.max(11, Math.round(style.size / 3.6)), + textTransform: style.uppercase ? "uppercase" : "none", + textShadow: style.outline + ? `0 0 2px ${style.outlineColor}, 0 0 2px ${style.outlineColor}, 0 0 1px ${style.outlineColor}` + : undefined, + }; + return ( + + + {SAMPLE_WORDS.map((word, index) => { + const active = style.activeWordHighlight && index === 1; + return ( + + {index > 0 ? " " : ""} + + {word} + + + ); + })} + + + ); +} + +function lookFilter(look: ColorLook) { + const v = look.values; + const intensity = v.intensity ?? 1; + const amount = (value: number | undefined) => (value ?? 0) * intensity; + const temperature = amount(v.temperature); + return [ + `brightness(${1 + amount(v.exposure) * 0.5})`, + `contrast(${1 + amount(v.contrast) - amount(v.fade) * 0.25})`, + `saturate(${Math.max(0, 1 + amount(v.saturation))})`, + temperature > 0 ? `sepia(${temperature * 0.5})` : "", + temperature < 0 ? `hue-rotate(${temperature * 25}deg)` : "", + amount(v.tint) !== 0 ? `hue-rotate(${amount(v.tint) * -12}deg)` : "", + ] + .filter(Boolean) + .join(" "); +} + +function LookTile({ look }: { look: ColorLook }) { + const vignette = (look.values.vignette ?? 0) * (look.values.intensity ?? 1); + return ( + +
    +
    + + ); +} + +export function ContentPreview({ + backgrounds, + captionStyles, + colorLooks, +}: { + backgrounds: readonly CatalogBackground[]; + captionStyles: readonly CaptionStyle[]; + colorLooks: readonly ColorLook[]; +}) { + if (!backgrounds.length && !captionStyles.length && !colorLooks.length) { + return null; + } + return ( +
    + {backgrounds.length > 0 && ( +
    +

    + {backgrounds.length} backgrounds +

    +
    + {backgrounds.map((background) => ( + + {background.kind === "image" && ( + + )} + + ))} +
    +
    + )} + {captionStyles.length > 0 && ( +
    +

    + {captionStyles.length} caption styles +

    +
    + {captionStyles.map((style) => ( + + ))} +
    +
    + )} + {colorLooks.length > 0 && ( +
    +

    + {colorLooks.length} color looks +

    +
    + {colorLooks.map((look) => ( + + ))} +
    +
    + )} +
    + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/PlatformBadges.tsx b/apps/web/app/(org)/dashboard/apps/_components/PlatformBadges.tsx new file mode 100644 index 00000000000..71685b6d133 --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/PlatformBadges.tsx @@ -0,0 +1,29 @@ +import { Globe, Monitor } from "lucide-react"; + +const LABELS = { + web: { label: "Web", Icon: Globe }, + desktop: { label: "Desktop", Icon: Monitor }, +} as const; + +export function PlatformBadges({ + platforms, +}: { + platforms: readonly ("web" | "desktop")[]; +}) { + return ( +
    + {platforms.map((platform) => { + const { label, Icon } = LABELS[platform]; + return ( + + + {label} + + ); + })} +
    + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/SettingsForm.tsx b/apps/web/app/(org)/dashboard/apps/_components/SettingsForm.tsx new file mode 100644 index 00000000000..81b2407d664 --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/SettingsForm.tsx @@ -0,0 +1,153 @@ +"use client"; + +import type { SettingField, SettingValue } from "@cap/app-store"; +import { Select, Switch } from "@cap/ui"; +import clsx from "clsx"; + +export type SettingsDraft = Record; + +export function initialDraft( + fields: readonly SettingField[], + values: Record = {}, +): SettingsDraft { + const draft: SettingsDraft = {}; + for (const field of fields) { + const value = values[field.key]; + if (field.type === "toggle") { + draft[field.key] = + typeof value === "boolean" ? value : (field.default ?? false); + } else if (field.type === "secret") { + draft[field.key] = ""; + } else { + draft[field.key] = + typeof value === "string" ? value : (field.default ?? ""); + } + } + return draft; +} + +const inputClass = + "h-9 w-full rounded-lg border border-gray-4 bg-gray-1 px-3 text-[13px] text-gray-12 outline-none transition-colors placeholder:text-gray-8 hover:border-gray-5 focus:border-gray-7 disabled:opacity-60"; + +export function SettingsForm({ + fields, + draft, + onChange, + errors, + secretsSet = [], + disabled, + idPrefix, +}: { + fields: readonly SettingField[]; + draft: SettingsDraft; + onChange: (draft: SettingsDraft) => void; + errors?: Record; + secretsSet?: readonly string[]; + disabled?: boolean; + idPrefix: string; +}) { + const set = (key: string, value: SettingValue) => + onChange({ ...draft, [key]: value }); + + return ( +
    + {fields.map((field) => { + const id = `${idPrefix}-${field.key}`; + const error = errors?.[field.key]; + const description = field.description ? ( +

    + {field.description} +

    + ) : null; + + if (field.type === "toggle") { + return ( +
    +
    + + {description} +
    + set(field.key, checked)} + aria-describedby={ + field.description ? `${id}-description` : undefined + } + /> +
    + ); + } + + const required = "required" in field && field.required; + return ( +
    + + {field.type === "select" ? ( + set(field.key, event.target.value)} + placeholder={ + field.type === "secret" && secretsSet.includes(field.key) + ? "Saved. Enter a new value to replace it" + : "placeholder" in field + ? field.placeholder + : undefined + } + aria-invalid={error ? true : undefined} + aria-describedby={ + field.description ? `${id}-description` : undefined + } + className={clsx(inputClass, error && "border-red-500")} + /> + )} + {description} + {error &&

    {error}

    } +
    + ); + })} +
    + ); +} diff --git a/apps/web/app/(org)/dashboard/apps/_components/types.ts b/apps/web/app/(org)/dashboard/apps/_components/types.ts new file mode 100644 index 00000000000..2620eba7de8 --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/_components/types.ts @@ -0,0 +1,16 @@ +import type { CatalogApp } from "@cap/app-store"; +import type { Organisation } from "@cap/web-domain"; + +export type AppListing = Omit; + +export type OrganizationOption = { + id: Organisation.OrganisationId; + name: string; + canManage: boolean; + adminsOnly: boolean; +}; + +export const toListing = ({ + readme: _readme, + ...app +}: CatalogApp): AppListing => app; diff --git a/apps/web/app/(org)/dashboard/apps/page.tsx b/apps/web/app/(org)/dashboard/apps/page.tsx new file mode 100644 index 00000000000..df0119f988c --- /dev/null +++ b/apps/web/app/(org)/dashboard/apps/page.tsx @@ -0,0 +1,43 @@ +import { getCurrentUser } from "@cap/database/auth/session"; +import type { Metadata } from "next"; +import { redirect } from "next/navigation"; +import { userOrganizations } from "@/lib/app-store/access"; +import { getAppStoreCatalog } from "@/lib/app-store/catalog"; +import { listInstallations } from "@/lib/app-store/installations"; +import { canManageOrganizationSettings } from "@/lib/permissions/roles"; +import { AppStoreBrowser } from "./_components/AppStoreBrowser"; +import { toListing } from "./_components/types"; + +export const metadata: Metadata = { + title: "Apps | Cap", +}; + +export default async function AppsPage() { + const user = await getCurrentUser(); + if (!user) redirect("/login"); + + const [installations, organizations] = await Promise.all([ + listInstallations(user.id), + userOrganizations(user.id), + ]); + const active = organizations.find( + (organization) => organization.id === user.activeOrganizationId, + ); + + return ( + + ); +} diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapAppActionItems.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapAppActionItems.tsx new file mode 100644 index 00000000000..742da04a01b --- /dev/null +++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapAppActionItems.tsx @@ -0,0 +1,95 @@ +"use client"; + +import { DropdownMenuItem, DropdownMenuSeparator } from "@cap/ui"; +import type { Video } from "@cap/web-domain"; +import { useEffect, useState } from "react"; +import { toast } from "sonner"; +import { type CapAction, capActionLabel } from "./cap-action-label"; + +type ActionResult = + | { type: "toast"; message: string } + | { type: "open"; url: string; message?: string }; + +const actionsPath = (videoId: string) => + `/api/app-store/caps/${encodeURIComponent(videoId)}/actions`; + +async function readError(response: Response) { + const body = (await response.json().catch(() => null)) as { + error?: string; + } | null; + return body?.error ?? "Something went wrong"; +} + +export function CapAppActionItems({ videoId }: { videoId: Video.VideoId }) { + const [data, setData] = useState(null); + + useEffect(() => { + const controller = new AbortController(); + fetch(actionsPath(videoId), { + credentials: "same-origin", + signal: controller.signal, + }) + .then((response) => (response.ok ? response.json() : null)) + .then((body: { actions?: CapAction[] } | null) => + setData(body?.actions ?? []), + ) + .catch(() => {}); + return () => controller.abort(); + }, [videoId]); + + if (!data || data.length === 0) return null; + + const run = (action: CapAction) => { + const promise = fetch(actionsPath(videoId), { + method: "POST", + credentials: "same-origin", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + installationId: action.installationId, + actionId: action.actionId, + }), + }).then(async (response) => { + if (!response.ok) throw new Error(await readError(response)); + const { result } = (await response.json()) as { result: ActionResult }; + if (result.type === "open" && result.url.startsWith("https://")) { + window.open(result.url, "_blank", "noopener,noreferrer"); + } + return result.message ?? `${action.title}: done`; + }); + toast.promise(promise, { + loading: `${action.title}...`, + success: (message) => message, + error: (error) => + error instanceof Error ? error.message : "Something went wrong", + }); + }; + + return ( + <> + +
    + {data.map((action) => ( + { + event.stopPropagation(); + run(action); + }} + className="flex gap-2 items-center rounded-lg" + > + +

    + {capActionLabel(action, data)} +

    +
    + ))} +
    + + ); +} diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx index 2a802a9c2ff..b574132256e 100644 --- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx @@ -61,6 +61,7 @@ import { MoveItemsDialog } from "../MoveItemsDialog"; import { PasswordDialog } from "../PasswordDialog"; import { SettingsDialog } from "../SettingsDialog"; import { SharingDialog } from "../SharingDialog"; +import { CapAppActionItems } from "./CapAppActionItems"; import { CapCardAnalytics, capAnalyticsHref } from "./CapCardAnalytics"; import { CapCardButton } from "./CapCardButton"; import { CapCardContent } from "./CapCardContent"; @@ -620,6 +621,7 @@ export const CapCard = ({ )} )} + diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/cap-action-label.ts b/apps/web/app/(org)/dashboard/caps/components/CapCard/cap-action-label.ts new file mode 100644 index 00000000000..44fe5f54d32 --- /dev/null +++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/cap-action-label.ts @@ -0,0 +1,20 @@ +export type CapAction = { + installationId: string; + appName: string; + iconUrl: string; + actionId: string; + title: string; + scope: "user" | "organization"; +}; + +// The same app can be installed for you and for your organization, each with +// its own settings, so a repeated title says which install it uses. +export function capActionLabel(action: CapAction, actions: CapAction[]) { + const repeated = actions.some( + (other) => + other.installationId !== action.installationId && + other.title === action.title, + ); + if (!repeated) return action.title; + return `${action.title} · ${action.scope === "user" ? "Just me" : "Organization"}`; +} diff --git a/apps/web/app/.well-known/cap-app-store-keys.json/route.ts b/apps/web/app/.well-known/cap-app-store-keys.json/route.ts new file mode 100644 index 00000000000..b13bacac325 --- /dev/null +++ b/apps/web/app/.well-known/cap-app-store-keys.json/route.ts @@ -0,0 +1,12 @@ +import { appStorePublicKeys } from "@/lib/app-store/signing"; + +export const dynamic = "force-dynamic"; + +export function GET() { + return Response.json(appStorePublicKeys(), { + headers: { + "cache-control": "public, max-age=3600", + "access-control-allow-origin": "*", + }, + }); +} diff --git a/apps/web/app/api/app-store/[...route]/route.ts b/apps/web/app/api/app-store/[...route]/route.ts new file mode 100644 index 00000000000..f4cf33fc671 --- /dev/null +++ b/apps/web/app/api/app-store/[...route]/route.ts @@ -0,0 +1,300 @@ +import { db } from "@cap/database"; +import { users } from "@cap/database/schema"; +import { CurrentUser, HttpAuthMiddleware, Video } from "@cap/web-domain"; +import { + HttpApi, + HttpApiBuilder, + HttpApiEndpoint, + HttpApiGroup, + HttpServerRequest, + HttpServerResponse, +} from "@effect/platform"; +import { eq } from "drizzle-orm"; +import { Effect, Layer, Schema } from "effect"; +import { userOrganizations } from "@/lib/app-store/access"; +import { catalogForClient } from "@/lib/app-store/catalog"; +import { + listCapActions, + runCapAction, + sendUninstalled, +} from "@/lib/app-store/delivery"; +import { + announceInBackground, + announceLifecycle, +} from "@/lib/app-store/events"; +import { + AppStoreError, + installApp, + listInstallations, + uninstallApp, + updateInstallation, +} from "@/lib/app-store/installations"; +import { canManageOrganizationSettings } from "@/lib/permissions/roles"; +import { apiToHandler } from "@/lib/server"; + +const SettingsPayload = Schema.Record({ + key: Schema.String.pipe(Schema.maxLength(64)), + value: Schema.Union( + Schema.String.pipe(Schema.maxLength(4_000)), + Schema.Boolean, + Schema.Null, + ), +}); + +const InstallPayload = Schema.Struct({ + appId: Schema.String.pipe(Schema.maxLength(64)), + scope: Schema.Literal("user", "organization"), + organizationId: Schema.optional( + Schema.NullOr(Schema.String.pipe(Schema.maxLength(64))), + ), + settings: Schema.optional(SettingsPayload), +}); + +const UpdatePayload = Schema.Struct({ + settings: Schema.optional(SettingsPayload), + acceptUpdate: Schema.optional(Schema.Boolean), + resume: Schema.optional(Schema.Boolean), +}); + +const InstallationPath = Schema.Struct({ + installationId: Schema.String.pipe(Schema.maxLength(64)), +}); + +const CapPath = Schema.Struct({ videoId: Video.VideoId }); + +const RunActionPayload = Schema.Struct({ + installationId: Schema.String.pipe(Schema.maxLength(64)), + actionId: Schema.String.pipe(Schema.maxLength(64)), +}); + +class Api extends HttpApi.make("AppStoreApi") + .add( + HttpApiGroup.make("public").add( + HttpApiEndpoint.get("catalog", "/api/app-store/catalog").setUrlParams( + Schema.Struct({ apiVersion: Schema.optional(Schema.NumberFromString) }), + ), + ), + ) + .add( + HttpApiGroup.make("account") + .add(HttpApiEndpoint.get("installations", "/api/app-store/installations")) + .add( + HttpApiEndpoint.post( + "install", + "/api/app-store/installations", + ).setPayload(InstallPayload), + ) + .add( + HttpApiEndpoint.post( + "update", + "/api/app-store/installations/:installationId", + ) + .setPath(InstallationPath) + .setPayload(UpdatePayload), + ) + .add( + HttpApiEndpoint.del( + "uninstall", + "/api/app-store/installations/:installationId", + ).setPath(InstallationPath), + ) + .add( + HttpApiEndpoint.get( + "capActions", + "/api/app-store/caps/:videoId/actions", + ).setPath(CapPath), + ) + .add( + HttpApiEndpoint.post( + "runCapAction", + "/api/app-store/caps/:videoId/actions", + ) + .setPath(CapPath) + .setPayload(RunActionPayload), + ) + .middleware(HttpAuthMiddleware), + ) {} + +const noStore = { "cache-control": "private, no-store" }; + +const json = (body: unknown, status = 200) => + HttpServerResponse.unsafeJson(body, { status, headers: noStore }); + +const STATUS: Record = { + not_found: 404, + forbidden: 403, + invalid: 422, + conflict: 409, + unavailable: 502, + rate_limited: 429, +}; + +const respond = ( + work: () => Promise, + toBody: (value: A) => unknown = (value) => value, + status = 200, +) => + Effect.tryPromise({ try: work, catch: (error) => error }).pipe( + Effect.map((value) => json(toBody(value), status)), + Effect.catchAll((error) => { + if (error instanceof AppStoreError) { + return Effect.succeed( + json( + { + error: error.message, + code: error.code, + fieldErrors: error.fieldErrors, + }, + STATUS[error.code], + ), + ); + } + console.error("[app-store] Request failed", error); + return Effect.succeed( + json({ error: "Something went wrong", code: "internal" }, 500), + ); + }), + ); + +const ApiLive = HttpApiBuilder.api(Api).pipe( + Layer.provide( + HttpApiBuilder.group(Api, "public", (handlers) => + handlers.handle("catalog", ({ urlParams }) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const catalog = catalogForClient(urlParams.apiVersion ?? null); + const etag = `"${catalog.revision}-${urlParams.apiVersion ?? "all"}"`; + const headers = { + etag, + "cache-control": "public, max-age=60, stale-while-revalidate=600", + }; + if (request.headers["if-none-match"] === etag) { + return HttpServerResponse.empty({ status: 304, headers }); + } + return HttpServerResponse.unsafeJson(catalog, { headers }); + }), + ), + ), + ), + Layer.provide( + HttpApiBuilder.group(Api, "account", (handlers) => + handlers + .handle("installations", () => + Effect.gen(function* () { + const user = yield* CurrentUser; + return yield* respond(async () => { + const [installations, organizations] = await Promise.all([ + listInstallations(user.id), + userOrganizations(user.id), + ]); + return { + installations, + activeOrganizationId: user.activeOrganizationId, + organizations: organizations.map((organization) => ({ + id: organization.id, + name: organization.name, + canManage: canManageOrganizationSettings(organization.role), + adminsOnly: organization.adminsOnly, + })), + }; + }); + }), + ) + .handle("install", ({ payload }) => + Effect.gen(function* () { + const user = yield* CurrentUser; + return yield* respond( + async () => { + const result = await installApp(user.id, { + appId: payload.appId, + scope: payload.scope, + organizationId: payload.organizationId ?? null, + settings: payload.settings, + activeOrganizationId: user.activeOrganizationId, + }); + announceLifecycle(result.row.id, "installed"); + return result.view; + }, + (view) => ({ installation: view }), + 201, + ); + }), + ) + .handle("update", ({ path, payload }) => + Effect.gen(function* () { + const user = yield* CurrentUser; + return yield* respond( + async () => { + const result = await updateInstallation( + user.id, + path.installationId, + payload, + ); + if (result.settingsChanged) { + announceLifecycle(result.row.id, "settings.updated"); + } + return result.view; + }, + (view) => ({ installation: view }), + ); + }), + ) + .handle("uninstall", ({ path }) => + Effect.gen(function* () { + const user = yield* CurrentUser; + return yield* respond( + async () => { + const { row, settings } = await uninstallApp( + user.id, + path.installationId, + ); + announceInBackground( + `uninstalled for ${row.id}`, + sendUninstalled(row, settings), + ); + return null; + }, + () => ({ ok: true }), + ); + }), + ) + .handle("capActions", ({ path }) => + Effect.gen(function* () { + const user = yield* CurrentUser; + return yield* respond( + () => listCapActions(user.id, path.videoId), + (actions) => ({ actions }), + ); + }), + ) + .handle("runCapAction", ({ path, payload }) => + Effect.gen(function* () { + const user = yield* CurrentUser; + return yield* respond( + async () => { + const [profile] = await db() + .select({ name: users.name }) + .from(users) + .where(eq(users.id, user.id)) + .limit(1); + return runCapAction({ + userId: user.id, + userName: profile?.name ?? null, + installationId: payload.installationId, + actionId: payload.actionId, + videoId: path.videoId, + }); + }, + (result) => ({ result }), + ); + }), + ), + ), + ), +); + +const handler = apiToHandler(ApiLive); + +export const GET = handler; +export const POST = handler; +export const DELETE = handler; diff --git a/apps/web/app/api/cron/cleanup-agent-api/route.ts b/apps/web/app/api/cron/cleanup-agent-api/route.ts index a4d2ed5dc1d..e93c12c4f78 100644 --- a/apps/web/app/api/cron/cleanup-agent-api/route.ts +++ b/apps/web/app/api/cron/cleanup-agent-api/route.ts @@ -1,6 +1,7 @@ import { timingSafeEqual } from "node:crypto"; import { NextResponse } from "next/server"; import { cleanupExpiredAgentApiRecords } from "@/lib/agent-api-cleanup"; +import { cleanupAppStoreEvents } from "@/lib/app-store/cleanup"; import { cleanupExpiredMcpRecords } from "@/lib/mcp-cleanup"; export const dynamic = "force-dynamic"; @@ -28,5 +29,8 @@ export async function GET(request: Request) { await cleanupExpiredMcpRecords().catch((error: unknown) => { console.error("MCP credential cleanup failed", error); }); + await cleanupAppStoreEvents().catch((error: unknown) => { + console.error("App Store event cleanup failed", error); + }); return NextResponse.json({ success: true, deleted }); } diff --git a/apps/web/lib/Notification.ts b/apps/web/lib/Notification.ts index e030de89af3..b6ea6055f4d 100644 --- a/apps/web/lib/Notification.ts +++ b/apps/web/lib/Notification.ts @@ -10,6 +10,7 @@ import { Comment, User, Video } from "@cap/web-domain"; import { and, eq, gte, inArray, isNull, ne, or, sql } from "drizzle-orm"; import type { UserPreferences } from "@/app/(org)/dashboard/dashboard-data"; import { getSessionHash } from "@/lib/anonymous-names"; +import { announceAppStoreEvent } from "@/lib/app-store/announce"; import { queueNotificationPush } from "@/lib/mobile-push"; export type NotificationType = Notification["type"]; @@ -72,6 +73,15 @@ export async function createNotification( throw new Error(`Video not found for videoId: ${notification.videoId}`); } + if ( + (notification.type === "comment" || notification.type === "reply") && + notification.comment?.id + ) { + announceAppStoreEvent("cap.comment.created", videoExists.id, { + commentId: notification.comment.id, + }); + } + const [ownerResult] = await db() .select({ id: users.id, diff --git a/apps/web/lib/app-store/access.ts b/apps/web/lib/app-store/access.ts new file mode 100644 index 00000000000..33f7a47f0d3 --- /dev/null +++ b/apps/web/lib/app-store/access.ts @@ -0,0 +1,103 @@ +import { db } from "@cap/database"; +import { + organizationMembers, + organizations, + sharedVideos, +} from "@cap/database/schema"; +import type { Organisation, User, Video } from "@cap/web-domain"; +import { and, eq, isNull, or } from "drizzle-orm"; +import { + canManageOrganizationSettings, + getEffectiveOrganizationRole, + type OrganizationRole, +} from "@/lib/permissions/roles"; + +export type UserOrganization = { + id: Organisation.OrganisationId; + name: string; + role: OrganizationRole; + adminsOnly: boolean; +}; + +export async function userOrganizations( + userId: User.UserId, +): Promise { + const rows = await db() + .select({ + id: organizations.id, + name: organizations.name, + ownerId: organizations.ownerId, + settings: organizations.settings, + memberRole: organizationMembers.role, + }) + .from(organizations) + .leftJoin( + organizationMembers, + and( + eq(organizationMembers.organizationId, organizations.id), + eq(organizationMembers.userId, userId), + ), + ) + .where( + and( + isNull(organizations.tombstoneAt), + or( + eq(organizations.ownerId, userId), + eq(organizationMembers.userId, userId), + ), + ), + ); + + const byId = new Map(); + for (const row of rows) { + const role = getEffectiveOrganizationRole({ + userId, + ownerId: row.ownerId, + memberRole: row.memberRole, + }); + if (!role) continue; + const existing = byId.get(row.id); + if (existing && rank(existing.role) >= rank(role)) continue; + byId.set(row.id, { + id: row.id, + name: row.name, + role, + adminsOnly: row.settings?.appStoreAdminsOnly === true, + }); + } + return [...byId.values()]; +} + +const rank = (role: OrganizationRole) => + role === "owner" ? 3 : role === "admin" ? 2 : 1; + +export const canManageOrganizationApps = ( + organization: UserOrganization | undefined, +) => !!organization && canManageOrganizationSettings(organization.role); + +export const memberMayInstallConnections = ( + organization: UserOrganization | undefined, +) => + !organization || + !organization.adminsOnly || + canManageOrganizationSettings(organization.role); + +// Organization installs only see Caps their owners shared with the +// organization. A Cap that merely belongs to the organization can still be +// private to its owner. +export async function isSharedWithOrganization( + videoId: Video.VideoId, + organizationId: Organisation.OrganisationId, +) { + const [row] = await db() + .select({ id: sharedVideos.id }) + .from(sharedVideos) + .where( + and( + eq(sharedVideos.videoId, videoId), + eq(sharedVideos.organizationId, organizationId), + ), + ) + .limit(1); + return !!row; +} diff --git a/apps/web/lib/app-store/announce.ts b/apps/web/lib/app-store/announce.ts new file mode 100644 index 00000000000..a1c24808a53 --- /dev/null +++ b/apps/web/lib/app-store/announce.ts @@ -0,0 +1,49 @@ +import type { CapEventType } from "@cap/app-store"; +import type { Video } from "@cap/web-domain"; +import { after } from "next/server"; + +type EventOptions = { commentId?: string }; + +// Kept free of database and workflow imports: upload, transcription and +// comment paths import this module, and the emitter only loads when an event +// actually fires. +async function emit( + type: CapEventType, + videoId: Video.VideoId, + options: EventOptions, +) { + try { + const { emitAppStoreEvent } = await import("./events"); + await emitAppStoreEvent(type, videoId, options); + } catch (error) { + console.error("[app-store] Event failed", { + type, + videoId, + message: error instanceof Error ? error.message : String(error), + }); + } +} + +export function announceAppStoreEvent( + type: CapEventType, + videoId: Video.VideoId, + options: EventOptions = {}, +): void { + // Hand after() a callback, not a running promise, so the event lookup and + // the per-installation enqueues start once the response is sent instead of + // competing with the request that triggered them. + try { + after(() => emit(type, videoId, options)); + } catch { + void emit(type, videoId, options); + } +} + +export const emitAppStoreEventSafely = ( + type: CapEventType, + videoId: Video.VideoId, + options: EventOptions = {}, +) => emit(type, videoId, options); + +export const emitCapReadySafely = (videoId: Video.VideoId) => + emit("cap.ready", videoId, {}); diff --git a/apps/web/lib/app-store/catalog.ts b/apps/web/lib/app-store/catalog.ts new file mode 100644 index 00000000000..50ae3bb652e --- /dev/null +++ b/apps/web/lib/app-store/catalog.ts @@ -0,0 +1,31 @@ +import { + APP_STORE_API_VERSIONS, + Catalog, + type CatalogApp, +} from "@cap/app-store"; +import { Schema } from "effect"; +import generated from "./generated/catalog.json"; + +let cached: Catalog | null = null; + +export function getAppStoreCatalog(): Catalog { + if (!cached) cached = Schema.decodeUnknownSync(Catalog)(generated); + return cached; +} + +export function getCatalogApp(appId: string): CatalogApp | null { + return getAppStoreCatalog().apps.find((app) => app.id === appId) ?? null; +} + +export function isSupportedApiVersion(apiVersion: number) { + return APP_STORE_API_VERSIONS.some((version) => version === apiVersion); +} + +export function catalogForClient(maxApiVersion: number | null): Catalog { + const catalog = getAppStoreCatalog(); + if (maxApiVersion === null) return catalog; + return { + ...catalog, + apps: catalog.apps.filter((app) => app.apiVersion <= maxApiVersion), + }; +} diff --git a/apps/web/lib/app-store/cleanup.ts b/apps/web/lib/app-store/cleanup.ts new file mode 100644 index 00000000000..597e3ecb314 --- /dev/null +++ b/apps/web/lib/app-store/cleanup.ts @@ -0,0 +1,36 @@ +import { db } from "@cap/database"; +import { appStoreEvents } from "@cap/database/schema"; +import { lt } from "drizzle-orm"; + +// Event rows only stop the same event reaching an app twice. cap.ready fires +// for at most a week after a Cap is made and retries finish within hours, so +// a month of rows covers every repeat that matters. +export const APP_STORE_EVENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; + +const affectedRows = (result: unknown) => + Array.isArray(result) + ? ((result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0) + : ((result as { affectedRows?: number }).affectedRows ?? 0); + +export async function cleanupAppStoreEvents(input?: { + now?: Date; + batchSize?: number; + maxBatches?: number; +}) { + const now = input?.now ?? new Date(); + const batchSize = Math.min(Math.max(input?.batchSize ?? 5_000, 1), 5_000); + const maxBatches = Math.min(Math.max(input?.maxBatches ?? 20, 1), 50); + const cutoff = new Date(now.getTime() - APP_STORE_EVENT_RETENTION_MS); + let deleted = 0; + for (let batch = 0; batch < maxBatches; batch += 1) { + const count = affectedRows( + await db() + .delete(appStoreEvents) + .where(lt(appStoreEvents.createdAt, cutoff)) + .limit(batchSize), + ); + deleted += count; + if (count < batchSize) break; + } + return deleted; +} diff --git a/apps/web/lib/app-store/connection.ts b/apps/web/lib/app-store/connection.ts new file mode 100644 index 00000000000..471e629491a --- /dev/null +++ b/apps/web/lib/app-store/connection.ts @@ -0,0 +1,215 @@ +import { + type CapRequest, + CONNECTION_TIMEOUT_MS, + isFirstPartyConnectionUrl, +} from "@cap/app-store"; +import { type CapRequestKind, signCapRequest } from "@cap/app-store/signing"; +import { nanoId } from "@cap/database/helpers"; +import { serverEnv } from "@cap/env"; +import { checkWebhookUrl } from "@/lib/developer-webhook-delivery"; +import { requestPublicOnly } from "@/lib/storage-fetch"; +import { firstPartyConnectionHandler } from "./first-party"; +import { appStoreSigningKey } from "./signing"; + +export const RESPONSE_BODY_MAX_BYTES = 64 * 1024; + +export type ConnectionErrorCode = + | "invalid_url" + | "private_address" + | "timeout" + | "connection_failed" + | "redirect" + | "http_error" + | "response_too_large"; + +export type ConnectionResult = + | { ok: true; status: number; body: string | null; durationMs: number } + | { + ok: false; + status: number | null; + errorCode: ConnectionErrorCode; + durationMs: number; + }; + +export type ConnectionTarget = { appId: string; url: string }; + +export const connectionPath = ( + request: CapRequest, +): "lifecycle" | "events" | `actions/${string}` => + request.kind === "lifecycle" + ? "lifecycle" + : request.kind === "event" + ? "events" + : `actions/${encodeURIComponent(request.action)}`; + +const requestKind = (request: CapRequest): CapRequestKind => request.kind; + +async function readLimited(response: Response): Promise { + if (!response.body) return ""; + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > RESPONSE_BODY_MAX_BYTES) { + await reader.cancel().catch(() => {}); + return null; + } + chunks.push(value); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return new TextDecoder().decode(bytes); +} + +export async function sendConnectionRequest( + target: ConnectionTarget, + request: CapRequest, + options: { + readBody?: boolean; + timeoutMs?: number; + requestId?: string; + fetcher?: (url: string, init: RequestInit) => Promise; + } = {}, +): Promise { + const started = Date.now(); + const elapsed = () => Date.now() - started; + const body = JSON.stringify(request); + const requestId = options.requestId ?? `req_${nanoId()}`; + const headers = { + "content-type": "application/json", + "user-agent": "Cap-App-Store/1.0", + ...signCapRequest({ + key: appStoreSigningKey(), + body, + requestId, + kind: requestKind(request), + }), + }; + const path = connectionPath(request); + const firstParty = isFirstPartyConnectionUrl(target.url); + const url = firstParty + ? `${serverEnv().WEB_URL}${target.url}/${path}` + : `${target.url}/${path}`; + + const abort = new AbortController(); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + abort.abort(); + }, options.timeoutMs ?? CONNECTION_TIMEOUT_MS); + const deadline = new Promise((_, reject) => { + abort.signal.addEventListener( + "abort", + () => reject(new Error("Connection request timed out")), + { once: true }, + ); + }); + deadline.catch(() => {}); + + try { + let response: Response; + if (firstParty) { + const handler = firstPartyConnectionHandler(target.appId); + if (!handler) { + return { + ok: false, + status: null, + errorCode: "connection_failed", + durationMs: elapsed(), + }; + } + response = await Promise.race([ + handler( + new Request(url, { + method: "POST", + headers, + body, + signal: abort.signal, + }), + ), + deadline, + ]); + } else { + const check = checkWebhookUrl(url); + check.catch(() => {}); + const problem = await Promise.race([check, deadline]); + if (problem) { + return { + ok: false, + status: null, + errorCode: + problem === "private_address" ? "private_address" : "invalid_url", + durationMs: elapsed(), + }; + } + response = await (options.fetcher ?? requestPublicOnly)(url, { + method: "POST", + headers, + body, + signal: abort.signal, + }); + } + + const status = response.status; + if (status >= 300 && status < 400) { + await response.body?.cancel().catch(() => {}); + return { + ok: false, + status, + errorCode: "redirect", + durationMs: elapsed(), + }; + } + if (status < 200 || status >= 300) { + await response.body?.cancel().catch(() => {}); + return { + ok: false, + status, + errorCode: "http_error", + durationMs: elapsed(), + }; + } + if (!options.readBody) { + await response.body?.cancel().catch(() => {}); + return { ok: true, status, body: null, durationMs: elapsed() }; + } + const text = await readLimited(response); + if (text === null) { + return { + ok: false, + status, + errorCode: "response_too_large", + durationMs: elapsed(), + }; + } + return { ok: true, status, body: text, durationMs: elapsed() }; + } catch (error) { + if (timedOut) { + return { + ok: false, + status: null, + errorCode: "timeout", + durationMs: elapsed(), + }; + } + return { + ok: false, + status: null, + errorCode: + error instanceof Error && /private address/i.test(error.message) + ? "private_address" + : "connection_failed", + durationMs: elapsed(), + }; + } finally { + clearTimeout(timer); + abort.abort(); + } +} diff --git a/apps/web/lib/app-store/delivery.ts b/apps/web/lib/app-store/delivery.ts new file mode 100644 index 00000000000..503f4596886 --- /dev/null +++ b/apps/web/lib/app-store/delivery.ts @@ -0,0 +1,361 @@ +import { + type ActionResult, + type CapEventType, + type ConnectionPermission, + type EventRequest, + type LifecycleRequest, + parseActionResult, +} from "@cap/app-store"; +import { db } from "@cap/database"; +import { appStoreInstallations } from "@cap/database/schema"; +import type { User, Video } from "@cap/web-domain"; +import { and, eq, or, sql } from "drizzle-orm"; +import { + WEBHOOK_DISABLE_AFTER_FAILURES, + WEBHOOK_DISABLE_AFTER_MS, +} from "@/lib/developer-webhook-events"; +import { + isSharedWithOrganization, + memberMayInstallConnections, + userOrganizations, +} from "./access"; +import { getCatalogApp } from "./catalog"; +import { type ConnectionResult, sendConnectionRequest } from "./connection"; +import { + AppStoreError, + enforceAppStoreRateLimit, + eventIsGranted, + type InstallationRow, + installationRef, + readInstallationSettings, +} from "./installations"; +import { + buildCapPayload, + type CapRecord, + loadCapRecord, + loadCommentPayload, +} from "./payload"; + +export const DISABLED_BY_FAILURES = "delivery_failures"; + +export type DeliveryOutcome = "delivered" | "retry" | "dropped"; + +export type AppStoreDeliveryJob = + | { + kind: "event"; + installationId: string; + eventId: string; + type: CapEventType; + videoId: string; + commentId?: string; + createdAt: string; + } + | { + kind: "lifecycle"; + installationId: string; + type: "installed" | "settings.updated"; + }; + +const appRef = (row: InstallationRow) => ({ + id: row.appId, + version: getCatalogApp(row.appId)?.version ?? row.appVersion, +}); + +async function loadRow(installationId: string) { + const [row] = await db() + .select() + .from(appStoreInstallations) + .where(eq(appStoreInstallations.id, installationId)) + .limit(1); + return row ?? null; +} + +export async function capVisibleToInstallation( + row: InstallationRow, + record: CapRecord, +): Promise { + if (row.scope === "organization") { + return ( + !!row.organizationId && + record.video.orgId === row.organizationId && + (await isSharedWithOrganization(record.video.id, row.organizationId)) + ); + } + if (record.video.ownerId !== row.userId || !row.userId) return false; + if (!record.video.orgId) return true; + const organizations = await userOrganizations(row.userId as User.UserId); + return memberMayInstallConnections( + organizations.find((org) => org.id === record.video.orgId), + ); +} + +const shouldRetry = (result: ConnectionResult) => + !result.ok && + (result.status === null || + result.status === 408 || + result.status === 429 || + result.status >= 500 || + result.errorCode === "redirect"); + +export async function recordConnectionResult( + installationId: string, + result: ConnectionResult, + now: Date = new Date(), +) { + await db().transaction(async (tx) => { + const [row] = await tx + .select({ + consecutiveFailures: appStoreInstallations.consecutiveFailures, + failingSince: appStoreInstallations.failingSince, + status: appStoreInstallations.status, + }) + .from(appStoreInstallations) + .where(eq(appStoreInstallations.id, installationId)) + .for("update"); + if (!row) return; + const lastDeliveryStatus = result.ok + ? String(result.status) + : (result.status?.toString() ?? result.errorCode); + if (result.ok) { + await tx + .update(appStoreInstallations) + .set({ + consecutiveFailures: 0, + failingSince: null, + lastDeliveryAt: now, + lastDeliveryStatus, + }) + .where(eq(appStoreInstallations.id, installationId)); + return; + } + const failures = row.consecutiveFailures + 1; + const failingSince = row.failingSince ?? now; + const disable = + row.status === "active" && + failures >= WEBHOOK_DISABLE_AFTER_FAILURES && + now.getTime() - failingSince.getTime() >= WEBHOOK_DISABLE_AFTER_MS; + await tx + .update(appStoreInstallations) + .set({ + consecutiveFailures: sql`${appStoreInstallations.consecutiveFailures} + 1`, + failingSince, + lastDeliveryAt: now, + lastDeliveryStatus, + ...(disable + ? { + status: "disabled" as const, + disabledReason: DISABLED_BY_FAILURES, + } + : {}), + }) + .where(eq(appStoreInstallations.id, installationId)); + }); +} + +export async function deliverAppStoreJob( + job: AppStoreDeliveryJob, +): Promise { + const row = await loadRow(job.installationId); + if (!row || row.status !== "active") return "dropped"; + const app = getCatalogApp(row.appId); + if (!app?.connection) return "dropped"; + const settings = await readInstallationSettings(row); + + let request: EventRequest | LifecycleRequest; + if (job.kind === "lifecycle") { + request = { + kind: "lifecycle", + type: job.type, + app: appRef(row), + installation: installationRef(row), + settings, + }; + } else { + if (!eventIsGranted(row, job.type)) return "dropped"; + const record = await loadCapRecord(job.videoId as Video.VideoId); + if (!record || !(await capVisibleToInstallation(row, record))) { + return "dropped"; + } + const permissions = row.grantedPermissions as ConnectionPermission[]; + const comment = job.commentId + ? await loadCommentPayload(job.commentId) + : undefined; + if (job.commentId && !comment) return "dropped"; + request = { + kind: "event", + id: job.eventId, + type: job.type, + createdAt: job.createdAt, + app: appRef(row), + installation: installationRef(row), + settings, + data: { + cap: await buildCapPayload(record, permissions), + ...(comment ? { comment } : {}), + }, + }; + } + + const result = await sendConnectionRequest( + { appId: row.appId, url: app.connection.url }, + request, + { requestId: job.kind === "event" ? job.eventId : undefined }, + ); + await recordConnectionResult(row.id, result); + if (result.ok) return "delivered"; + return shouldRetry(result) ? "retry" : "dropped"; +} + +export async function sendUninstalled( + row: InstallationRow, + settings: Awaited>, +) { + const app = getCatalogApp(row.appId); + if (!app?.connection) return; + await sendConnectionRequest( + { appId: row.appId, url: app.connection.url }, + { + kind: "lifecycle", + type: "uninstalled", + app: appRef(row), + installation: installationRef(row), + settings, + }, + ).catch(() => undefined); +} + +export type CapAction = { + installationId: string; + appId: string; + appName: string; + iconUrl: string; + actionId: string; + title: string; + scope: "user" | "organization"; +}; + +async function actionRowsForCap(userId: User.UserId, record: CapRecord) { + const organizations = await userOrganizations(userId); + const capOrganization = organizations.find( + (org) => org.id === record.video.orgId, + ); + // Actions send the Cap's details to another service, so only its owner can + // run them. Organization membership alone does not grant access to a + // private Cap. + if (record.video.ownerId !== userId) return []; + + const scopes = [ + and( + eq(appStoreInstallations.scope, "user"), + eq(appStoreInstallations.userId, userId), + ), + ]; + if (capOrganization) { + scopes.push( + and( + eq(appStoreInstallations.scope, "organization"), + eq(appStoreInstallations.organizationId, capOrganization.id), + ), + ); + } + const rows = await db() + .select() + .from(appStoreInstallations) + .where(and(eq(appStoreInstallations.status, "active"), or(...scopes))); + return rows.filter((row) => { + if (row.scope === "user") { + return ( + row.userId === userId && memberMayInstallConnections(capOrganization) + ); + } + return !!capOrganization && row.organizationId === capOrganization.id; + }); +} + +export async function listCapActions( + userId: User.UserId, + videoId: Video.VideoId, +): Promise { + const record = await loadCapRecord(videoId); + if (!record) return []; + const rows = await actionRowsForCap(userId, record); + const actions: CapAction[] = []; + for (const row of rows) { + const app = getCatalogApp(row.appId); + for (const action of app?.connection?.actions ?? []) { + if (!app) continue; + actions.push({ + installationId: row.id, + appId: app.id, + appName: app.name, + iconUrl: app.icon.url, + actionId: action.id, + title: action.title, + scope: row.scope, + }); + } + } + return actions.sort((a, b) => a.title.localeCompare(b.title)); +} + +export async function runCapAction(input: { + userId: User.UserId; + userName: string | null; + installationId: string; + actionId: string; + videoId: Video.VideoId; +}): Promise { + const record = await loadCapRecord(input.videoId); + if (!record) throw new AppStoreError("not_found", "This Cap was not found"); + const rows = await actionRowsForCap(input.userId, record); + const row = rows.find((candidate) => candidate.id === input.installationId); + if (!row) throw new AppStoreError("not_found", "This app is not installed"); + const app = getCatalogApp(row.appId); + const action = app?.connection?.actions.find( + (candidate) => candidate.id === input.actionId, + ); + if (!app?.connection || !action) { + throw new AppStoreError("not_found", "This action is not available"); + } + await enforceAppStoreRateLimit("action", input.userId); + + const result = await sendConnectionRequest( + { appId: app.id, url: app.connection.url }, + { + kind: "action", + action: action.id, + app: appRef(row), + installation: installationRef(row), + settings: await readInstallationSettings(row), + user: { id: input.userId, name: input.userName }, + data: { + cap: await buildCapPayload( + record, + row.grantedPermissions as ConnectionPermission[], + ), + }, + }, + { readBody: true }, + ); + if (!result.ok) { + throw new AppStoreError( + "unavailable", + result.errorCode === "timeout" + ? `${app.name} took too long to respond` + : `${app.name} could not complete this action`, + ); + } + let parsed: ActionResult | null = null; + try { + parsed = parseActionResult(JSON.parse(result.body ?? "")); + } catch { + parsed = null; + } + if (!parsed) { + throw new AppStoreError( + "unavailable", + `${app.name} sent a response Cap could not read`, + ); + } + return parsed; +} diff --git a/apps/web/lib/app-store/events.ts b/apps/web/lib/app-store/events.ts new file mode 100644 index 00000000000..0f1c3f65e36 --- /dev/null +++ b/apps/web/lib/app-store/events.ts @@ -0,0 +1,180 @@ +import { createHash } from "node:crypto"; +import type { CapEventType } from "@cap/app-store"; +import { db } from "@cap/database"; +import { + appStoreEvents, + appStoreInstallations, + videos, +} from "@cap/database/schema"; +import type { Video } from "@cap/web-domain"; +import { and, eq, or } from "drizzle-orm"; +import { after } from "next/server"; +import { start } from "workflow/api"; +import { deliverAppStoreRequestWorkflow } from "@/workflows/deliver-app-store-request"; +import { isSharedWithOrganization } from "./access"; +import { getCatalogApp } from "./catalog"; +import type { AppStoreDeliveryJob } from "./delivery"; +import { eventIsGranted } from "./installations"; + +export const appStoreEventId = ( + type: CapEventType, + videoId: string, + subjectId = "", +) => + `evt_${createHash("sha256") + .update(`${type}:${videoId}:${subjectId}`) + .digest("hex") + .slice(0, 32)}`; + +export const CAP_READY_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; + +export function isNewRecording( + video: Pick, + now: number = Date.now(), +) { + if (video.metadata?.loomImportRun || video.metadata?.loomImportUpload) { + return false; + } + return now - video.createdAt.getTime() <= CAP_READY_MAX_AGE_MS; +} + +async function startJobs(jobs: AppStoreDeliveryJob[]) { + const started = await Promise.allSettled( + jobs.map((job) => start(deliverAppStoreRequestWorkflow, [job])), + ); + const failed = started.filter((result) => result.status === "rejected"); + if (failed.length > 0) { + console.error("[app-store] Failed to queue deliveries", { + failed: failed.length, + }); + } + return jobs.length - failed.length; +} + +export const appStoreDeliveryKey = (eventId: string, installationId: string) => + `dlv_${createHash("sha256") + .update(`${eventId}:${installationId}`) + .digest("hex") + .slice(0, 40)}`; + +// The marker is per installation and removed again when the workflow cannot +// be started, so a failed enqueue is retried by the next emission of the same +// event instead of being suppressed forever. +async function queueEventDelivery( + job: Extract, +): Promise { + const key = appStoreDeliveryKey(job.eventId, job.installationId); + const [inserted] = await db() + .insert(appStoreEvents) + .ignore() + .values({ id: key, type: job.type, videoId: job.videoId as Video.VideoId }); + if (inserted.affectedRows === 0) return false; + try { + await start(deliverAppStoreRequestWorkflow, [job]); + return true; + } catch (error) { + await db() + .delete(appStoreEvents) + .where(eq(appStoreEvents.id, key)) + .catch(() => undefined); + console.error("[app-store] Failed to queue a delivery", { + installationId: job.installationId, + message: error instanceof Error ? error.message : String(error), + }); + return false; + } +} + +export async function emitAppStoreEvent( + type: CapEventType, + videoId: Video.VideoId, + options: { commentId?: string } = {}, +): Promise { + const [video] = await db() + .select({ + ownerId: videos.ownerId, + orgId: videos.orgId, + createdAt: videos.createdAt, + metadata: videos.metadata, + }) + .from(videos) + .where(eq(videos.id, videoId)) + .limit(1); + if (!video) return 0; + if (type === "cap.ready" && !isNewRecording(video)) return 0; + + const scopes = [ + and( + eq(appStoreInstallations.scope, "user"), + eq(appStoreInstallations.userId, video.ownerId), + ), + ]; + if (video.orgId && (await isSharedWithOrganization(videoId, video.orgId))) { + scopes.push( + and( + eq(appStoreInstallations.scope, "organization"), + eq(appStoreInstallations.organizationId, video.orgId), + ), + ); + } + const installations = ( + await db() + .select({ + id: appStoreInstallations.id, + appId: appStoreInstallations.appId, + grantedEvents: appStoreInstallations.grantedEvents, + grantedPermissions: appStoreInstallations.grantedPermissions, + }) + .from(appStoreInstallations) + .where(and(eq(appStoreInstallations.status, "active"), or(...scopes))) + ).filter( + (row) => + eventIsGranted(row, type) && !!getCatalogApp(row.appId)?.connection, + ); + if (installations.length === 0) return 0; + + const eventId = appStoreEventId(type, videoId, options.commentId); + const createdAt = new Date().toISOString(); + const queued = await Promise.all( + installations.map((row) => + queueEventDelivery({ + kind: "event", + installationId: row.id, + eventId, + type, + videoId, + commentId: options.commentId, + createdAt, + }), + ), + ); + return queued.filter(Boolean).length; +} + +function runInBackground(label: string, work: Promise) { + const guarded = work.catch((error: unknown) => { + console.error("[app-store] Background task failed", { + task: label, + message: error instanceof Error ? error.message : String(error), + }); + }); + try { + after(guarded); + } catch { + void guarded; + } +} + +export function announceLifecycle( + installationId: string, + type: "installed" | "settings.updated", +): void { + runInBackground( + `${type} for ${installationId}`, + startJobs([{ kind: "lifecycle", installationId, type }]), + ); +} + +export function announceInBackground(label: string, work: Promise) { + runInBackground(label, work); +} diff --git a/apps/web/lib/app-store/first-party/discord.ts b/apps/web/lib/app-store/first-party/discord.ts new file mode 100644 index 00000000000..a6bea8b7304 --- /dev/null +++ b/apps/web/lib/app-store/first-party/discord.ts @@ -0,0 +1,92 @@ +import type { ActionResult, CapPayload } from "@cap/app-store"; +import { FIRST_PARTY_CONNECTION_PREFIX } from "@cap/app-store"; +import { capJson, readVerifiedCapRequest } from "./verify"; + +const DISCORD_WEBHOOK = + /^https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d{5,30}\/[A-Za-z0-9_-]{20,200}$/; + +export const isDiscordWebhookUrl = (value: unknown): value is string => + typeof value === "string" && DISCORD_WEBHOOK.test(value); + +export function discordMessage(cap: CapPayload) { + const title = cap.title.replace(/[*_~`|>]/g, "").slice(0, 200); + return { + content: `**${title}**\n${cap.url}`, + username: "Cap", + allowed_mentions: { parse: [] }, + }; +} + +export async function postToDiscord( + webhookUrl: string, + cap: CapPayload, + fetcher: typeof fetch = fetch, +): Promise<"posted" | "rejected" | "retry"> { + const response = await fetcher(webhookUrl, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(discordMessage(cap)), + redirect: "manual", + signal: AbortSignal.timeout(8_000), + }); + await response.body?.cancel().catch(() => {}); + if (response.ok) return "posted"; + if (response.status === 429 || response.status >= 500) return "retry"; + return "rejected"; +} + +const toast = (message: string): ActionResult => ({ type: "toast", message }); + +export async function discordConnection(request: Request): Promise { + const verified = await readVerifiedCapRequest( + request, + `${FIRST_PARTY_CONNECTION_PREFIX}discord`, + ); + if (!verified.ok) return verified.response; + const capRequest = verified.request; + + if (capRequest.kind === "lifecycle") return capJson(200, { ok: true }); + + const webhookUrl = capRequest.settings.webhookUrl; + if (!isDiscordWebhookUrl(webhookUrl)) { + return capRequest.kind === "action" + ? capJson( + 200, + toast( + "Use a Discord webhook URL in the app's settings, then try again", + ), + ) + : capJson(200, { ok: true, skipped: "no_webhook" }); + } + + if (capRequest.kind === "event") { + if ( + capRequest.type !== "cap.ready" || + capRequest.settings.postNewCaps !== true + ) { + return capJson(200, { ok: true, skipped: "not_enabled" }); + } + const outcome = await postToDiscord(webhookUrl, capRequest.data.cap).catch( + () => "retry" as const, + ); + if (outcome === "retry") return capJson(503, { error: "Discord is busy" }); + return capJson(200, { ok: true, outcome }); + } + + if (verified.path !== "actions/post") { + return capJson(404, { error: "Unknown action" }); + } + const outcome = await postToDiscord(webhookUrl, capRequest.data.cap).catch( + () => "retry" as const, + ); + return capJson( + 200, + outcome === "posted" + ? toast("Posted to Discord") + : outcome === "rejected" + ? toast( + "Discord rejected the post. Check the webhook URL in the app's settings", + ) + : toast("Discord is busy right now. Try again in a moment"), + ); +} diff --git a/apps/web/lib/app-store/first-party/index.ts b/apps/web/lib/app-store/first-party/index.ts new file mode 100644 index 00000000000..373ff6cb253 --- /dev/null +++ b/apps/web/lib/app-store/first-party/index.ts @@ -0,0 +1,9 @@ +import { discordConnection } from "./discord"; + +const HANDLERS: Record Promise> = { + discord: discordConnection, +}; + +export function firstPartyConnectionHandler(appId: string) { + return HANDLERS[appId] ?? null; +} diff --git a/apps/web/lib/app-store/first-party/verify.ts b/apps/web/lib/app-store/first-party/verify.ts new file mode 100644 index 00000000000..76b8fea13f1 --- /dev/null +++ b/apps/web/lib/app-store/first-party/verify.ts @@ -0,0 +1,44 @@ +import type { CapRequest } from "@cap/app-store"; +import { verifyCapRequest } from "@cap/app-store/signing"; +import { appStorePublicKeys } from "../signing"; + +export type VerifiedCapRequest = + | { ok: true; request: CapRequest; path: string } + | { ok: false; response: Response }; + +const json = (status: number, body: unknown) => + Response.json(body, { status, headers: { "cache-control": "no-store" } }); + +export async function readVerifiedCapRequest( + request: Request, + prefix: string, +): Promise { + if (request.method !== "POST") { + return { ok: false, response: json(405, { error: "Method not allowed" }) }; + } + const body = await request.text(); + const verified = verifyCapRequest({ + headers: request.headers, + body, + keys: appStorePublicKeys(), + }); + if (!verified.ok) { + return { ok: false, response: json(401, { error: verified.reason }) }; + } + let parsed: CapRequest; + try { + parsed = JSON.parse(body) as CapRequest; + } catch { + return { ok: false, response: json(400, { error: "Invalid JSON" }) }; + } + if (parsed.kind !== verified.kind) { + return { ok: false, response: json(400, { error: "Kind mismatch" }) }; + } + const pathname = new URL(request.url).pathname; + const path = pathname.startsWith(prefix) + ? pathname.slice(prefix.length).replace(/^\//, "") + : ""; + return { ok: true, request: parsed, path }; +} + +export const capJson = json; diff --git a/apps/web/lib/app-store/installations.ts b/apps/web/lib/app-store/installations.ts new file mode 100644 index 00000000000..18b7d478005 --- /dev/null +++ b/apps/web/lib/app-store/installations.ts @@ -0,0 +1,457 @@ +import { + type CapEventType, + type CatalogApp, + type ConnectionPermission, + EVENT_REQUIRED_PERMISSION, + type InstallationRef, + type InstallationSettings, +} from "@cap/app-store"; +import { db } from "@cap/database"; +import { decrypt, encrypt } from "@cap/database/crypto"; +import { nanoId } from "@cap/database/helpers"; +import { appStoreInstallations } from "@cap/database/schema"; +import type { Organisation, User } from "@cap/web-domain"; +import { and, eq, inArray, or } from "drizzle-orm"; +import { isRateLimited, RATE_LIMIT_IDS } from "@/lib/rate-limit"; +import { + canManageOrganizationApps, + memberMayInstallConnections, + type UserOrganization, + userOrganizations, +} from "./access"; +import { getCatalogApp, isSupportedApiVersion } from "./catalog"; +import { + defaultSettings, + type PublicSettings, + parseStoredSettings, + publicSettings, + resolveSettings, + type SettingsInput, + type StoredSettings, + storedSettings, +} from "./settings"; + +export type InstallationRow = typeof appStoreInstallations.$inferSelect; +export type InstallScope = "user" | "organization"; + +export type AppStoreErrorCode = + | "not_found" + | "forbidden" + | "invalid" + | "conflict" + | "unavailable" + | "rate_limited"; + +export class AppStoreError extends Error { + constructor( + readonly code: AppStoreErrorCode, + message: string, + readonly fieldErrors?: Record, + ) { + super(message); + this.name = "AppStoreError"; + } +} + +export type InstallationView = { + id: string; + appId: string; + scope: InstallScope; + organizationId: string | null; + organizationName: string | null; + appVersion: string; + grantedPermissions: ConnectionPermission[]; + grantedEvents: CapEventType[]; + status: "active" | "disabled"; + disabledReason: string | null; + needsReview: boolean; + canManage: boolean; + settings: PublicSettings; + createdAt: string; +}; + +// Every install, settings change, uninstall and action sends a signed request +// to the app, so one account cannot make Cap send them without limit. +export async function enforceAppStoreRateLimit( + kind: "action" | "change", + userId: User.UserId, +) { + const ruleId = + kind === "action" + ? RATE_LIMIT_IDS.APP_STORE_ACTION + : RATE_LIMIT_IDS.APP_STORE_CHANGE; + if (await isRateLimited(ruleId, { key: userId })) { + throw new AppStoreError( + "rate_limited", + "Too many requests. Try again in a minute", + ); + } +} + +export const scopeKeyFor = (scope: InstallScope, ownerId: string): string => + `${scope === "user" ? "user" : "org"}:${ownerId}`; + +export const requestedPermissions = (app: CatalogApp) => + [...(app.connection?.permissions ?? [])] as ConnectionPermission[]; +export const requestedEvents = (app: CatalogApp) => + [...(app.connection?.events ?? [])] as CapEventType[]; + +export function needsReview(row: InstallationRow, app: CatalogApp) { + const granted = new Set([...row.grantedPermissions, ...row.grantedEvents]); + return [...requestedPermissions(app), ...requestedEvents(app)].some( + (item) => !granted.has(item), + ); +} + +export function eventIsGranted( + row: Pick, + type: CapEventType, +) { + if (!row.grantedEvents.includes(type)) return false; + const required = EVENT_REQUIRED_PERMISSION[type]; + return !required || row.grantedPermissions.includes(required); +} + +export async function readStoredSettings( + row: Pick, +): Promise { + if (!row.encryptedSettings) return { values: {}, secretKeys: [] }; + return parseStoredSettings(await decrypt(row.encryptedSettings)); +} + +export async function readInstallationSettings( + row: Pick, +): Promise { + return (await readStoredSettings(row)).values; +} + +const encryptSettings = async (stored: StoredSettings) => + Object.keys(stored.values).length === 0 + ? null + : await encrypt(JSON.stringify(stored)); + +export function installationRef(row: InstallationRow): InstallationRef { + return { + id: row.id, + scope: row.scope, + organizationId: row.organizationId ?? null, + installedByUserId: row.installedByUserId, + }; +} + +function requireInstallableApp(appId: string): CatalogApp { + const app = getCatalogApp(appId); + if (!app) throw new AppStoreError("not_found", "This app is not available"); + if (!isSupportedApiVersion(app.apiVersion)) { + throw new AppStoreError( + "unavailable", + "This app needs a newer version of Cap", + ); + } + if (app.builtin) { + throw new AppStoreError( + "invalid", + "Set this app up from its page in the App Store", + ); + } + return app; +} + +function canManageRow( + row: InstallationRow, + userId: User.UserId, + organizations: UserOrganization[], +) { + if (row.scope === "user") return row.userId === userId; + return canManageOrganizationApps( + organizations.find((org) => org.id === row.organizationId), + ); +} + +async function toView( + row: InstallationRow, + userId: User.UserId, + organizations: UserOrganization[], +): Promise { + const app = getCatalogApp(row.appId); + if (!app) return null; + const fields = app.connection?.settings ?? []; + const settings = + fields.length > 0 + ? publicSettings(fields, await readStoredSettings(row)) + : { values: {}, secretsSet: [] }; + return { + id: row.id, + appId: row.appId, + scope: row.scope, + organizationId: row.organizationId ?? null, + organizationName: + organizations.find((org) => org.id === row.organizationId)?.name ?? null, + appVersion: row.appVersion, + grantedPermissions: row.grantedPermissions as ConnectionPermission[], + grantedEvents: row.grantedEvents as CapEventType[], + status: row.status, + disabledReason: row.disabledReason ?? null, + needsReview: needsReview(row, app), + canManage: canManageRow(row, userId, organizations), + settings, + createdAt: row.createdAt.toISOString(), + }; +} + +async function rowsVisibleTo( + userId: User.UserId, + organizations: UserOrganization[], +) { + const organizationIds = organizations.map((org) => org.id); + return db() + .select() + .from(appStoreInstallations) + .where( + organizationIds.length > 0 + ? or( + and( + eq(appStoreInstallations.scope, "user"), + eq(appStoreInstallations.userId, userId), + ), + and( + eq(appStoreInstallations.scope, "organization"), + inArray(appStoreInstallations.organizationId, organizationIds), + ), + ) + : and( + eq(appStoreInstallations.scope, "user"), + eq(appStoreInstallations.userId, userId), + ), + ); +} + +export async function listInstallations( + userId: User.UserId, +): Promise { + const organizations = await userOrganizations(userId); + const rows = await rowsVisibleTo(userId, organizations); + const views = await Promise.all( + rows.map((row) => toView(row, userId, organizations)), + ); + return views + .filter((view): view is InstallationView => view !== null) + .sort((a, b) => a.createdAt.localeCompare(b.createdAt)); +} + +async function loadManagedRow(userId: User.UserId, installationId: string) { + const organizations = await userOrganizations(userId); + const [row] = await db() + .select() + .from(appStoreInstallations) + .where(eq(appStoreInstallations.id, installationId)) + .limit(1); + if (!row) throw new AppStoreError("not_found", "This app is not installed"); + const visible = + (row.scope === "user" && row.userId === userId) || + (row.scope === "organization" && + organizations.some((org) => org.id === row.organizationId)); + if (!visible) + throw new AppStoreError("not_found", "This app is not installed"); + if (!canManageRow(row, userId, organizations)) { + throw new AppStoreError( + "forbidden", + "Only owners and admins can change apps installed for the organization", + ); + } + return { row, organizations }; +} + +export type InstallInput = { + appId: string; + scope: InstallScope; + organizationId?: string | null; + settings?: SettingsInput; + activeOrganizationId?: string | null; +}; + +export async function installApp( + userId: User.UserId, + input: InstallInput, +): Promise<{ view: InstallationView; row: InstallationRow }> { + const app = requireInstallableApp(input.appId); + await enforceAppStoreRateLimit("change", userId); + const organizations = await userOrganizations(userId); + + let organizationId: Organisation.OrganisationId | null = null; + if (input.scope === "organization") { + const organization = organizations.find( + (org) => org.id === input.organizationId, + ); + if (!canManageOrganizationApps(organization)) { + throw new AppStoreError( + "forbidden", + "Only owners and admins can install apps for the organization", + ); + } + organizationId = organization?.id ?? null; + } else if (app.connection) { + const active = organizations.find( + (org) => org.id === input.activeOrganizationId, + ); + if (!memberMayInstallConnections(active)) { + throw new AppStoreError( + "forbidden", + "Your organization only lets owners and admins install apps that connect to other services", + ); + } + } + + const fields = app.connection?.settings ?? []; + let settings: InstallationSettings = {}; + if (fields.length > 0) { + const resolved = resolveSettings(fields, input.settings ?? {}, null); + if (!resolved.ok) { + throw new AppStoreError( + "invalid", + "Some settings need attention", + resolved.errors, + ); + } + settings = { ...defaultSettings(fields), ...resolved.settings }; + } + + const ownerId = input.scope === "user" ? userId : (organizationId ?? ""); + const scopeKey = scopeKeyFor(input.scope, ownerId); + const [existing] = await db() + .select({ id: appStoreInstallations.id }) + .from(appStoreInstallations) + .where( + and( + eq(appStoreInstallations.appId, app.id), + eq(appStoreInstallations.scopeKey, scopeKey), + ), + ) + .limit(1); + if (existing) { + throw new AppStoreError("conflict", `${app.name} is already installed`); + } + + const id = nanoId(); + try { + await db() + .insert(appStoreInstallations) + .values({ + id, + appId: app.id, + scope: input.scope, + scopeKey, + userId: input.scope === "user" ? userId : null, + organizationId, + installedByUserId: userId, + appVersion: app.version, + grantedPermissions: requestedPermissions(app), + grantedEvents: requestedEvents(app), + encryptedSettings: await encryptSettings( + storedSettings(fields, settings, null), + ), + status: "active", + }); + } catch (error) { + if ( + error instanceof Error && + /duplicate|ER_DUP_ENTRY/i.test(`${error.message} ${String(error.cause)}`) + ) { + throw new AppStoreError("conflict", `${app.name} is already installed`); + } + throw error; + } + + const [row] = await db() + .select() + .from(appStoreInstallations) + .where(eq(appStoreInstallations.id, id)) + .limit(1); + if (!row) throw new Error("Installation was not saved"); + const view = await toView(row, userId, organizations); + if (!view) throw new Error("Installation has no catalog entry"); + return { view, row }; +} + +export type UpdateInput = { + settings?: SettingsInput; + acceptUpdate?: boolean; + resume?: boolean; +}; + +export async function updateInstallation( + userId: User.UserId, + installationId: string, + input: UpdateInput, +): Promise<{ + view: InstallationView; + row: InstallationRow; + settingsChanged: boolean; +}> { + const { row, organizations } = await loadManagedRow(userId, installationId); + await enforceAppStoreRateLimit("change", userId); + const app = getCatalogApp(row.appId); + if (!app) throw new AppStoreError("not_found", "This app is not available"); + + const patch: Partial = {}; + let settingsChanged = false; + const fields = app.connection?.settings ?? []; + if (input.settings && fields.length > 0) { + const previous = await readStoredSettings(row); + const existing = previous.values; + const resolved = resolveSettings(fields, input.settings, existing); + if (!resolved.ok) { + throw new AppStoreError( + "invalid", + "Some settings need attention", + resolved.errors, + ); + } + settingsChanged = + JSON.stringify(existing) !== JSON.stringify(resolved.settings); + patch.encryptedSettings = await encryptSettings( + storedSettings(fields, resolved.settings, previous), + ); + } + if (input.acceptUpdate) { + patch.grantedPermissions = requestedPermissions(app); + patch.grantedEvents = requestedEvents(app); + patch.appVersion = app.version; + } + if (input.resume || (settingsChanged && row.status === "disabled")) { + patch.status = "active"; + patch.disabledReason = null; + patch.consecutiveFailures = 0; + patch.failingSince = null; + } + + if (Object.keys(patch).length > 0) { + await db() + .update(appStoreInstallations) + .set(patch) + .where(eq(appStoreInstallations.id, row.id)); + } + const [updated] = await db() + .select() + .from(appStoreInstallations) + .where(eq(appStoreInstallations.id, row.id)) + .limit(1); + if (!updated) + throw new AppStoreError("not_found", "This app is not installed"); + const view = await toView(updated, userId, organizations); + if (!view) throw new AppStoreError("not_found", "This app is not available"); + return { view, row: updated, settingsChanged }; +} + +export async function uninstallApp( + userId: User.UserId, + installationId: string, +): Promise<{ row: InstallationRow; settings: InstallationSettings }> { + const { row } = await loadManagedRow(userId, installationId); + await enforceAppStoreRateLimit("change", userId); + const settings = await readInstallationSettings(row).catch(() => ({})); + await db() + .delete(appStoreInstallations) + .where(eq(appStoreInstallations.id, row.id)); + return { row, settings }; +} diff --git a/apps/web/lib/app-store/payload.ts b/apps/web/lib/app-store/payload.ts new file mode 100644 index 00000000000..940b422178a --- /dev/null +++ b/apps/web/lib/app-store/payload.ts @@ -0,0 +1,158 @@ +import type { + CapPayload, + CommentPayload, + ConnectionPermission, +} from "@cap/app-store"; +import { db } from "@cap/database"; +import { comments, organizations, users, videos } from "@cap/database/schema"; +import { serverEnv } from "@cap/env"; +import { Storage } from "@cap/web-backend"; +import type { Video } from "@cap/web-domain"; +import { eq } from "drizzle-orm"; +import { Effect, Option } from "effect"; +import { parseAgentVtt } from "@/lib/agent-api"; +import { runPromise } from "@/lib/server"; +import { videoShareUrl } from "@/lib/video-share-url"; +import { decodeStorageVideo } from "@/lib/video-storage"; + +export const TRANSCRIPT_MAX_CHARACTERS = 200_000; +export const COMMENT_MAX_CHARACTERS = 4_000; + +export type CapRecord = { + video: typeof videos.$inferSelect; + ownerName: string | null; + organization: Pick< + typeof organizations.$inferSelect, + "id" | "customDomain" | "domainVerified" | "settings" + > | null; +}; + +export async function loadCapRecord( + videoId: Video.VideoId, +): Promise { + const [row] = await db() + .select({ + video: videos, + ownerName: users.name, + organization: { + id: organizations.id, + customDomain: organizations.customDomain, + domainVerified: organizations.domainVerified, + settings: organizations.settings, + }, + }) + .from(videos) + .leftJoin(users, eq(users.id, videos.ownerId)) + .leftJoin(organizations, eq(organizations.id, videos.orgId)) + .where(eq(videos.id, videoId)) + .limit(1); + if (!row) return null; + return { + video: row.video, + ownerName: row.ownerName ?? null, + organization: row.organization?.id ? row.organization : null, + }; +} + +async function readTranscript( + video: typeof videos.$inferSelect, +): Promise { + if (video.transcriptionStatus !== "COMPLETE") return null; + const vtt = await Effect.gen(function* () { + const [bucket] = yield* Storage.getAccessForVideo( + decodeStorageVideo(video), + ); + return yield* bucket.getObject( + `${video.ownerId}/${video.id}/transcription.vtt`, + ); + }).pipe(runPromise); + if (Option.isNone(vtt)) return null; + const text = parseAgentVtt(vtt.value) + .map((cue) => cue.text) + .join(" ") + .replace(/\s+/g, " ") + .trim(); + return text.slice(0, TRANSCRIPT_MAX_CHARACTERS); +} + +const disabled = ( + record: CapRecord, + setting: "disableTranscript" | "disableSummary", +) => + record.video.settings?.[setting] ?? + record.organization?.settings?.[setting] ?? + false; + +export async function buildCapPayload( + record: CapRecord, + permissions: readonly ConnectionPermission[], +): Promise { + const { video } = record; + const payload: CapPayload = { + id: video.id, + title: video.name, + url: videoShareUrl(serverEnv().WEB_URL, video.id, record.organization), + ownerName: record.ownerName, + organizationId: video.orgId ?? null, + createdAt: video.createdAt.toISOString(), + durationSeconds: + typeof video.duration === "number" && Number.isFinite(video.duration) + ? Math.round(video.duration * 10) / 10 + : null, + }; + + if (permissions.includes("cap.transcript")) { + payload.transcript = disabled(record, "disableTranscript") + ? null + : await readTranscript(video).catch((error: unknown) => { + console.error("[app-store] Could not read transcript", { + videoId: video.id, + message: error instanceof Error ? error.message : String(error), + }); + return null; + }); + } + + if (permissions.includes("cap.summary")) { + const metadata = video.metadata; + payload.summary = disabled(record, "disableSummary") + ? null + : { + title: metadata?.aiTitle ?? null, + summary: metadata?.summary ?? null, + chapters: (metadata?.chapters ?? []).map((chapter) => ({ + title: chapter.title, + startSeconds: chapter.start, + })), + }; + } + + return payload; +} + +export async function loadCommentPayload( + commentId: string, +): Promise { + const [row] = await db() + .select({ + id: comments.id, + content: comments.content, + createdAt: comments.createdAt, + timestamp: comments.timestamp, + parentCommentId: comments.parentCommentId, + authorName: users.name, + }) + .from(comments) + .leftJoin(users, eq(users.id, comments.authorId)) + .where(eq(comments.id, commentId as typeof comments.$inferSelect.id)) + .limit(1); + if (!row) return null; + return { + id: row.id, + text: row.content.slice(0, COMMENT_MAX_CHARACTERS), + authorName: row.authorName ?? null, + createdAt: row.createdAt.toISOString(), + timestampSeconds: row.timestamp ?? null, + parentCommentId: row.parentCommentId ?? null, + }; +} diff --git a/apps/web/lib/app-store/settings.ts b/apps/web/lib/app-store/settings.ts new file mode 100644 index 00000000000..71d30d775a4 --- /dev/null +++ b/apps/web/lib/app-store/settings.ts @@ -0,0 +1,194 @@ +import type { + InstallationSettings, + SettingField, + SettingValue, +} from "@cap/app-store"; + +export const SETTING_TEXT_MAX_LENGTH = 2_000; + +export type SettingsInput = Record; + +export type SettingsResult = + | { ok: true; settings: InstallationSettings } + | { ok: false; errors: Record }; + +export type PublicSettings = { + values: Record; + secretsSet: string[]; +}; + +function isHttpsUrl(value: string) { + try { + const url = new URL(value); + return url.protocol === "https:" && !url.username && !url.password; + } catch { + return false; + } +} + +export function defaultSettings( + fields: readonly SettingField[], +): InstallationSettings { + const settings: InstallationSettings = {}; + for (const field of fields) { + if (field.type === "toggle") settings[field.key] = field.default ?? false; + else if (field.type !== "secret" && field.default !== undefined) { + settings[field.key] = field.default; + } + } + return settings; +} + +export function resolveSettings( + fields: readonly SettingField[], + input: SettingsInput, + existing: InstallationSettings | null, +): SettingsResult { + const settings: InstallationSettings = {}; + const errors: Record = {}; + + for (const field of fields) { + const raw = input[field.key]; + const previous = existing?.[field.key]; + + if (field.type === "toggle") { + if (raw === undefined) { + settings[field.key] = + typeof previous === "boolean" ? previous : (field.default ?? false); + } else if (typeof raw === "boolean") { + settings[field.key] = raw; + } else { + errors[field.key] = "Must be on or off"; + } + continue; + } + + if (raw !== undefined && raw !== null && typeof raw !== "string") { + errors[field.key] = "Must be text"; + continue; + } + const value = typeof raw === "string" ? raw.trim() : ""; + + if (field.type === "secret") { + if (value) settings[field.key] = value; + else if (typeof previous === "string" && previous) { + settings[field.key] = previous; + } else if (field.required) { + errors[field.key] = `${field.label} is required`; + } + if (value.length > SETTING_TEXT_MAX_LENGTH) { + errors[field.key] = `${field.label} is too long`; + } + continue; + } + + const resolved = + raw === undefined && typeof previous === "string" + ? previous + : value || (raw === undefined ? (field.default ?? "") : ""); + + if (!resolved) { + if (field.required) errors[field.key] = `${field.label} is required`; + continue; + } + if (resolved.length > SETTING_TEXT_MAX_LENGTH) { + errors[field.key] = `${field.label} is too long`; + continue; + } + if (field.type === "url" && !isHttpsUrl(resolved)) { + errors[field.key] = `${field.label} must be an https:// URL`; + continue; + } + if ( + field.type === "select" && + !field.options.some((option) => option.value === resolved) + ) { + errors[field.key] = `Choose one of the options for ${field.label}`; + continue; + } + settings[field.key] = resolved; + } + + return Object.keys(errors).length > 0 + ? { ok: false, errors } + : { ok: true, settings }; +} + +export type StoredSettings = { + values: InstallationSettings; + secretKeys: string[]; +}; + +export function publicSettings( + fields: readonly SettingField[], + stored: StoredSettings, +): PublicSettings { + const hidden = new Set(stored.secretKeys); + const values: Record = {}; + const secretsSet: string[] = []; + for (const field of fields) { + const value = stored.values[field.key]; + if (field.type === "secret" || hidden.has(field.key)) { + if (typeof value === "string" && value) secretsSet.push(field.key); + continue; + } + if (value !== undefined) values[field.key] = value; + } + return { values, secretsSet }; +} + +// A key stays secret once it has held a secret, even if a later version of +// the app declares it as plain text, so an update can never reveal a saved +// credential to people who can read the install. +export function storedSettings( + fields: readonly SettingField[], + values: InstallationSettings, + previous: StoredSettings | null, +): StoredSettings { + const secretKeys = new Set(previous?.secretKeys ?? []); + for (const field of fields) { + if (field.type === "secret" && values[field.key] !== undefined) { + secretKeys.add(field.key); + } + } + return { + values, + secretKeys: [...secretKeys].filter((key) => values[key] !== undefined), + }; +} + +function settingValues(input: unknown): InstallationSettings { + const settings: InstallationSettings = {}; + if (!input || typeof input !== "object" || Array.isArray(input)) { + return settings; + } + for (const [key, value] of Object.entries(input)) { + if (typeof value === "string" || typeof value === "boolean") { + settings[key] = value; + } + } + return settings; +} + +export function parseStoredSettings(raw: string | null): StoredSettings { + if (!raw) return { values: {}, secretKeys: [] }; + const parsed: unknown = JSON.parse(raw); + if ( + parsed && + typeof parsed === "object" && + "values" in parsed && + "secretKeys" in parsed + ) { + const { values, secretKeys } = parsed as { + values: unknown; + secretKeys: unknown; + }; + return { + values: settingValues(values), + secretKeys: Array.isArray(secretKeys) + ? secretKeys.filter((key): key is string => typeof key === "string") + : [], + }; + } + return { values: settingValues(parsed), secretKeys: [] }; +} diff --git a/apps/web/lib/app-store/signing.ts b/apps/web/lib/app-store/signing.ts new file mode 100644 index 00000000000..cc40f04a45c --- /dev/null +++ b/apps/web/lib/app-store/signing.ts @@ -0,0 +1,16 @@ +import { type CapSigningKey, deriveSigningKey } from "@cap/app-store/signing"; +import { serverEnv } from "@cap/env"; + +let cached: { secret: string; key: CapSigningKey } | null = null; + +export function appStoreSigningKey(): CapSigningKey { + const secret = serverEnv().NEXTAUTH_SECRET; + if (!cached || cached.secret !== secret) { + cached = { secret, key: deriveSigningKey(secret) }; + } + return cached.key; +} + +export function appStorePublicKeys() { + return { keys: [appStoreSigningKey().publicKey] }; +} diff --git a/apps/web/lib/queue-video-transcription.ts b/apps/web/lib/queue-video-transcription.ts index 3b78a446605..a3c7fa26d8e 100644 --- a/apps/web/lib/queue-video-transcription.ts +++ b/apps/web/lib/queue-video-transcription.ts @@ -4,6 +4,7 @@ import { serverEnv } from "@cap/env"; import type { Video } from "@cap/web-domain"; import { eq } from "drizzle-orm"; import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement"; +import { announceAppStoreEvent } from "@/lib/app-store/announce"; import { transcribeVideo } from "@/lib/transcribe"; type VideoSourceType = (typeof videos.$inferSelect)["source"]["type"]; @@ -38,6 +39,7 @@ export function shouldQueueTranscriptionAfterMultipartComplete( export async function queueVideoTranscription( videoId: Video.VideoId, ): Promise { + announceAppStoreEvent("cap.ready", videoId); if (!serverEnv().ASSEMBLY_API_KEY) { return { success: true, message: "Transcription is not configured" }; } diff --git a/apps/web/lib/rate-limit.ts b/apps/web/lib/rate-limit.ts index 8eb5fc31d1f..b8c201a5933 100644 --- a/apps/web/lib/rate-limit.ts +++ b/apps/web/lib/rate-limit.ts @@ -203,6 +203,10 @@ export const RATE_LIMIT_IDS = { COLLECTION_PASSWORD_PER_COLLECTION: "rl_collection_password_per_collection", /** Invite emails: organization batches per organization and per sender, and video viewer invites per owner. Suggested: 30 / 1h per key. */ ORGANIZATION_INVITE: "rl_organization_invite", + /** App Store actions run on Caps, each a signed request to the app. Suggested: 30 / 1m per key (user). */ + APP_STORE_ACTION: "rl_app_store_action", + /** App Store installs, setting changes and uninstalls, each a signed lifecycle request. Suggested: 30 / 1m per key (user). */ + APP_STORE_CHANGE: "rl_app_store_change", CHECKOUT: "rl_checkout", VIDEO_PASSWORD_PER_VIEWER: "rl_video_password_per_viewer", COLLECTION_PASSWORD_PER_VIEWER: "rl_collection_password_per_viewer", @@ -273,6 +277,8 @@ const FALLBACK_RATE_LIMITS: Record = { windowMs: 10 * MINUTE_MS, }, [RATE_LIMIT_IDS.ORGANIZATION_INVITE]: { limit: 30, windowMs: 60 * MINUTE_MS }, + [RATE_LIMIT_IDS.APP_STORE_ACTION]: { limit: 30, windowMs: MINUTE_MS }, + [RATE_LIMIT_IDS.APP_STORE_CHANGE]: { limit: 30, windowMs: MINUTE_MS }, [RATE_LIMIT_IDS.CHECKOUT]: { limit: 20, windowMs: 10 * MINUTE_MS }, [RATE_LIMIT_IDS.VIDEO_PASSWORD_PER_VIEWER]: { limit: 1, diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs index be81f821007..71854095855 100644 --- a/apps/web/next.config.mjs +++ b/apps/web/next.config.mjs @@ -45,6 +45,7 @@ const nextConfig = { "/infra/llms-full.txt": ["./content/docs/api/*.mdx"], }, transpilePackages: [ + "@cap/app-store", "@cap/ui", "@cap/utils", "@cap/web-api-contract", @@ -110,6 +111,16 @@ const nextConfig = { { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, ], }, + { + source: "/app-store/:path*", + headers: [ + { + key: "Cache-Control", + value: "public, max-age=31536000, immutable", + }, + { key: "Access-Control-Allow-Origin", value: "*" }, + ], + }, ]; }, async rewrites() { diff --git a/apps/web/package.json b/apps/web/package.json index 62536495c12..4c3e3d4e692 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -3,21 +3,23 @@ "version": "0.3.1", "private": true, "scripts": { - "dev": "cross-env NODE_OPTIONS=--disable-warning=DEP0169 dotenv -e ../../.env -- next dev", - "build": "next build --turbopack", - "build:web": "next build --turbopack", + "dev": "bun run app-store:catalog && cross-env NODE_OPTIONS=--disable-warning=DEP0169 dotenv -e ../../.env -- next dev", + "build": "bun run app-store:catalog && next build --turbopack", + "build:web": "bun run app-store:catalog && next build --turbopack", + "app-store:catalog": "bun ../../packages/app-store/src/cli.ts build --catalog lib/app-store/generated/catalog.json --assets public/app-store", "build:docker": "cd ../.. && docker build -t cap-web-docker . --no-cache --progress=plain", "start": "cross-env NODE_OPTIONS=--disable-warning=DEP0169 next start", "compress-images": "bash tools/compress-images.sh", "mcp-card:generate": "bun scripts/build-mcp-card.mjs", "mcp-card:check": "bun scripts/build-mcp-card.mjs --check", - "test": "vitest run", + "test": "bun run app-store:catalog && vitest run", "test:agent-e2e": "CAP_AGENT_E2E=1 vitest run __tests__/e2e/agent-local-e2e.test.ts", "test:watch": "vitest", "test:coverage": "vitest run --coverage", "test:ui": "vitest --ui" }, "dependencies": { + "@cap/app-store": "workspace:*", "@ai-sdk/anthropic": "^4.0.37", "@ai-sdk/groq": "^4.0.27", "@ai-sdk/openai": "^4.0.37", diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index e0431701d7e..ea0ba5f54c8 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -44,6 +44,7 @@ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"], "references": [ + { "path": "../../packages/app-store" }, { "path": "../../packages/database" }, { "path": "../../packages/env" }, { "path": "../../packages/recorder-core" }, diff --git a/apps/web/workflows/deliver-app-store-request.ts b/apps/web/workflows/deliver-app-store-request.ts new file mode 100644 index 00000000000..93f425283e2 --- /dev/null +++ b/apps/web/workflows/deliver-app-store-request.ts @@ -0,0 +1,38 @@ +import { sleep } from "workflow"; +import { + type AppStoreDeliveryJob, + type DeliveryOutcome, + deliverAppStoreJob, +} from "@/lib/app-store/delivery"; +import { webhookRetryDelaySeconds } from "@/lib/developer-webhook-events"; + +export async function deliverAppStoreRequestWorkflow( + job: AppStoreDeliveryJob, +): Promise<{ outcome: DeliveryOutcome | "gave_up"; attempts: number }> { + "use workflow"; + + for (let attempt = 1; ; attempt++) { + const outcome = await attemptDelivery(job); + if (outcome !== "retry") return { outcome, attempts: attempt }; + const delay = webhookRetryDelaySeconds(attempt); + if (delay === null) return { outcome: "gave_up", attempts: attempt }; + await sleep(`${delay}s`); + } +} + +async function attemptDelivery( + job: AppStoreDeliveryJob, +): Promise { + "use step"; + + try { + return await deliverAppStoreJob(job); + } catch (error) { + console.error("[app-store] Delivery attempt failed to run", { + installationId: job.installationId, + kind: job.kind, + message: error instanceof Error ? error.message : String(error), + }); + return "retry"; + } +} diff --git a/apps/web/workflows/finalize-desktop-recording.ts b/apps/web/workflows/finalize-desktop-recording.ts index cbf8a6fffa6..8850c02133e 100644 --- a/apps/web/workflows/finalize-desktop-recording.ts +++ b/apps/web/workflows/finalize-desktop-recording.ts @@ -9,6 +9,7 @@ import { Option } from "effect"; import { getStepMetadata, sleep } from "workflow"; import { z } from "zod"; import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement"; +import { emitCapReadySafely } from "@/lib/app-store/announce"; import { observeDesktopRecordingJob } from "@/lib/desktop-recording-job-status"; import { attachRemoteJob, @@ -934,6 +935,7 @@ async function queueFinalizedRecordingTranscription( ): Promise { "use step"; + await emitCapReadySafely(Video.VideoId.make(videoId)); if (!serverEnv().ASSEMBLY_API_KEY) return true; try { const [[owner], [video]] = await Promise.all([ diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.ts index 73e553b16b3..7e077dc57a3 100644 --- a/apps/web/workflows/generate-ai.ts +++ b/apps/web/workflows/generate-ai.ts @@ -16,6 +16,7 @@ import { FatalError } from "workflow"; import { isAiConfigured } from "@/lib/ai/provider"; import { AiUnavailableError, runWithAiProviders } from "@/lib/ai/run"; import { setGeneratedAiContent } from "@/lib/ai-content-metadata"; +import { emitAppStoreEventSafely } from "@/lib/app-store/announce"; import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names"; import { decodeStorageVideo } from "@/lib/video-storage"; import { runWorkflowPromise } from "@/lib/workflow-runtime"; @@ -402,6 +403,8 @@ async function saveResults( .set({ metadata: metadataUpdate }) .where(eq(videos.id, videoId as Video.VideoId)); + await emitAppStoreEventSafely("cap.summary.ready", videoId as Video.VideoId); + if ( generatedTitle && shouldReplaceVideoTitle({ diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.ts index e87fb291e04..474d5aa1dcc 100644 --- a/apps/web/workflows/process-video.ts +++ b/apps/web/workflows/process-video.ts @@ -6,6 +6,7 @@ import { Video } from "@cap/web-domain"; import { eq } from "drizzle-orm"; import { FatalError, sleep } from "workflow"; import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement"; +import { emitCapReadySafely } from "@/lib/app-store/announce"; import { getMediaProcessingRejection } from "@/lib/media-processing-policy"; import { createMediaServerCapacityError, @@ -419,6 +420,7 @@ async function queueProcessedVideoTranscription( ): Promise { "use step"; + await emitCapReadySafely(Video.VideoId.make(videoId)); if (!serverEnv().ASSEMBLY_API_KEY) return; try { const [owner] = await db() diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.ts index 8c6d17227d5..c0ebdb0e76d 100644 --- a/apps/web/workflows/transcribe.ts +++ b/apps/web/workflows/transcribe.ts @@ -21,6 +21,7 @@ import { and, eq, isNull, sql } from "drizzle-orm"; import { Either, Option, Schema } from "effect"; import { FatalError } from "workflow"; import { start } from "workflow/api"; +import { emitAppStoreEventSafely } from "@/lib/app-store/announce"; import { createAssemblyAIClient, getAssemblyAITranscriptionOptions, @@ -909,6 +910,11 @@ async function saveTranscription( .set({ transcriptionStatus: "COMPLETE" }) .where(eq(videos.id, videoId as Video.VideoId)); + await emitAppStoreEventSafely( + "cap.transcript.ready", + videoId as Video.VideoId, + ); + // The canonical transcript supersedes the provisional live transcript, so // drop the artifact and its metadata flag. Never fatal: a leftover live // artifact is unused once transcriptionStatus is COMPLETE. diff --git a/bun.lock b/bun.lock index 18e0d8f9710..de4f2edccfb 100644 --- a/bun.lock +++ b/bun.lock @@ -127,6 +127,7 @@ "@aws-sdk/cloudfront-signer": "^3.821.0", "@aws-sdk/s3-presigned-post": "^3.485.0", "@aws-sdk/s3-request-presigner": "^3.485.0", + "@cap/app-store": "workspace:*", "@cap/database": "workspace:*", "@cap/env": "workspace:*", "@cap/infra-mcp": "workspace:*", @@ -295,6 +296,15 @@ "sst": "3.17.14", }, }, + "packages/app-store": { + "name": "@cap/app-store", + "dependencies": { + "effect": "^3.18.4", + }, + "devDependencies": { + "vitest": "^3.2.0", + }, + }, "packages/config": { "name": "config", "version": "0.0.0", @@ -372,7 +382,7 @@ }, "packages/infra-mcp": { "name": "@cap/infra-mcp", - "version": "0.1.0", + "version": "0.2.0", "bin": { "cap-infra-mcp": "./dist/bin.js", }, @@ -828,6 +838,8 @@ "@borewit/text-codec": ["@borewit/text-codec@0.2.2", "", {}, "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ=="], + "@cap/app-store": ["@cap/app-store@workspace:packages/app-store"], + "@cap/chrome-extension": ["@cap/chrome-extension@workspace:apps/chrome-extension"], "@cap/database": ["@cap/database@workspace:packages/database"], diff --git a/package.json b/package.json index 9b9df574635..6157548cfd1 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "analytics:migrate-dub:apply": "dotenv -e .env -- node scripts/analytics/migrate-dub-to-tinybird.js --apply", "analytics:posthog-growth": "dotenv -e .env -- node scripts/analytics/posthog-growth-audit.mjs", "analytics:setup": "dotenv -e .env -- node scripts/analytics/setup-analytics.js", + "app-store": "bun packages/app-store/src/cli.ts", "analytics:check": "dotenv -e .env -- node scripts/analytics/check-analytics.js", "analytics:delete-all": "dotenv -e .env -- node scripts/analytics/delete-all-data.js", "analytics:populate-test": "dotenv -e .env -- node scripts/analytics/populate-test-data.js", @@ -27,7 +28,7 @@ "format": "bun run biome check --write", "lint": "bun run biome lint", "gpui:build": "dotenv -e .env -- node scripts/bundle-gpui.mjs", - "typecheck": "bun run --cwd apps/web next typegen && tsc-rs -b", + "typecheck": "bun run --cwd apps/web app-store:catalog && bun run --cwd apps/web next typegen && tsc-rs -b", "test": "turbo run test", "test:web": "bun run --filter=@cap/web test", "test:discover": "bun run with-env cargo run -p cap-test -- discover", diff --git a/packages/app-store/package.json b/packages/app-store/package.json new file mode 100644 index 00000000000..a29d283a6f5 --- /dev/null +++ b/packages/app-store/package.json @@ -0,0 +1,22 @@ +{ + "name": "@cap/app-store", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./build": "./src/build.ts", + "./signing": "./src/signing.ts", + "./validate": "./src/validate.ts" + }, + "scripts": { + "test": "vitest run" + }, + "dependencies": { + "effect": "^3.18.4" + }, + "devDependencies": { + "vitest": "^3.2.0" + } +} diff --git a/packages/app-store/src/build.ts b/packages/app-store/src/build.ts new file mode 100644 index 00000000000..09ae746b0f3 --- /dev/null +++ b/packages/app-store/src/build.ts @@ -0,0 +1,140 @@ +import { createHash } from "node:crypto"; +import { + type BlockedApp, + type Catalog, + type CatalogApp, + type CatalogAsset, + type CatalogBackground, + platformsFor, +} from "./catalog"; +import { isFirstPartyApp } from "./constants"; +import { hashBytes, type LoadedApp } from "./validate"; + +const EXTENSIONS: Record = { + png: "png", + jpeg: "jpg", + webp: "webp", +}; + +export type CatalogFile = { path: string; bytes: Uint8Array }; + +export type BuildCatalogOptions = { + assetBaseUrl: string; + blocked?: readonly BlockedApp[]; +}; + +export function buildCatalog( + apps: LoadedApp[], + options: BuildCatalogOptions, +): { catalog: Catalog; files: CatalogFile[] } { + const files = new Map(); + const base = options.assetBaseUrl.replace(/\/$/, ""); + + const assetFor = (app: LoadedApp, path: string): CatalogAsset => { + const bytes = app.files.get(path); + const info = app.images.get(path); + if (!bytes || !info) { + throw new Error(`${app.id}: ${path} was not validated`); + } + const sha256 = hashBytes(bytes); + const name = `${app.id}/${sha256.slice(0, 32)}.${EXTENSIONS[info.format]}`; + files.set(name, bytes); + return { + url: `${base}/${name}`, + sha256, + bytes: bytes.byteLength, + width: info.width, + height: info.height, + }; + }; + + const blocked = [...(options.blocked ?? [])].sort((a, b) => + a.id.localeCompare(b.id), + ); + const blockedIds = new Set(blocked.map((entry) => entry.id)); + + const catalogApps = apps + .filter((app) => !blockedIds.has(app.id)) + .sort((a, b) => a.id.localeCompare(b.id)) + .map((app): CatalogApp => { + const manifest = app.manifest; + return { + apiVersion: manifest.apiVersion, + id: manifest.id, + name: manifest.name, + version: manifest.version, + description: manifest.description, + author: manifest.author, + firstParty: isFirstPartyApp(manifest), + license: manifest.license, + categories: [...manifest.categories], + keywords: [...(manifest.keywords ?? [])], + homepage: manifest.homepage, + support: manifest.support, + privacyPolicy: manifest.privacyPolicy, + icon: assetFor(app, "icon.png"), + screenshots: (manifest.screenshots ?? []).map((path) => + assetFor(app, path), + ), + readme: app.readme, + platforms: platformsFor(manifest), + builtin: manifest.builtin, + backgrounds: (manifest.backgrounds ?? []).map( + (background): CatalogBackground => { + if ("image" in background) { + return { + kind: "image", + id: background.id, + name: background.name, + image: assetFor(app, background.image), + }; + } + if ("gradient" in background) { + return { + kind: "gradient", + id: background.id, + name: background.name, + ...background.gradient, + }; + } + return { + kind: "color", + id: background.id, + name: background.name, + color: background.color, + }; + }, + ), + captionStyles: [...(manifest.captionStyles ?? [])], + colorLooks: [...(manifest.colorLooks ?? [])], + connection: manifest.connection + ? { + url: manifest.connection.url, + permissions: [...(manifest.connection.permissions ?? [])], + events: [...(manifest.connection.events ?? [])], + settings: [...(manifest.connection.settings ?? [])], + actions: [...(manifest.connection.actions ?? [])], + } + : undefined, + contentHash: app.contentHash, + }; + }); + + const revision = createHash("sha256") + .update( + JSON.stringify({ + apps: catalogApps.map((app) => [app.id, app.contentHash]), + blocked, + base, + }), + ) + .digest("hex") + .slice(0, 32); + + return { + catalog: { catalogVersion: 1, revision, apps: catalogApps, blocked }, + files: [...files.entries()] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([path, bytes]) => ({ path, bytes })), + }; +} diff --git a/packages/app-store/src/catalog.ts b/packages/app-store/src/catalog.ts new file mode 100644 index 00000000000..57857ab0a4c --- /dev/null +++ b/packages/app-store/src/catalog.ts @@ -0,0 +1,127 @@ +import { Schema } from "effect"; +import { BUILTIN_APPS, type BuiltinApp } from "./constants"; +import { + Author, + CapEvent, + CaptionStyle, + ColorLook, + ConnectionAction, + ConnectionPermission, + HexColor, + ItemId, + type Manifest, + SettingField, +} from "./manifest"; + +export const Platform = Schema.Literal("web", "desktop"); +export type Platform = typeof Platform.Type; + +export const CatalogAsset = Schema.Struct({ + url: Schema.String, + sha256: Schema.String, + bytes: Schema.Number, + width: Schema.Number, + height: Schema.Number, +}); +export type CatalogAsset = typeof CatalogAsset.Type; + +export const CatalogBackground = Schema.Union( + Schema.Struct({ + kind: Schema.Literal("image"), + id: ItemId, + name: Schema.String, + image: CatalogAsset, + }), + Schema.Struct({ + kind: Schema.Literal("gradient"), + id: ItemId, + name: Schema.String, + from: HexColor, + to: HexColor, + angle: Schema.Number, + }), + Schema.Struct({ + kind: Schema.Literal("color"), + id: ItemId, + name: Schema.String, + color: HexColor, + }), +); +export type CatalogBackground = typeof CatalogBackground.Type; + +export const CatalogConnection = Schema.Struct({ + url: Schema.String, + permissions: Schema.Array(ConnectionPermission), + events: Schema.Array(CapEvent), + settings: Schema.Array(SettingField), + actions: Schema.Array(ConnectionAction), +}); +export type CatalogConnection = typeof CatalogConnection.Type; + +export const CatalogApp = Schema.Struct({ + apiVersion: Schema.Number, + id: Schema.String, + name: Schema.String, + version: Schema.String, + description: Schema.String, + author: Author, + firstParty: Schema.Boolean, + license: Schema.String, + categories: Schema.Array(Schema.String), + keywords: Schema.Array(Schema.String), + homepage: Schema.optional(Schema.String), + support: Schema.optional(Schema.String), + privacyPolicy: Schema.optional(Schema.String), + icon: CatalogAsset, + screenshots: Schema.Array(CatalogAsset), + readme: Schema.String, + platforms: Schema.Array(Platform), + builtin: Schema.optional(Schema.Literal(...BUILTIN_APPS)), + backgrounds: Schema.Array(CatalogBackground), + captionStyles: Schema.Array(CaptionStyle), + colorLooks: Schema.Array(ColorLook), + connection: Schema.optional(CatalogConnection), + contentHash: Schema.String, +}); +export type CatalogApp = typeof CatalogApp.Type; + +export const BlockedApp = Schema.Struct({ + id: Schema.String, + reason: Schema.String, +}); +export type BlockedApp = typeof BlockedApp.Type; + +export const Catalog = Schema.Struct({ + catalogVersion: Schema.Literal(1), + revision: Schema.String, + apps: Schema.Array(CatalogApp), + blocked: Schema.Array(BlockedApp), +}); +export type Catalog = typeof Catalog.Type; + +export const BUILTIN_PLATFORMS: Record = { + slack: ["web"], + "amazon-s3": ["web", "desktop"], + "google-drive": ["web", "desktop"], +}; + +export function platformsFor(manifest: Manifest): Platform[] { + const platforms = new Set(); + if (manifest.builtin) { + for (const platform of BUILTIN_PLATFORMS[manifest.builtin]) { + platforms.add(platform); + } + } + if (manifest.backgrounds || manifest.captionStyles || manifest.colorLooks) { + platforms.add("desktop"); + } + if (manifest.connection) { + platforms.add("web"); + if ((manifest.connection.actions ?? []).length > 0) { + platforms.add("desktop"); + } + } + return (["web", "desktop"] as const).filter((platform) => + platforms.has(platform), + ); +} diff --git a/packages/app-store/src/cli.ts b/packages/app-store/src/cli.ts new file mode 100644 index 00000000000..6606751d639 --- /dev/null +++ b/packages/app-store/src/cli.ts @@ -0,0 +1,210 @@ +import { execFileSync } from "node:child_process"; +import { + cp, + mkdir, + mkdtemp, + readFile, + rm, + stat, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { JSONSchema, Schema } from "effect"; +import { buildCatalog } from "./build"; +import { BlockedApp } from "./catalog"; +import { Manifest } from "./manifest"; +import { + type BaseApp, + listAppFolders, + loadApp, + secretKeysOf, + type ValidationIssue, + validateAppStore, +} from "./validate"; + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../.."); +const storeRoot = join(repoRoot, "app-store"); +const appsRoot = join(storeRoot, "apps"); +const schemaPath = join(storeRoot, "manifest.schema.json"); +const blockedPath = join(storeRoot, "blocked.json"); + +function option(args: string[], name: string) { + const index = args.indexOf(name); + return index === -1 ? undefined : args[index + 1]; +} + +function printIssues(issues: ValidationIssue[]) { + const byApp = new Map(); + for (const issue of issues) { + const list = byApp.get(issue.app) ?? []; + list.push(issue); + byApp.set(issue.app, list); + } + for (const [app, list] of byApp) { + console.error(`\n${app}`); + for (const issue of list) { + console.error(` ${issue.file}: ${issue.message}`); + } + } + console.error( + `\n${issues.length} problem${issues.length === 1 ? "" : "s"} found. See app-store/README.md for the rules.`, + ); +} + +async function loadBase(ref: string): Promise> { + const base = new Map(); + const scratch = await mkdtemp(join(tmpdir(), "cap-app-store-base-")); + try { + let archive: Buffer; + try { + archive = execFileSync( + "git", + ["archive", "--format=tar", ref, "app-store/apps"], + { cwd: repoRoot, maxBuffer: 512 * 1024 * 1024 }, + ); + } catch { + return base; + } + execFileSync("tar", ["-x", "-C", scratch], { input: archive }); + const root = join(scratch, "app-store", "apps"); + for (const folder of await listAppFolders(root)) { + const { app } = await loadApp(join(root, folder), folder); + if (app) { + base.set(app.id, { + version: app.manifest.version, + contentHash: app.contentHash, + secretKeys: secretKeysOf(app.manifest), + }); + } + } + return base; + } finally { + await rm(scratch, { recursive: true, force: true }); + } +} + +async function readBlocked() { + try { + const raw = JSON.parse(await readFile(blockedPath, "utf8")); + return Schema.decodeUnknownSync(Schema.Array(BlockedApp))(raw); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } +} + +export function manifestJsonSchema() { + return `${JSON.stringify(JSONSchema.make(Manifest), null, "\t")}\n`; +} + +async function validateCommand(args: string[]) { + const ref = option(args, "--base"); + const base = ref ? await loadBase(ref) : undefined; + const { apps, issues } = await validateAppStore(appsRoot, { base }); + const committedSchema = await readFile(schemaPath, "utf8").catch(() => ""); + const schemaDrift = + JSON.stringify(JSON.parse(committedSchema || "null")) !== + JSON.stringify(JSON.parse(manifestJsonSchema())); + if (schemaDrift) { + issues.push({ + app: "app-store", + file: "manifest.schema.json", + message: "is out of date. Run `bun app-store schema`", + }); + } + if (issues.length > 0) { + printIssues(issues); + process.exitCode = 1; + return; + } + console.log(`${apps.length} apps are valid.`); +} + +async function buildCommand(args: string[]) { + const catalogPath = option(args, "--catalog"); + const assetsDir = option(args, "--assets"); + const assetBaseUrl = option(args, "--asset-base-url") ?? "/app-store"; + if (!catalogPath || !assetsDir) { + throw new Error( + "Usage: app-store build --catalog --assets [--asset-base-url /app-store]", + ); + } + const { apps, issues } = await validateAppStore(appsRoot); + if (issues.length > 0) { + printIssues(issues); + process.exitCode = 1; + return; + } + const { catalog, files } = buildCatalog(apps, { + assetBaseUrl, + blocked: await readBlocked(), + }); + const assetsRoot = resolve(assetsDir); + await rm(assetsRoot, { recursive: true, force: true }); + for (const file of files) { + const target = join(assetsRoot, file.path); + await mkdir(dirname(target), { recursive: true }); + await writeFile(target, file.bytes); + } + const catalogFile = resolve(catalogPath); + await mkdir(dirname(catalogFile), { recursive: true }); + await writeFile(catalogFile, `${JSON.stringify(catalog)}\n`); + console.log( + `Built the App Store catalog: ${catalog.apps.length} apps, ${files.length} assets, revision ${catalog.revision}.`, + ); +} + +async function schemaCommand() { + await writeFile(schemaPath, manifestJsonSchema()); + const biome = join(repoRoot, "node_modules/.bin/biome"); + if (await stat(biome).catch(() => null)) { + execFileSync(biome, ["format", "--write", schemaPath], { cwd: repoRoot }); + } + console.log(`Wrote ${schemaPath}`); +} + +async function newCommand(args: string[]) { + const id = args[0]; + const template = option(args, "--template") ?? "content"; + if (!id || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) { + throw new Error( + "Usage: app-store new [--template content|connection]", + ); + } + const source = join(storeRoot, "templates", template); + const target = join(appsRoot, id); + if (!(await stat(source).catch(() => null))) { + throw new Error(`Unknown template "${template}"`); + } + if (await stat(target).catch(() => null)) { + throw new Error(`app-store/apps/${id} already exists`); + } + await cp(source, target, { recursive: true }); + const manifestPath = join(target, "manifest.json"); + const manifest = await readFile(manifestPath, "utf8"); + await writeFile(manifestPath, manifest.replaceAll("my-app", id)); + console.log( + `Created app-store/apps/${id}. Edit manifest.json, replace icon.png and README.md, then run \`bun app-store validate\`.`, + ); +} + +const [command, ...rest] = process.argv.slice(2); +const commands: Record Promise> = { + validate: validateCommand, + build: buildCommand, + schema: schemaCommand, + new: newCommand, +}; + +const run = command ? commands[command] : undefined; +if (!run) { + console.error("Usage: app-store [options]"); + process.exitCode = 1; +} else { + run(rest).catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }); +} diff --git a/packages/app-store/src/connection-url.ts b/packages/app-store/src/connection-url.ts new file mode 100644 index 00000000000..ed988c37976 --- /dev/null +++ b/packages/app-store/src/connection-url.ts @@ -0,0 +1,64 @@ +const IPV4 = /^\d{1,3}(?:\.\d{1,3}){3}$/; + +export type ConnectionUrlProblem = + | "invalid" + | "https_required" + | "credentials" + | "port" + | "query_or_fragment" + | "trailing_slash" + | "not_public"; + +export const CONNECTION_URL_PROBLEM_MESSAGES: Record< + ConnectionUrlProblem, + string +> = { + invalid: "is not a valid URL", + https_required: "must start with https://", + credentials: "must not contain a username or password", + port: "must use the default https port", + query_or_fragment: "must not contain a query string or fragment", + trailing_slash: "must not end with a slash", + not_public: "must use a public hostname, not an IP address or local name", +}; + +export function connectionUrlProblem( + value: string, +): ConnectionUrlProblem | null { + let url: URL; + try { + url = new URL(value); + } catch { + return "invalid"; + } + if (url.protocol !== "https:") return "https_required"; + if (url.username || url.password) return "credentials"; + if (url.port !== "") return "port"; + if (url.search || url.hash || value.includes("?") || value.includes("#")) + return "query_or_fragment"; + if (value.endsWith("/")) return "trailing_slash"; + // A trailing dot names the same host ("localhost." is localhost). + const host = url.hostname.toLowerCase().replace(/\.$/, ""); + if ( + IPV4.test(host) || + host.startsWith("[") || + !host.includes(".") || + host === "localhost" || + host.endsWith(".localhost") || + host.endsWith(".local") || + host.endsWith(".internal") || + host.endsWith(".test") || + host.endsWith(".example") || + host.endsWith(".invalid") + ) + return "not_public"; + return null; +} + +export const connectionEndpoint = ( + baseUrl: string, + kind: "lifecycle" | "events" | { action: string }, +) => + typeof kind === "string" + ? `${baseUrl}/${kind}` + : `${baseUrl}/actions/${encodeURIComponent(kind.action)}`; diff --git a/packages/app-store/src/constants.ts b/packages/app-store/src/constants.ts new file mode 100644 index 00000000000..cd5c807b2d8 --- /dev/null +++ b/packages/app-store/src/constants.ts @@ -0,0 +1,165 @@ +export const APP_STORE_API_VERSIONS = [1] as const; +export type AppStoreApiVersion = (typeof APP_STORE_API_VERSIONS)[number]; +export const CURRENT_APP_STORE_API_VERSION: AppStoreApiVersion = 1; + +export const APP_CATEGORIES = [ + "backgrounds", + "captions", + "color", + "communication", + "productivity", + "project-management", + "documentation", + "storage", + "automation", + "developer-tools", + "sales", + "education", +] as const; +export type AppCategory = (typeof APP_CATEGORIES)[number]; + +export const APP_CATEGORY_LABELS: Record = { + backgrounds: "Backgrounds", + captions: "Captions", + color: "Color", + communication: "Communication", + productivity: "Productivity", + "project-management": "Project management", + documentation: "Documentation", + storage: "Storage", + automation: "Automation", + "developer-tools": "Developer tools", + sales: "Sales", + education: "Education", +}; + +export const APP_LICENSES = [ + "MIT", + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "MPL-2.0", + "Unlicense", + "CC0-1.0", + "CC-BY-4.0", +] as const; +export type AppLicense = (typeof APP_LICENSES)[number]; + +export const CAP_EVENTS = [ + "cap.ready", + "cap.transcript.ready", + "cap.summary.ready", + "cap.comment.created", +] as const; +export type CapEventType = (typeof CAP_EVENTS)[number]; + +export const CAP_EVENT_DESCRIPTIONS: Record = { + "cap.ready": "A new Cap finished uploading", + "cap.transcript.ready": "A Cap's transcript is ready", + "cap.summary.ready": "A Cap's AI summary is ready", + "cap.comment.created": "Someone commented on a Cap", +}; + +export const CONNECTION_PERMISSIONS = [ + "cap.transcript", + "cap.summary", + "cap.comments", +] as const; + +export const BASE_PERMISSION_DESCRIPTION = + "Title, share link, owner name, length and creation time of Caps it can see"; + +export const CONNECTION_PERMISSION_DESCRIPTIONS: Record< + (typeof CONNECTION_PERMISSIONS)[number], + string +> = { + "cap.transcript": "Transcripts", + "cap.summary": "AI titles, summaries and chapters", + "cap.comments": "Comment text and commenter names", +}; + +export const EVENT_REQUIRED_PERMISSION: Partial< + Record +> = { + "cap.transcript.ready": "cap.transcript", + "cap.summary.ready": "cap.summary", + "cap.comment.created": "cap.comments", +}; + +export const BUILTIN_APPS = ["slack", "amazon-s3", "google-drive"] as const; +export type BuiltinApp = (typeof BUILTIN_APPS)[number]; + +export const FIRST_PARTY_GITHUB_OWNER = "CapSoftware"; + +// Apps published by Cap. The author field in a manifest is self-declared, so +// only the apps listed here are shown as made by Cap, may use reserved words +// in their id, may be built-in, or may use a first-party connection URL. +// Adding an id here is a code change, reviewed separately from app folders. +export const FIRST_PARTY_APPS = [ + "amazon-s3", + "aurora-backgrounds", + "discord", + "film-looks", + "google-drive", + "slack", + "studio-captions", +] as const; + +export const isFirstPartyApp = (manifest: { + id: string; + author: { github: string }; +}) => + manifest.author.github === FIRST_PARTY_GITHUB_OWNER && + (FIRST_PARTY_APPS as readonly string[]).includes(manifest.id); + +export const RESERVED_ID_WORDS = ["cap", "official"] as const; + +export const LIMITS = { + idMinLength: 3, + idMaxLength: 40, + itemIdMaxLength: 40, + nameMinLength: 2, + nameMaxLength: 30, + descriptionMinLength: 10, + descriptionMaxLength: 140, + itemNameMaxLength: 30, + itemDescriptionMaxLength: 80, + keywordsMax: 8, + keywordMaxLength: 24, + categoriesMax: 3, + backgroundsMax: 24, + captionStylesMax: 12, + colorLooksMax: 12, + settingsMax: 20, + settingOptionsMax: 50, + actionsMax: 5, + actionTitleMaxLength: 30, + settingLabelMaxLength: 40, + settingDescriptionMaxLength: 160, + settingDefaultMaxLength: 500, + urlMaxLength: 512, + iconSize: 512, + iconMaxBytes: 256 * 1024, + backgroundMinWidth: 1920, + backgroundMinHeight: 1080, + backgroundMaxDimension: 7680, + backgroundMaxBytes: 8 * 1024 * 1024, + screenshotsMax: 6, + screenshotWidth: 2000, + screenshotHeight: 1250, + screenshotMaxBytes: 2 * 1024 * 1024, + readmeMaxBytes: 64 * 1024, + appMaxBytes: 25 * 1024 * 1024, + captionSizeMin: 12, + captionSizeMax: 200, +} as const; + +export const CONNECTION_TIMEOUT_MS = 10_000; +export const SIGNATURE_TOLERANCE_SECONDS = 300; + +export const SIGNATURE_HEADER = "Cap-Signature"; +export const TIMESTAMP_HEADER = "Cap-Timestamp"; +export const REQUEST_ID_HEADER = "Cap-Request-Id"; +export const REQUEST_KIND_HEADER = "Cap-Request-Kind"; +export const PUBLIC_KEYS_PATH = "/.well-known/cap-app-store-keys.json"; diff --git a/packages/app-store/src/image-info.ts b/packages/app-store/src/image-info.ts new file mode 100644 index 00000000000..04b592c9e1c --- /dev/null +++ b/packages/app-store/src/image-info.ts @@ -0,0 +1,107 @@ +export type ImageFormat = "png" | "jpeg" | "webp"; + +export type ImageInfo = { + format: ImageFormat; + width: number; + height: number; +}; + +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; + +function readPng(bytes: Uint8Array): ImageInfo | null { + if (bytes.length < 24) return null; + for (let i = 0; i < PNG_SIGNATURE.length; i++) { + if (bytes[i] !== PNG_SIGNATURE[i]) return null; + } + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const chunkType = String.fromCharCode(...bytes.subarray(12, 16)); + if (chunkType !== "IHDR") return null; + return { + format: "png", + width: view.getUint32(16), + height: view.getUint32(20), + }; +} + +const JPEG_SOF_MARKERS = new Set([ + 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, +]); + +function readJpeg(bytes: Uint8Array): ImageInfo | null { + if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let offset = 2; + while (offset + 4 <= bytes.length) { + if (bytes[offset] !== 0xff) return null; + const marker = bytes[offset + 1] ?? 0; + if (marker === 0xff) { + offset += 1; + continue; + } + if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) { + offset += 2; + continue; + } + const length = view.getUint16(offset + 2); + if (length < 2) return null; + if (JPEG_SOF_MARKERS.has(marker)) { + if (offset + 9 > bytes.length) return null; + return { + format: "jpeg", + height: view.getUint16(offset + 5), + width: view.getUint16(offset + 7), + }; + } + offset += 2 + length; + } + return null; +} + +function readWebp(bytes: Uint8Array): ImageInfo | null { + if (bytes.length < 30) return null; + const riff = String.fromCharCode(...bytes.subarray(0, 4)); + const webp = String.fromCharCode(...bytes.subarray(8, 12)); + if (riff !== "RIFF" || webp !== "WEBP") return null; + const chunk = String.fromCharCode(...bytes.subarray(12, 16)); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (chunk === "VP8X") { + const width = + 1 + + ((bytes[24] ?? 0) | ((bytes[25] ?? 0) << 8) | ((bytes[26] ?? 0) << 16)); + const height = + 1 + + ((bytes[27] ?? 0) | ((bytes[28] ?? 0) << 8) | ((bytes[29] ?? 0) << 16)); + return { format: "webp", width, height }; + } + if (chunk === "VP8 ") { + return { + format: "webp", + width: view.getUint16(26, true) & 0x3fff, + height: view.getUint16(28, true) & 0x3fff, + }; + } + if (chunk === "VP8L") { + const b0 = bytes[21] ?? 0; + const b1 = bytes[22] ?? 0; + const b2 = bytes[23] ?? 0; + const b3 = bytes[24] ?? 0; + return { + format: "webp", + width: 1 + (((b1 & 0x3f) << 8) | b0), + height: 1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)), + }; + } + return null; +} + +export function readImageInfo(bytes: Uint8Array): ImageInfo | null { + return readPng(bytes) ?? readJpeg(bytes) ?? readWebp(bytes); +} + +export const formatForPath = (path: string): ImageFormat | null => { + const lower = path.toLowerCase(); + if (lower.endsWith(".png")) return "png"; + if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "jpeg"; + if (lower.endsWith(".webp")) return "webp"; + return null; +}; diff --git a/packages/app-store/src/index.ts b/packages/app-store/src/index.ts new file mode 100644 index 00000000000..52b49d4abe2 --- /dev/null +++ b/packages/app-store/src/index.ts @@ -0,0 +1,5 @@ +export * from "./catalog"; +export * from "./connection-url"; +export * from "./constants"; +export * from "./manifest"; +export * from "./protocol"; diff --git a/packages/app-store/src/manifest.ts b/packages/app-store/src/manifest.ts new file mode 100644 index 00000000000..0bbc0fa84c2 --- /dev/null +++ b/packages/app-store/src/manifest.ts @@ -0,0 +1,390 @@ +import { Either, ParseResult, Schema } from "effect"; +import { + APP_CATEGORIES, + APP_LICENSES, + APP_STORE_API_VERSIONS, + BUILTIN_APPS, + CAP_EVENTS, + CONNECTION_PERMISSIONS, + LIMITS, +} from "./constants"; + +// Control characters, bidi overrides and zero-width characters let a listing +// look like something else ("Slack" with a zero-width joiner, a name that +// renders backwards), so text shown to people may not contain them. +const HIDDEN_CHARACTERS = /[\p{Cc}\p{Cf}]/u; + +const boundedString = (min: number, max: number) => + Schema.String.pipe( + Schema.minLength(min), + Schema.maxLength(max), + Schema.filter((value) => value.trim() === value, { + message: () => "must not start or end with whitespace", + jsonSchema: {}, + }), + Schema.filter((value) => !HIDDEN_CHARACTERS.test(value), { + message: () => + "must not contain control, zero-width or text direction characters", + jsonSchema: {}, + }), + ); + +export const AppId = Schema.String.pipe( + Schema.minLength(LIMITS.idMinLength), + Schema.maxLength(LIMITS.idMaxLength), + Schema.pattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, { + message: () => "must be lowercase kebab-case, like my-app", + }), +).annotations({ + description: "Unique kebab-case id. Must match the folder name.", +}); + +export const ItemId = Schema.String.pipe( + Schema.minLength(1), + Schema.maxLength(LIMITS.itemIdMaxLength), + Schema.pattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, { + message: () => "must be lowercase kebab-case", + }), +); + +export const Semver = Schema.String.pipe( + Schema.pattern(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/, { + message: () => "must be a version like 1.2.3", + }), +); + +export const HexColor = Schema.String.pipe( + Schema.pattern(/^#[0-9A-Fa-f]{6}$/, { + message: () => "must be a hex color like #1E90FF", + }), +); + +export const HttpsUrl = Schema.String.pipe( + Schema.maxLength(LIMITS.urlMaxLength), + Schema.pattern(/^https:\/\/[^\s]+$/, { + message: () => "must be an https:// URL", + }), +); + +export const ImagePath = Schema.String.pipe( + Schema.pattern( + /^(?:[a-z0-9][a-z0-9_-]*\/)*[a-z0-9][a-z0-9_-]*\.(?:png|jpg|jpeg|webp)$/, + { + message: () => + "must be a lowercase relative path to a .png, .jpg or .webp file inside the app folder", + }, + ), +); + +const unit = (min: number, max: number) => + Schema.Number.pipe(Schema.between(min, max)); + +const ItemName = boundedString(1, LIMITS.itemNameMaxLength); +const ItemDescription = boundedString(1, LIMITS.itemDescriptionMaxLength); + +export const ImageBackground = Schema.Struct({ + id: ItemId, + name: ItemName, + image: ImagePath, +}); + +export const GradientBackground = Schema.Struct({ + id: ItemId, + name: ItemName, + gradient: Schema.Struct({ + from: HexColor, + to: HexColor, + angle: Schema.Int.pipe(Schema.between(0, 359)), + }), +}); + +export const ColorBackground = Schema.Struct({ + id: ItemId, + name: ItemName, + color: HexColor, +}); + +export const Background = Schema.Union( + ImageBackground, + GradientBackground, + ColorBackground, +); +export type Background = typeof Background.Type; + +export const CaptionStyle = Schema.Struct({ + id: ItemId, + name: ItemName, + description: Schema.optional(ItemDescription), + fontWeight: Schema.Literal(400, 500, 700), + size: Schema.Int.pipe( + Schema.between(LIMITS.captionSizeMin, LIMITS.captionSizeMax), + ), + color: HexColor, + backgroundColor: HexColor, + backgroundOpacity: Schema.Int.pipe(Schema.between(0, 100)), + outline: Schema.Boolean, + outlineColor: HexColor, + highlightColor: HexColor, + activeWordHighlight: Schema.Boolean, + highlightStyle: Schema.Literal("color", "pill"), + animation: Schema.Literal("none", "bounce", "pop"), + uppercase: Schema.Boolean, + fadeDuration: unit(0, 1), +}); +export type CaptionStyle = typeof CaptionStyle.Type; + +export const ColorLook = Schema.Struct({ + id: ItemId, + name: ItemName, + description: Schema.optional(ItemDescription), + values: Schema.Struct({ + intensity: Schema.optional(unit(0, 1)), + exposure: Schema.optional(unit(-1, 1)), + contrast: Schema.optional(unit(-1, 1)), + saturation: Schema.optional(unit(-1, 1)), + temperature: Schema.optional(unit(-1, 1)), + tint: Schema.optional(unit(-1, 1)), + fade: Schema.optional(unit(0, 1)), + splitTone: Schema.optional(unit(-1, 1)), + vignette: Schema.optional(unit(0, 1)), + grain: Schema.optional(unit(0, 1)), + }), +}); +export type ColorLook = typeof ColorLook.Type; + +const SettingKey = Schema.String.pipe( + Schema.pattern(/^[a-z][a-zA-Z0-9]{0,39}$/, { + message: () => "must be camelCase, like webhookUrl", + }), +); + +const settingBase = { + key: SettingKey, + label: boundedString(1, LIMITS.settingLabelMaxLength), + description: Schema.optional( + boundedString(1, LIMITS.settingDescriptionMaxLength), + ), + required: Schema.optional(Schema.Boolean), +}; + +const Placeholder = boundedString(1, 80); +const DefaultText = Schema.String.pipe( + Schema.maxLength(LIMITS.settingDefaultMaxLength), +); + +export const TextSetting = Schema.Struct({ + ...settingBase, + type: Schema.Literal("text"), + placeholder: Schema.optional(Placeholder), + default: Schema.optional(DefaultText), +}); + +export const UrlSetting = Schema.Struct({ + ...settingBase, + type: Schema.Literal("url"), + placeholder: Schema.optional(Placeholder), + default: Schema.optional(HttpsUrl), +}); + +export const SecretSetting = Schema.Struct({ + ...settingBase, + type: Schema.Literal("secret"), + placeholder: Schema.optional(Placeholder), +}); + +export const SelectSetting = Schema.Struct({ + ...settingBase, + type: Schema.Literal("select"), + options: Schema.Array( + Schema.Struct({ + value: boundedString(1, 64), + label: boundedString(1, LIMITS.settingLabelMaxLength), + }), + ).pipe(Schema.minItems(1), Schema.maxItems(LIMITS.settingOptionsMax)), + default: Schema.optional(boundedString(1, 64)), +}); + +export const ToggleSetting = Schema.Struct({ + key: SettingKey, + label: boundedString(1, LIMITS.settingLabelMaxLength), + description: Schema.optional( + boundedString(1, LIMITS.settingDescriptionMaxLength), + ), + type: Schema.Literal("toggle"), + default: Schema.optional(Schema.Boolean), +}); + +export const SettingField = Schema.Union( + TextSetting, + UrlSetting, + SecretSetting, + SelectSetting, + ToggleSetting, +); +export type SettingField = typeof SettingField.Type; + +export const ConnectionAction = Schema.Struct({ + id: ItemId, + title: boundedString(2, LIMITS.actionTitleMaxLength), + target: Schema.Literal("cap"), +}); +export type ConnectionAction = typeof ConnectionAction.Type; + +export const ConnectionPermission = Schema.Literal(...CONNECTION_PERMISSIONS); +export type ConnectionPermission = typeof ConnectionPermission.Type; +export const CapEvent = Schema.Literal(...CAP_EVENTS); + +export const FIRST_PARTY_CONNECTION_PREFIX = "/api/app-store/first-party/"; + +export const ConnectionUrl = Schema.String.pipe( + Schema.maxLength(LIMITS.urlMaxLength), + Schema.pattern( + /^(?:https:\/\/[^\s]+|\/api\/app-store\/first-party\/[a-z0-9-]+)$/, + { + message: () => "must be an https:// URL", + }, + ), +).annotations({ + description: + "Base URL of your server. Cap sends signed requests to {url}/lifecycle, {url}/events and {url}/actions/{actionId}.", +}); + +export const isFirstPartyConnectionUrl = (url: string) => + url.startsWith(FIRST_PARTY_CONNECTION_PREFIX); + +export const Connection = Schema.Struct({ + url: ConnectionUrl, + permissions: Schema.optional(Schema.Array(ConnectionPermission)), + events: Schema.optional(Schema.Array(CapEvent)), + settings: Schema.optional( + Schema.Array(SettingField).pipe(Schema.maxItems(LIMITS.settingsMax)), + ), + actions: Schema.optional( + Schema.Array(ConnectionAction).pipe(Schema.maxItems(LIMITS.actionsMax)), + ), +}); +export type Connection = typeof Connection.Type; + +export const Author = Schema.Struct({ + name: boundedString(1, 60), + github: Schema.String.pipe( + Schema.pattern(/^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/, { + message: () => "must be a GitHub username or organization", + }), + ), + url: Schema.optional(HttpsUrl), +}); + +export const Manifest = Schema.Struct({ + $schema: Schema.optional(Schema.String), + apiVersion: Schema.Literal(...APP_STORE_API_VERSIONS).annotations({ + description: "The App Store API version this app is written for.", + }), + id: AppId, + name: boundedString(LIMITS.nameMinLength, LIMITS.nameMaxLength).annotations({ + description: "Shown in the store. Title Case, 2 to 30 characters.", + }), + version: Semver.annotations({ + description: + "Semver like 1.2.3. Raise it whenever anything in the app folder changes.", + }), + description: boundedString( + LIMITS.descriptionMinLength, + LIMITS.descriptionMaxLength, + ).annotations({ + description: "One sentence, 10 to 140 characters, ending with a full stop.", + }), + author: Author, + license: Schema.Literal(...APP_LICENSES).annotations({ + description: "The license your app is published under.", + }), + categories: Schema.Array(Schema.Literal(...APP_CATEGORIES)).pipe( + Schema.minItems(1), + Schema.maxItems(LIMITS.categoriesMax), + ), + keywords: Schema.optional( + Schema.Array(boundedString(2, LIMITS.keywordMaxLength)).pipe( + Schema.maxItems(LIMITS.keywordsMax), + ), + ), + homepage: Schema.optional(HttpsUrl), + support: Schema.optional(HttpsUrl), + privacyPolicy: Schema.optional( + HttpsUrl.annotations({ + description: + "Required for apps with a connection, because Cap sends them data.", + }), + ), + screenshots: Schema.optional( + Schema.Array(ImagePath).pipe(Schema.maxItems(LIMITS.screenshotsMax)), + ), + builtin: Schema.optional( + Schema.Literal(...BUILTIN_APPS).annotations({ + description: + "Only for apps published by Cap that use one of Cap's own integrations.", + }), + ), + backgrounds: Schema.optional( + Schema.Array(Background).pipe( + Schema.minItems(1), + Schema.maxItems(LIMITS.backgroundsMax), + ), + ), + captionStyles: Schema.optional( + Schema.Array(CaptionStyle).pipe( + Schema.minItems(1), + Schema.maxItems(LIMITS.captionStylesMax), + ), + ), + colorLooks: Schema.optional( + Schema.Array(ColorLook).pipe( + Schema.minItems(1), + Schema.maxItems(LIMITS.colorLooksMax), + ), + ), + connection: Schema.optional(Connection), +}).annotations({ + identifier: "CapAppManifest", + title: "Cap App manifest", + description: + "Describes a Cap App. See https://github.com/CapSoftware/Cap/tree/main/app-store", +}); +export type Manifest = typeof Manifest.Type; + +export type ManifestIssue = { path: string; message: string }; + +const formatPath = (path: ReadonlyArray) => + path.length === 0 + ? "manifest" + : path + .map((segment, index) => + typeof segment === "number" + ? `[${segment}]` + : index === 0 + ? String(segment) + : `.${String(segment)}`, + ) + .join(""); + +const decodeManifest = Schema.decodeUnknownEither(Manifest, { + errors: "all", + onExcessProperty: "error", +}); + +export function parseManifest( + input: unknown, +): { ok: true; manifest: Manifest } | { ok: false; issues: ManifestIssue[] } { + const result = decodeManifest(input); + if (Either.isRight(result)) return { ok: true, manifest: result.right }; + const issues = ParseResult.ArrayFormatter.formatErrorSync(result.left).map( + (issue) => ({ path: formatPath(issue.path), message: issue.message }), + ); + return { ok: false, issues }; +} + +export const isImageBackground = ( + background: Background, +): background is typeof ImageBackground.Type => "image" in background; +export const isGradientBackground = ( + background: Background, +): background is typeof GradientBackground.Type => "gradient" in background; diff --git a/packages/app-store/src/protocol.ts b/packages/app-store/src/protocol.ts new file mode 100644 index 00000000000..e95a6b904e3 --- /dev/null +++ b/packages/app-store/src/protocol.ts @@ -0,0 +1,105 @@ +import { Either, Schema } from "effect"; +import type { CapEventType } from "./constants"; +import { HttpsUrl } from "./manifest"; + +export type SettingValue = string | boolean; +export type InstallationSettings = Record; + +export type InstallationRef = { + id: string; + scope: "user" | "organization"; + organizationId: string | null; + installedByUserId: string; +}; + +export type AppRef = { id: string; version: string }; + +export type CapChapter = { title: string; startSeconds: number }; + +export type CapPayload = { + id: string; + title: string; + url: string; + ownerName: string | null; + organizationId: string | null; + createdAt: string; + durationSeconds: number | null; + transcript?: string | null; + summary?: { + title: string | null; + summary: string | null; + chapters: CapChapter[]; + } | null; +}; + +export type CommentPayload = { + id: string; + text: string; + authorName: string | null; + createdAt: string; + timestampSeconds: number | null; + parentCommentId: string | null; +}; + +export type LifecycleRequest = { + kind: "lifecycle"; + type: "installed" | "settings.updated" | "uninstalled"; + app: AppRef; + installation: InstallationRef; + settings: InstallationSettings; +}; + +export type EventRequest = { + kind: "event"; + id: string; + type: CapEventType; + createdAt: string; + app: AppRef; + installation: InstallationRef; + settings: InstallationSettings; + data: { cap: CapPayload; comment?: CommentPayload }; +}; + +export type ActionRequest = { + kind: "action"; + action: string; + app: AppRef; + installation: InstallationRef; + settings: InstallationSettings; + user: { id: string; name: string | null }; + data: { cap: CapPayload }; +}; + +export type CapRequest = LifecycleRequest | EventRequest | ActionRequest; + +export const ACTION_MESSAGE_MAX_LENGTH = 140; + +export const ActionResult = Schema.Union( + Schema.Struct({ + type: Schema.Literal("toast"), + message: Schema.String.pipe( + Schema.minLength(1), + Schema.maxLength(ACTION_MESSAGE_MAX_LENGTH), + ), + }), + Schema.Struct({ + type: Schema.Literal("open"), + url: HttpsUrl, + message: Schema.optional( + Schema.String.pipe( + Schema.minLength(1), + Schema.maxLength(ACTION_MESSAGE_MAX_LENGTH), + ), + ), + }), +); +export type ActionResult = typeof ActionResult.Type; + +const decodeActionResult = Schema.decodeUnknownEither(ActionResult, { + onExcessProperty: "ignore", +}); + +export function parseActionResult(input: unknown): ActionResult | null { + const result = decodeActionResult(input); + return Either.isRight(result) ? result.right : null; +} diff --git a/packages/app-store/src/signing.ts b/packages/app-store/src/signing.ts new file mode 100644 index 00000000000..88695a5b92b --- /dev/null +++ b/packages/app-store/src/signing.ts @@ -0,0 +1,185 @@ +import { + createHash, + createPrivateKey, + createPublicKey, + hkdfSync, + type KeyObject, + sign, + verify, +} from "node:crypto"; +import { + REQUEST_ID_HEADER, + REQUEST_KIND_HEADER, + SIGNATURE_HEADER, + SIGNATURE_TOLERANCE_SECONDS, + TIMESTAMP_HEADER, +} from "./constants"; + +export type CapRequestKind = "lifecycle" | "event" | "action"; + +export type CapPublicKey = { + kty: "OKP"; + crv: "Ed25519"; + x: string; + kid: string; + use: "sig"; + alg: "EdDSA"; +}; + +export type CapPublicKeySet = { keys: CapPublicKey[] }; + +const PKCS8_ED25519_PREFIX = Buffer.from( + "302e020100300506032b657004220420", + "hex", +); +const SIGNING_INFO = "cap-app-store-request-signing-v1"; +const SIGNING_SALT = "cap-app-store"; + +export type CapSigningKey = { + privateKey: KeyObject; + publicKey: CapPublicKey; +}; + +export function deriveSigningKey(serverSecret: string): CapSigningKey { + if (serverSecret.length < 16) { + throw new Error("The server secret is too short to derive a signing key"); + } + const seed = Buffer.from( + hkdfSync("sha256", serverSecret, SIGNING_SALT, SIGNING_INFO, 32), + ); + const privateKey = createPrivateKey({ + key: Buffer.concat([PKCS8_ED25519_PREFIX, seed]), + format: "der", + type: "pkcs8", + }); + const jwk = createPublicKey(privateKey).export({ format: "jwk" }); + if (typeof jwk.x !== "string") throw new Error("Could not export public key"); + const kid = createHash("sha256") + .update(Buffer.from(jwk.x, "base64url")) + .digest("hex") + .slice(0, 16); + return { + privateKey, + publicKey: { + kty: "OKP", + crv: "Ed25519", + x: jwk.x, + kid, + use: "sig", + alg: "EdDSA", + }, + }; +} + +const signedMessage = (timestamp: string, requestId: string, body: string) => + Buffer.from(`v1.${timestamp}.${requestId}.${body}`, "utf8"); + +export function signCapRequest(input: { + key: CapSigningKey; + body: string; + requestId: string; + kind: CapRequestKind; + now?: number; +}): Record { + const timestamp = String(Math.floor((input.now ?? Date.now()) / 1000)); + const signature = sign( + null, + signedMessage(timestamp, input.requestId, input.body), + input.key.privateKey, + ).toString("base64url"); + return { + [SIGNATURE_HEADER]: `kid=${input.key.publicKey.kid},v1=${signature}`, + [TIMESTAMP_HEADER]: timestamp, + [REQUEST_ID_HEADER]: input.requestId, + [REQUEST_KIND_HEADER]: input.kind, + }; +} + +export type VerifyFailure = + | "missing_headers" + | "bad_signature_header" + | "unknown_key" + | "stale_timestamp" + | "bad_signature" + | "kind_mismatch" + | "wrong_app"; + +// The signature covers the body, not the Cap-Request-Kind header or the URL, +// so the kind and the target app are read from the signed body. A request Cap +// signed for one app can otherwise be replayed to another app, or with a +// different kind header, within the timestamp tolerance. +function signedFields(body: string): { kind: unknown; appId: unknown } { + try { + const parsed: unknown = JSON.parse(body); + if (!parsed || typeof parsed !== "object") + return { kind: null, appId: null }; + const { kind, app } = parsed as { kind?: unknown; app?: { id?: unknown } }; + return { kind, appId: app?.id }; + } catch { + return { kind: null, appId: null }; + } +} + +const headerValue = ( + headers: Headers | Record, + name: string, +) => + headers instanceof Headers + ? (headers.get(name) ?? undefined) + : (headers[name] ?? headers[name.toLowerCase()]); + +export function verifyCapRequest(input: { + headers: Headers | Record; + body: string; + keys: CapPublicKeySet; + // Your app's id. When set, requests Cap signed for another app are refused. + appId?: string; + now?: number; + toleranceSeconds?: number; +}): + | { ok: true; requestId: string; kind: string } + | { ok: false; reason: VerifyFailure } { + const signatureHeader = headerValue(input.headers, SIGNATURE_HEADER); + const timestamp = headerValue(input.headers, TIMESTAMP_HEADER); + const requestId = headerValue(input.headers, REQUEST_ID_HEADER); + const kind = headerValue(input.headers, REQUEST_KIND_HEADER); + if (!signatureHeader || !timestamp || !requestId || !kind) { + return { ok: false, reason: "missing_headers" }; + } + const parts = new Map( + signatureHeader.split(",").map((part) => { + const index = part.indexOf("="); + return [part.slice(0, index).trim(), part.slice(index + 1).trim()]; + }), + ); + const kid = parts.get("kid"); + const signature = parts.get("v1"); + if (!kid || !signature || !/^\d+$/.test(timestamp)) { + return { ok: false, reason: "bad_signature_header" }; + } + const key = input.keys.keys.find((candidate) => candidate.kid === kid); + if (!key) return { ok: false, reason: "unknown_key" }; + const nowSeconds = Math.floor((input.now ?? Date.now()) / 1000); + const tolerance = input.toleranceSeconds ?? SIGNATURE_TOLERANCE_SECONDS; + if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) { + return { ok: false, reason: "stale_timestamp" }; + } + let valid = false; + try { + valid = verify( + null, + signedMessage(timestamp, requestId, input.body), + createPublicKey({ key: { ...key }, format: "jwk" }), + Buffer.from(signature, "base64url"), + ); + } catch { + valid = false; + } + if (!valid) return { ok: false, reason: "bad_signature" }; + const signed = signedFields(input.body); + if (signed.kind !== kind) return { ok: false, reason: "kind_mismatch" }; + if (input.appId !== undefined && signed.appId !== input.appId) { + return { ok: false, reason: "wrong_app" }; + } + return { ok: true, requestId, kind }; +} diff --git a/packages/app-store/src/validate.ts b/packages/app-store/src/validate.ts new file mode 100644 index 00000000000..4d391dfb899 --- /dev/null +++ b/packages/app-store/src/validate.ts @@ -0,0 +1,583 @@ +import { createHash } from "node:crypto"; +import { lstat, readdir, readFile } from "node:fs/promises"; +import { join, relative, sep } from "node:path"; +import { + CONNECTION_URL_PROBLEM_MESSAGES, + connectionUrlProblem, +} from "./connection-url"; +import { + EVENT_REQUIRED_PERMISSION, + FIRST_PARTY_GITHUB_OWNER, + isFirstPartyApp, + LIMITS, + RESERVED_ID_WORDS, +} from "./constants"; +import { formatForPath, type ImageInfo, readImageInfo } from "./image-info"; +import { + FIRST_PARTY_CONNECTION_PREFIX, + isFirstPartyConnectionUrl, + isImageBackground, + type Manifest, + parseManifest, +} from "./manifest"; + +export type ValidationIssue = { + app: string; + file: string; + message: string; +}; + +export type LoadedApp = { + id: string; + dir: string; + manifest: Manifest; + files: Map; + images: Map; + readme: string; + contentHash: string; +}; + +export const REQUIRED_FILES = ["manifest.json", "icon.png", "README.md"]; +export const OPTIONAL_FILES = ["CHANGELOG.md"]; + +async function walk( + root: string, + dir: string, + files: string[], + problems: string[], +): Promise { + const entries = await readdir(dir, { withFileTypes: true }); + for (const entry of entries) { + const full = join(dir, entry.name); + const rel = relative(root, full).split(sep).join("/"); + if (entry.name.startsWith(".")) { + problems.push(`${rel}: hidden files are not allowed`); + continue; + } + const stat = await lstat(full); + if (stat.isSymbolicLink()) { + problems.push(`${rel}: symlinks are not allowed`); + continue; + } + if (stat.isDirectory()) { + await walk(root, full, files, problems); + continue; + } + if (!stat.isFile()) { + problems.push(`${rel}: only regular files are allowed`); + continue; + } + if ((stat.mode & 0o111) !== 0) { + problems.push(`${rel}: executable files are not allowed`); + continue; + } + files.push(rel); + } +} + +export const hashBytes = (bytes: Uint8Array) => + createHash("sha256").update(bytes).digest("hex"); + +export function contentHashOf(files: Map) { + const hash = createHash("sha256"); + for (const path of [...files.keys()].sort()) { + const bytes = files.get(path); + if (!bytes) continue; + hash.update(path); + hash.update("\0"); + hash.update(hashBytes(bytes)); + hash.update("\n"); + } + return hash.digest("hex"); +} + +function referencedImages(manifest: Manifest) { + const paths = new Set(); + for (const background of manifest.backgrounds ?? []) { + if (isImageBackground(background)) paths.add(background.image); + } + for (const screenshot of manifest.screenshots ?? []) paths.add(screenshot); + return paths; +} + +function duplicates(values: readonly string[]) { + const seen = new Set(); + const repeated = new Set(); + for (const value of values) { + if (seen.has(value)) repeated.add(value); + seen.add(value); + } + return [...repeated]; +} + +function checkManifestRules( + manifest: Manifest, + folderName: string, + report: (file: string, message: string) => void, +) { + const firstParty = isFirstPartyApp(manifest); + if (manifest.author.github === FIRST_PARTY_GITHUB_OWNER && !firstParty) { + report( + "manifest.json", + `author.github "${FIRST_PARTY_GITHUB_OWNER}" is only for apps published by Cap`, + ); + } + if (manifest.id !== folderName) { + report( + "manifest.json", + `id "${manifest.id}" must match the folder name "${folderName}"`, + ); + } + if (!firstParty) { + const segments = manifest.id.split("-"); + for (const word of RESERVED_ID_WORDS) { + if (segments.includes(word)) { + report("manifest.json", `id must not contain the word "${word}"`); + } + } + } + if (manifest.builtin && !firstParty) { + report("manifest.json", "only apps published by Cap can be built-in"); + } + if (manifest.builtin && manifest.connection) { + report( + "manifest.json", + "a built-in app uses Cap's own integration and cannot also declare a connection", + ); + } + const contributes = + manifest.builtin || + manifest.backgrounds || + manifest.captionStyles || + manifest.colorLooks || + manifest.connection; + if (!contributes) { + report( + "manifest.json", + "an app must contribute something: backgrounds, captionStyles, colorLooks or connection", + ); + } + for (const category of duplicates(manifest.categories)) { + report("manifest.json", `category "${category}" is listed twice`); + } + for (const [label, items] of [ + ["backgrounds", manifest.backgrounds], + ["captionStyles", manifest.captionStyles], + ["colorLooks", manifest.colorLooks], + ] as const) { + for (const id of duplicates((items ?? []).map((item) => item.id))) { + report("manifest.json", `${label} id "${id}" is used twice`); + } + } + const connection = manifest.connection; + if (!connection) return; + const problem = isFirstPartyConnectionUrl(connection.url) + ? null + : connectionUrlProblem(connection.url); + if (isFirstPartyConnectionUrl(connection.url)) { + if (!firstParty) { + report( + "manifest.json", + "connection.url must be an https:// URL on your own server", + ); + } else if ( + connection.url !== `${FIRST_PARTY_CONNECTION_PREFIX}${manifest.id}` + ) { + report( + "manifest.json", + `connection.url must be ${FIRST_PARTY_CONNECTION_PREFIX}${manifest.id}`, + ); + } + } + if (problem) { + report( + "manifest.json", + `connection.url ${CONNECTION_URL_PROBLEM_MESSAGES[problem]}`, + ); + } + if (!manifest.privacyPolicy) { + report( + "manifest.json", + "apps with a connection must link a privacyPolicy, because Cap sends them data", + ); + } + const events = connection.events ?? []; + const actions = connection.actions ?? []; + if (events.length === 0 && actions.length === 0) { + report( + "manifest.json", + "a connection must subscribe to at least one event or declare at least one action", + ); + } + for (const event of duplicates(events)) { + report("manifest.json", `event "${event}" is listed twice`); + } + const permissions = connection.permissions ?? []; + for (const permission of duplicates(permissions)) { + report("manifest.json", `permission "${permission}" is listed twice`); + } + for (const event of events) { + const required = EVENT_REQUIRED_PERMISSION[event]; + if (required && !permissions.includes(required)) { + report( + "manifest.json", + `event "${event}" needs the "${required}" permission`, + ); + } + } + for (const id of duplicates(actions.map((action) => action.id))) { + report("manifest.json", `action id "${id}" is used twice`); + } + const settings = connection.settings ?? []; + for (const key of duplicates(settings.map((setting) => setting.key))) { + report("manifest.json", `setting key "${key}" is used twice`); + } + for (const setting of settings) { + if (setting.type !== "select") continue; + const values = setting.options.map((option) => option.value); + for (const value of duplicates(values)) { + report( + "manifest.json", + `setting "${setting.key}" lists option "${value}" twice`, + ); + } + if (setting.default !== undefined && !values.includes(setting.default)) { + report( + "manifest.json", + `setting "${setting.key}" default must be one of its options`, + ); + } + } +} + +function checkImage( + path: string, + info: ImageInfo | null, + bytes: Uint8Array, + rule: { + label: string; + format?: ImageInfo["format"]; + exact?: { width: number; height: number }; + min?: { width: number; height: number }; + maxDimension?: number; + maxBytes: number; + }, + report: (file: string, message: string) => void, +) { + if (!info) { + report(path, `${rule.label} is not a readable PNG, JPEG or WebP image`); + return; + } + const expected = formatForPath(path); + if (expected !== info.format) { + report(path, `${rule.label} extension does not match its contents`); + } + if (rule.format && info.format !== rule.format) { + report(path, `${rule.label} must be a ${rule.format.toUpperCase()}`); + } + if ( + rule.exact && + (info.width !== rule.exact.width || info.height !== rule.exact.height) + ) { + report( + path, + `${rule.label} must be ${rule.exact.width}x${rule.exact.height}, found ${info.width}x${info.height}`, + ); + } + if ( + rule.min && + (info.width < rule.min.width || info.height < rule.min.height) + ) { + report( + path, + `${rule.label} must be at least ${rule.min.width}x${rule.min.height}, found ${info.width}x${info.height}`, + ); + } + if ( + rule.maxDimension && + (info.width > rule.maxDimension || info.height > rule.maxDimension) + ) { + report( + path, + `${rule.label} must be at most ${rule.maxDimension} pixels on each side`, + ); + } + if (bytes.byteLength > rule.maxBytes) { + report( + path, + `${rule.label} must be at most ${Math.round(rule.maxBytes / 1024)} KB`, + ); + } +} + +export async function loadApp( + dir: string, + folderName: string, +): Promise<{ app: LoadedApp | null; issues: ValidationIssue[] }> { + const issues: ValidationIssue[] = []; + const report = (file: string, message: string) => + issues.push({ app: folderName, file, message }); + + const paths: string[] = []; + const problems: string[] = []; + await walk(dir, dir, paths, problems); + for (const problem of problems) { + const [file, message] = problem.split(": "); + report(file ?? problem, message ?? problem); + } + + for (const required of REQUIRED_FILES) { + if (!paths.includes(required)) report(required, "is required"); + } + if (!paths.includes("manifest.json")) return { app: null, issues }; + + const files = new Map(); + for (const path of paths) { + files.set(path, new Uint8Array(await readFile(join(dir, path)))); + } + + let raw: unknown; + try { + raw = JSON.parse( + new TextDecoder().decode(files.get("manifest.json") ?? new Uint8Array()), + ); + } catch (error) { + report( + "manifest.json", + `is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, + ); + return { app: null, issues }; + } + + const parsed = parseManifest(raw); + if (!parsed.ok) { + for (const issue of parsed.issues) { + report("manifest.json", `${issue.path}: ${issue.message}`); + } + return { app: null, issues }; + } + const manifest = parsed.manifest; + checkManifestRules(manifest, folderName, report); + + const images = new Map(); + const referenced = referencedImages(manifest); + const allowed = new Set([ + ...REQUIRED_FILES, + ...OPTIONAL_FILES, + ...referenced, + ]); + for (const path of paths) { + if (!allowed.has(path)) { + report( + path, + "is not used by the manifest. Remove it, or reference it from manifest.json", + ); + } + } + for (const path of referenced) { + if (!files.has(path)) + report(path, "is referenced by the manifest but missing"); + } + + let total = 0; + for (const bytes of files.values()) total += bytes.byteLength; + if (total > LIMITS.appMaxBytes) { + report( + ".", + `the app folder must be at most ${LIMITS.appMaxBytes / 1024 / 1024} MB, found ${(total / 1024 / 1024).toFixed(1)} MB`, + ); + } + + const icon = files.get("icon.png"); + if (icon) { + const info = readImageInfo(icon); + if (info) images.set("icon.png", info); + checkImage( + "icon.png", + info, + icon, + { + label: "icon", + format: "png", + exact: { width: LIMITS.iconSize, height: LIMITS.iconSize }, + maxBytes: LIMITS.iconMaxBytes, + }, + report, + ); + } + + for (const background of manifest.backgrounds ?? []) { + if (!isImageBackground(background)) continue; + const bytes = files.get(background.image); + if (!bytes) continue; + const info = readImageInfo(bytes); + if (info) images.set(background.image, info); + checkImage( + background.image, + info, + bytes, + { + label: `background "${background.id}"`, + min: { + width: LIMITS.backgroundMinWidth, + height: LIMITS.backgroundMinHeight, + }, + maxDimension: LIMITS.backgroundMaxDimension, + maxBytes: LIMITS.backgroundMaxBytes, + }, + report, + ); + } + + for (const screenshot of manifest.screenshots ?? []) { + const bytes = files.get(screenshot); + if (!bytes) continue; + const info = readImageInfo(bytes); + if (info) images.set(screenshot, info); + checkImage( + screenshot, + info, + bytes, + { + label: "screenshot", + exact: { + width: LIMITS.screenshotWidth, + height: LIMITS.screenshotHeight, + }, + maxBytes: LIMITS.screenshotMaxBytes, + }, + report, + ); + } + + const readmeBytes = files.get("README.md"); + const readme = readmeBytes ? new TextDecoder().decode(readmeBytes) : ""; + if (readmeBytes) { + if (readmeBytes.byteLength > LIMITS.readmeMaxBytes) { + report("README.md", "must be at most 64 KB"); + } + if (readme.trim().length < 40) { + report( + "README.md", + "must explain what the app does and how to set it up", + ); + } + if (/<\s*(script|iframe|style|object|embed)\b/i.test(readme)) { + report( + "README.md", + "must not contain script, iframe, style or embed tags", + ); + } + } + + return { + app: { + id: manifest.id, + dir, + manifest, + files, + images, + readme, + contentHash: contentHashOf(files), + }, + issues, + }; +} + +export function compareSemver(a: string, b: string) { + const left = a.split(".").map(Number); + const right = b.split(".").map(Number); + for (let i = 0; i < 3; i++) { + const diff = (left[i] ?? 0) - (right[i] ?? 0); + if (diff !== 0) return Math.sign(diff); + } + return 0; +} + +export type BaseApp = { + version: string; + contentHash: string; + secretKeys?: string[]; +}; + +export const secretKeysOf = (manifest: Manifest) => + (manifest.connection?.settings ?? []) + .filter((setting) => setting.type === "secret") + .map((setting) => setting.key); + +export async function listAppFolders(appsRoot: string) { + const entries = await readdir(appsRoot, { withFileTypes: true }).catch( + () => [], + ); + return entries + .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")) + .map((entry) => entry.name) + .sort(); +} + +export async function validateAppStore( + appsRoot: string, + options: { base?: Map } = {}, +): Promise<{ apps: LoadedApp[]; issues: ValidationIssue[] }> { + const issues: ValidationIssue[] = []; + const apps: LoadedApp[] = []; + const rootEntries = await readdir(appsRoot, { withFileTypes: true }).catch( + () => [], + ); + for (const entry of rootEntries) { + if (!entry.isDirectory()) { + issues.push({ + app: entry.name, + file: entry.name, + message: "only app folders are allowed in app-store/apps", + }); + } + } + for (const folder of await listAppFolders(appsRoot)) { + const result = await loadApp(join(appsRoot, folder), folder); + issues.push(...result.issues); + if (result.app) apps.push(result.app); + } + + const names = new Map(); + for (const app of apps) { + const key = app.manifest.name.toLowerCase(); + const other = names.get(key); + if (other) { + issues.push({ + app: app.id, + file: "manifest.json", + message: `name "${app.manifest.name}" is already used by ${other}`, + }); + } + names.set(key, app.id); + } + + if (options.base) { + for (const app of apps) { + const previous = options.base.get(app.id); + if (!previous || previous.contentHash === app.contentHash) continue; + for (const key of previous.secretKeys ?? []) { + const setting = app.manifest.connection?.settings?.find( + (candidate) => candidate.key === key, + ); + if (setting && setting.type !== "secret") { + issues.push({ + app: app.id, + file: "manifest.json", + message: `setting "${key}" was a secret and must stay one. Use a new key for a different kind of value`, + }); + } + } + if (compareSemver(app.manifest.version, previous.version) <= 0) { + issues.push({ + app: app.id, + file: "manifest.json", + message: `the app changed, so version must go above ${previous.version}`, + }); + } + } + } + + return { apps, issues }; +} diff --git a/packages/app-store/test/app-store.test.ts b/packages/app-store/test/app-store.test.ts new file mode 100644 index 00000000000..d65b04cc301 --- /dev/null +++ b/packages/app-store/test/app-store.test.ts @@ -0,0 +1,549 @@ +import { + chmod, + cp, + mkdtemp, + readFile, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildCatalog } from "../src/build"; +import { platformsFor } from "../src/catalog"; +import { connectionUrlProblem } from "../src/connection-url"; +import { readImageInfo } from "../src/image-info"; +import { type Manifest, parseManifest } from "../src/manifest"; +import { parseActionResult } from "../src/protocol"; +import { + deriveSigningKey, + signCapRequest, + verifyCapRequest, +} from "../src/signing"; +import { loadApp, validateAppStore } from "../src/validate"; + +const repoRoot = resolve(import.meta.dirname, "../../.."); +const appsRoot = join(repoRoot, "app-store/apps"); +const templatesRoot = join(repoRoot, "app-store/templates"); + +const scratchDirs: string[] = []; +async function scratch() { + const dir = await mkdtemp(join(tmpdir(), "cap-app-store-test-")); + scratchDirs.push(dir); + return dir; +} + +afterEach(async () => { + await Promise.all( + scratchDirs + .splice(0) + .map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +async function appFromTemplate( + template: "content" | "connection", + id = "my-app", + edit?: (manifest: Record) => void, +) { + const root = await scratch(); + const dir = join(root, id); + await cp(join(templatesRoot, template), dir, { recursive: true }); + const manifestPath = join(dir, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + manifest.id = id; + edit?.(manifest); + await writeFile(manifestPath, JSON.stringify(manifest)); + return { root, dir }; +} + +const messagesFor = async (dir: string, id = "my-app") => + (await loadApp(dir, id)).issues.map( + (issue) => `${issue.file}: ${issue.message}`, + ); + +describe("the apps in this repo", () => { + it("are all valid", async () => { + const { apps, issues } = await validateAppStore(appsRoot); + expect(issues).toEqual([]); + expect(apps.length).toBeGreaterThan(0); + }); + + it("templates are valid apps", async () => { + for (const template of ["content", "connection"] as const) { + const { dir } = await appFromTemplate(template); + expect(await messagesFor(dir)).toEqual([]); + } + }); +}); + +describe("manifest schema", () => { + const base = { + apiVersion: 1, + id: "my-app", + name: "My App", + version: "1.0.0", + description: "Adds something useful to Cap.", + author: { name: "Someone", github: "someone" }, + license: "MIT", + categories: ["backgrounds"], + backgrounds: [{ id: "a", name: "A", color: "#112233" }], + }; + + it("accepts a minimal manifest", () => { + expect(parseManifest(base).ok).toBe(true); + }); + + it("rejects unknown keys", () => { + const result = parseManifest({ ...base, surprise: true }); + expect(result.ok).toBe(false); + }); + + it("rejects unsupported api versions, bad ids and bad versions", () => { + for (const patch of [ + { apiVersion: 2 }, + { id: "My_App" }, + { id: "ab" }, + { version: "1.0" }, + { version: "01.0.0" }, + { categories: [] }, + { categories: ["games"] }, + { license: "GPL-9" }, + { name: " Padded" }, + { name: "Sla\u200Dck" }, + { name: "Slack \u202Etsil" }, + { description: "Adds something\u200B useful to Cap." }, + { author: { name: "Cap\u2066", github: "someone" } }, + ]) { + expect( + parseManifest({ ...base, ...patch }).ok, + JSON.stringify(patch), + ).toBe(false); + } + }); + + it("rejects out of range content values", () => { + const look = { + id: "x", + name: "X", + values: { saturation: 2 }, + }; + expect(parseManifest({ ...base, colorLooks: [look] }).ok).toBe(false); + }); + + it("reports paths for problems", () => { + const result = parseManifest({ + ...base, + author: { name: "x", github: "-bad" }, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect( + result.issues.some((issue) => issue.path === "author.github"), + ).toBe(true); + } + }); +}); + +describe("validator guards", () => { + it("requires the id to match the folder", async () => { + const { dir } = await appFromTemplate("content", "my-app", (manifest) => { + manifest.id = "other-app"; + }); + expect((await messagesFor(dir)).join("\n")).toContain( + 'must match the folder name "my-app"', + ); + }); + + it("reserves words for first-party apps", async () => { + const { dir } = await appFromTemplate("content", "cap-themes"); + expect((await messagesFor(dir, "cap-themes")).join("\n")).toContain( + 'must not contain the word "cap"', + ); + }); + + it("rejects files the manifest does not use, hidden files and symlinks", async () => { + const { dir } = await appFromTemplate("content"); + await writeFile(join(dir, "notes.txt"), "hi"); + await writeFile(join(dir, ".env"), "SECRET=1"); + await symlink("/etc/hosts", join(dir, "hosts")); + const messages = (await messagesFor(dir)).join("\n"); + expect(messages).toContain("notes.txt: is not used by the manifest"); + expect(messages).toContain(".env: hidden files are not allowed"); + expect(messages).toContain("hosts: symlinks are not allowed"); + }); + + it("rejects executables", async () => { + const { dir } = await appFromTemplate("content"); + await chmod(join(dir, "README.md"), 0o755); + expect((await messagesFor(dir)).join("\n")).toContain( + "executable files are not allowed", + ); + }); + + it("checks the icon size", async () => { + const { dir } = await appFromTemplate("content"); + await cp( + join(appsRoot, "aurora-backgrounds/backgrounds/dawn.jpg"), + join(dir, "icon.png"), + ); + const messages = (await messagesFor(dir)).join("\n"); + expect(messages).toContain("icon extension does not match its contents"); + expect(messages).toContain("icon must be 512x512"); + }); + + it("checks background images", async () => { + const { dir } = await appFromTemplate("content", "my-app", (manifest) => { + manifest.backgrounds = [ + { id: "small", name: "Small", image: "small.png" }, + ]; + }); + await cp(join(dir, "icon.png"), join(dir, "small.png")); + expect((await messagesFor(dir)).join("\n")).toContain( + 'background "small" must be at least 1920x1080', + ); + }); + + it("requires a privacy policy, a public https url and matching permissions for connections", async () => { + const { dir } = await appFromTemplate( + "connection", + "my-app", + (manifest) => { + delete manifest.privacyPolicy; + const connection = manifest.connection as Record; + connection.url = "https://localhost/cap"; + connection.permissions = []; + }, + ); + const messages = (await messagesFor(dir)).join("\n"); + expect(messages).toContain("must link a privacyPolicy"); + expect(messages).toContain("must use a public hostname"); + expect(messages).toContain('needs the "cap.transcript" permission'); + }); + + it("keeps first-party connection paths and built-ins to Cap", async () => { + const { dir } = await appFromTemplate( + "connection", + "my-app", + (manifest) => { + (manifest.connection as Record).url = + "/api/app-store/first-party/my-app"; + }, + ); + expect((await messagesFor(dir)).join("\n")).toContain( + "must be an https:// URL on your own server", + ); + const builtin = await appFromTemplate("content", "my-app", (manifest) => { + manifest.builtin = "slack"; + }); + expect((await messagesFor(builtin.dir)).join("\n")).toContain( + "only apps published by Cap can be built-in", + ); + }); + + it("does not trust a self-declared Cap author", async () => { + const { root } = await appFromTemplate( + "content", + "cap-official-slack", + (manifest) => { + manifest.author = { name: "Cap", github: "CapSoftware" }; + manifest.builtin = "slack"; + }, + ); + const { apps, issues } = await validateAppStore(root); + const messages = issues.map((issue) => issue.message).join("\n"); + expect(messages).toContain( + 'author.github "CapSoftware" is only for apps published by Cap', + ); + expect(messages).toContain('must not contain the word "cap"'); + expect(messages).toContain("only apps published by Cap can be built-in"); + const { catalog } = buildCatalog(apps, { assetBaseUrl: "/app-store" }); + expect(catalog.apps[0]?.firstParty).toBe(false); + }); + + it("rejects duplicate setting keys and a select default outside its options", async () => { + const { dir } = await appFromTemplate( + "connection", + "my-app", + (manifest) => { + (manifest.connection as Record).settings = [ + { key: "a", type: "text", label: "A" }, + { key: "a", type: "text", label: "Again" }, + { + key: "mode", + type: "select", + label: "Mode", + options: [{ value: "x", label: "X" }], + default: "y", + }, + ]; + }, + ); + const messages = (await messagesFor(dir)).join("\n"); + expect(messages).toContain('setting key "a" is used twice'); + expect(messages).toContain( + 'setting "mode" default must be one of its options', + ); + }); + + it("requires a version bump when an app changes", async () => { + const { root, dir } = await appFromTemplate("content"); + const before = await loadApp(dir, "my-app"); + await writeFile( + join(dir, "README.md"), + "# My App\n\nA longer description of the app and how to use it.", + ); + const base = new Map([ + [ + "my-app", + { version: "1.0.0", contentHash: before.app?.contentHash ?? "" }, + ], + ]); + const changed = await validateAppStore(root, { base }); + expect(changed.issues.map((issue) => issue.message)).toContain( + "the app changed, so version must go above 1.0.0", + ); + const manifestPath = join(dir, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + manifest.version = "1.0.1"; + await writeFile(manifestPath, JSON.stringify(manifest)); + expect((await validateAppStore(root, { base })).issues).toEqual([]); + }); +}); + +describe("secret settings across versions", () => { + it("refuses an update that turns a secret into plain text", async () => { + const { root, dir } = await appFromTemplate("connection"); + const before = await loadApp(dir, "my-app"); + const manifestPath = join(dir, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + manifest.version = "1.1.0"; + manifest.connection.settings[0].type = "text"; + await writeFile(manifestPath, JSON.stringify(manifest)); + const base = new Map([ + [ + "my-app", + { + version: "1.0.0", + contentHash: before.app?.contentHash ?? "", + secretKeys: ["apiKey"], + }, + ], + ]); + const { issues } = await validateAppStore(root, { base }); + expect(issues.map((issue) => issue.message).join("\n")).toContain( + 'setting "apiKey" was a secret and must stay one', + ); + }); +}); + +describe("connection urls", () => { + it("accepts public https urls only", () => { + expect(connectionUrlProblem("https://example.com/cap")).toBeNull(); + expect(connectionUrlProblem("http://example.com")).toBe("https_required"); + expect(connectionUrlProblem("https://user:pw@example.com")).toBe( + "credentials", + ); + expect(connectionUrlProblem("https://example.com:8443")).toBe("port"); + expect(connectionUrlProblem("https://example.com/cap?x=1")).toBe( + "query_or_fragment", + ); + expect(connectionUrlProblem("https://example.com/cap/")).toBe( + "trailing_slash", + ); + expect(connectionUrlProblem("https://10.0.0.1/cap")).toBe("not_public"); + expect(connectionUrlProblem("https://[::1]/cap")).toBe("not_public"); + expect(connectionUrlProblem("https://intranet/cap")).toBe("not_public"); + expect(connectionUrlProblem("https://localhost./cap")).toBe("not_public"); + expect(connectionUrlProblem("https://metadata.google.internal./cap")).toBe( + "not_public", + ); + expect(connectionUrlProblem("https://intranet./cap")).toBe("not_public"); + }); +}); + +describe("image headers", () => { + it("reads png and jpeg sizes", async () => { + const icon = new Uint8Array( + await readFile(join(appsRoot, "discord/icon.png")), + ); + expect(readImageInfo(icon)).toEqual({ + format: "png", + width: 512, + height: 512, + }); + const jpeg = new Uint8Array( + await readFile(join(appsRoot, "aurora-backgrounds/backgrounds/dawn.jpg")), + ); + expect(readImageInfo(jpeg)).toEqual({ + format: "jpeg", + width: 2560, + height: 1440, + }); + expect(readImageInfo(new Uint8Array([1, 2, 3]))).toBeNull(); + }); +}); + +describe("catalog", () => { + it("is deterministic, content addressed and honours the block list", async () => { + const { apps } = await validateAppStore(appsRoot); + const first = buildCatalog(apps, { assetBaseUrl: "/app-store" }); + const second = buildCatalog([...apps].reverse(), { + assetBaseUrl: "/app-store", + }); + expect(second.catalog).toEqual(first.catalog); + for (const file of first.files) { + expect(file.path).toMatch(/^[a-z0-9-]+\/[0-9a-f]{32}\.(png|jpg|webp)$/); + } + const blocked = buildCatalog(apps, { + assetBaseUrl: "/app-store", + blocked: [{ id: "discord", reason: "test" }], + }); + expect(blocked.catalog.apps.some((app) => app.id === "discord")).toBe( + false, + ); + expect(blocked.files.some((file) => file.path.startsWith("discord/"))).toBe( + false, + ); + expect(blocked.catalog.revision).not.toBe(first.catalog.revision); + }); + + it("derives platforms from contributions", () => { + const manifest = (patch: Partial) => + ({ + apiVersion: 1, + id: "x-app", + name: "X", + version: "1.0.0", + description: "Something useful.", + author: { name: "x", github: "x" }, + license: "MIT", + categories: ["color"], + ...patch, + }) as Manifest; + expect(platformsFor(manifest({ colorLooks: [] }))).toEqual(["desktop"]); + expect( + platformsFor( + manifest({ + connection: { url: "https://x.dev", events: ["cap.ready"] }, + }), + ), + ).toEqual(["web"]); + expect( + platformsFor( + manifest({ + connection: { + url: "https://x.dev", + actions: [{ id: "a", title: "Do it", target: "cap" }], + }, + }), + ), + ).toEqual(["web", "desktop"]); + expect(platformsFor(manifest({ builtin: "slack" }))).toEqual(["web"]); + }); +}); + +describe("request signing", () => { + const key = deriveSigningKey("a-long-enough-server-secret-value"); + const keys = { keys: [key.publicKey] }; + + it("derives a stable key from the server secret", () => { + expect( + deriveSigningKey("a-long-enough-server-secret-value").publicKey, + ).toEqual(key.publicKey); + expect( + deriveSigningKey("another-long-server-secret-value").publicKey.x, + ).not.toBe(key.publicKey.x); + }); + + it("verifies signed requests and rejects tampering, replays and unknown keys", () => { + const now = 1_800_000_000_000; + const body = JSON.stringify({ kind: "event", id: "evt_1" }); + const headers = signCapRequest({ + key, + body, + requestId: "req_1", + kind: "event", + now, + }); + expect(verifyCapRequest({ headers, body, keys, now })).toEqual({ + ok: true, + requestId: "req_1", + kind: "event", + }); + expect(verifyCapRequest({ headers, body: `${body} `, keys, now })).toEqual({ + ok: false, + reason: "bad_signature", + }); + expect( + verifyCapRequest({ + headers: { ...headers, "Cap-Request-Id": "req_2" }, + body, + keys, + now, + }), + ).toEqual({ ok: false, reason: "bad_signature" }); + expect( + verifyCapRequest({ headers, body, keys, now: now + 10 * 60 * 1000 }), + ).toEqual({ ok: false, reason: "stale_timestamp" }); + const other = deriveSigningKey("another-long-server-secret-value"); + expect( + verifyCapRequest({ + headers, + body, + keys: { keys: [other.publicKey] }, + now, + }), + ).toEqual({ ok: false, reason: "unknown_key" }); + const web = new Headers(headers); + expect(verifyCapRequest({ headers: web, body, keys, now }).ok).toBe(true); + }); + + it("refuses a signed request replayed with another kind or to another app", () => { + const now = 1_800_000_000_000; + const body = JSON.stringify({ + kind: "action", + action: "send", + app: { id: "first-app", version: "1.0.0" }, + }); + const headers = signCapRequest({ + key, + body, + requestId: "req_1", + kind: "action", + now, + }); + expect( + verifyCapRequest({ headers, body, keys, now, appId: "first-app" }), + ).toEqual({ ok: true, requestId: "req_1", kind: "action" }); + expect( + verifyCapRequest({ + headers: { ...headers, "Cap-Request-Kind": "lifecycle" }, + body, + keys, + now, + }), + ).toEqual({ ok: false, reason: "kind_mismatch" }); + expect( + verifyCapRequest({ headers, body, keys, now, appId: "second-app" }), + ).toEqual({ ok: false, reason: "wrong_app" }); + }); +}); + +describe("action results", () => { + it("accepts toast and https open results only", () => { + expect(parseActionResult({ type: "toast", message: "Posted" })).toEqual({ + type: "toast", + message: "Posted", + }); + expect( + parseActionResult({ type: "open", url: "https://example.com/x" }), + ).toEqual({ type: "open", url: "https://example.com/x" }); + expect( + parseActionResult({ type: "open", url: "javascript:alert(1)" }), + ).toBeNull(); + expect(parseActionResult({ type: "html", body: "" })).toBeNull(); + expect(parseActionResult({ type: "toast", message: "" })).toBeNull(); + }); +}); diff --git a/packages/app-store/test/catalog-golden.test.ts b/packages/app-store/test/catalog-golden.test.ts new file mode 100644 index 00000000000..29c3339f9b1 --- /dev/null +++ b/packages/app-store/test/catalog-golden.test.ts @@ -0,0 +1,143 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { buildCatalog } from "../src/build"; +import type { ImageInfo } from "../src/image-info"; +import { type Manifest, parseManifest } from "../src/manifest"; +import { contentHashOf, type LoadedApp } from "../src/validate"; + +const fixture = join(import.meta.dirname, "fixtures/catalog.golden.json"); + +function fakeApp( + manifest: Manifest, + images: Record, +): LoadedApp { + const files = new Map(); + const infos = new Map(); + for (const [path, info] of Object.entries(images)) { + files.set(path, new TextEncoder().encode(`${manifest.id}:${path}`)); + infos.set(path, info); + } + files.set( + "manifest.json", + new TextEncoder().encode(JSON.stringify(manifest)), + ); + return { + id: manifest.id, + dir: `/apps/${manifest.id}`, + manifest, + files, + images: infos, + readme: `# ${manifest.name}\n\nFixture app.`, + contentHash: contentHashOf(files), + }; +} + +function manifest(input: unknown): Manifest { + const parsed = parseManifest(input); + if (!parsed.ok) throw new Error(JSON.stringify(parsed.issues)); + return parsed.manifest; +} + +const author = { name: "Fixture", github: "fixture" }; +const icon = { format: "png", width: 512, height: 512 } as const; + +const contentApp = fakeApp( + manifest({ + apiVersion: 1, + id: "fixture-content", + name: "Fixture Content", + version: "1.2.3", + description: "Every kind of content an app can add.", + author, + license: "MIT", + categories: ["backgrounds", "captions", "color"], + backgrounds: [ + { id: "photo", name: "Photo", image: "backgrounds/photo.jpg" }, + { + id: "sunset", + name: "Sunset", + gradient: { from: "#FF7E5F", to: "#6A3093", angle: 135 }, + }, + { id: "ink", name: "Ink", color: "#111827" }, + ], + captionStyles: [ + { + id: "bold", + name: "Bold", + description: "Big and bold", + fontWeight: 700, + size: 64, + color: "#FFFFFF", + backgroundColor: "#000000", + backgroundOpacity: 0, + outline: true, + outlineColor: "#000000", + highlightColor: "#FFD43B", + activeWordHighlight: true, + highlightStyle: "pill", + animation: "pop", + uppercase: true, + fadeDuration: 0.12, + }, + ], + colorLooks: [ + { + id: "warm", + name: "Warm", + values: { temperature: 0.3, vignette: 0.2, splitTone: -0.1 }, + }, + ], + }), + { + "icon.png": icon, + "backgrounds/photo.jpg": { format: "jpeg", width: 2560, height: 1440 }, + }, +); + +const connectionApp = fakeApp( + manifest({ + apiVersion: 1, + id: "fixture-connection", + name: "Fixture Connection", + version: "2.0.0", + description: "A connection with settings, events and actions.", + author, + license: "Apache-2.0", + categories: ["productivity"], + privacyPolicy: "https://fixture.dev/privacy", + connection: { + url: "https://fixture.dev/cap", + permissions: ["cap.transcript"], + events: ["cap.ready", "cap.transcript.ready"], + settings: [ + { key: "token", type: "secret", label: "Token", required: true }, + { + key: "mode", + type: "select", + label: "Mode", + options: [{ value: "all", label: "All" }], + default: "all", + }, + { key: "enabled", type: "toggle", label: "Enabled", default: true }, + ], + actions: [{ id: "send", title: "Send to Fixture", target: "cap" }], + }, + }), + { "icon.png": icon }, +); + +describe("catalog golden", () => { + it("matches the fixture the desktop app parses", async () => { + const { catalog } = buildCatalog([contentApp, connectionApp], { + assetBaseUrl: "/app-store", + }); + const json = `${JSON.stringify(catalog, null, "\t")}\n`; + if (process.env.UPDATE_GOLDEN === "1") { + await writeFile(fixture, json); + } + expect(JSON.parse(json)).toEqual( + JSON.parse(await readFile(fixture, "utf8")), + ); + }); +}); diff --git a/packages/app-store/test/fixtures/catalog.golden.json b/packages/app-store/test/fixtures/catalog.golden.json new file mode 100644 index 00000000000..671680fb477 --- /dev/null +++ b/packages/app-store/test/fixtures/catalog.golden.json @@ -0,0 +1,160 @@ +{ + "catalogVersion": 1, + "revision": "926185e4ee87043a6bcf8d31e70941e7", + "apps": [ + { + "apiVersion": 1, + "id": "fixture-connection", + "name": "Fixture Connection", + "version": "2.0.0", + "description": "A connection with settings, events and actions.", + "author": { + "name": "Fixture", + "github": "fixture" + }, + "firstParty": false, + "license": "Apache-2.0", + "categories": ["productivity"], + "keywords": [], + "privacyPolicy": "https://fixture.dev/privacy", + "icon": { + "url": "/app-store/fixture-connection/2c77fa2f6853700c29f9735324d65138.png", + "sha256": "2c77fa2f6853700c29f9735324d6513825a8d0af2f68f44d1ffd76ccdf35d2b9", + "bytes": 27, + "width": 512, + "height": 512 + }, + "screenshots": [], + "readme": "# Fixture Connection\n\nFixture app.", + "platforms": ["web", "desktop"], + "backgrounds": [], + "captionStyles": [], + "colorLooks": [], + "connection": { + "url": "https://fixture.dev/cap", + "permissions": ["cap.transcript"], + "events": ["cap.ready", "cap.transcript.ready"], + "settings": [ + { + "key": "token", + "label": "Token", + "required": true, + "type": "secret" + }, + { + "key": "mode", + "label": "Mode", + "type": "select", + "options": [ + { + "value": "all", + "label": "All" + } + ], + "default": "all" + }, + { + "key": "enabled", + "label": "Enabled", + "type": "toggle", + "default": true + } + ], + "actions": [ + { + "id": "send", + "title": "Send to Fixture", + "target": "cap" + } + ] + }, + "contentHash": "11322c83abab0ad550615f98fd33eab34ef000ab606622d0d830272e44a22154" + }, + { + "apiVersion": 1, + "id": "fixture-content", + "name": "Fixture Content", + "version": "1.2.3", + "description": "Every kind of content an app can add.", + "author": { + "name": "Fixture", + "github": "fixture" + }, + "firstParty": false, + "license": "MIT", + "categories": ["backgrounds", "captions", "color"], + "keywords": [], + "icon": { + "url": "/app-store/fixture-content/4a240b27b3a4d337236a812deba84d70.png", + "sha256": "4a240b27b3a4d337236a812deba84d709be1198527bfb256a609d7acab2a7ed1", + "bytes": 24, + "width": 512, + "height": 512 + }, + "screenshots": [], + "readme": "# Fixture Content\n\nFixture app.", + "platforms": ["desktop"], + "backgrounds": [ + { + "kind": "image", + "id": "photo", + "name": "Photo", + "image": { + "url": "/app-store/fixture-content/e76ae1b899c30659e91c4e13fa13d141.jpg", + "sha256": "e76ae1b899c30659e91c4e13fa13d141e6fb24f917d2490f276bbb4eff3c12c4", + "bytes": 37, + "width": 2560, + "height": 1440 + } + }, + { + "kind": "gradient", + "id": "sunset", + "name": "Sunset", + "from": "#FF7E5F", + "to": "#6A3093", + "angle": 135 + }, + { + "kind": "color", + "id": "ink", + "name": "Ink", + "color": "#111827" + } + ], + "captionStyles": [ + { + "id": "bold", + "name": "Bold", + "description": "Big and bold", + "fontWeight": 700, + "size": 64, + "color": "#FFFFFF", + "backgroundColor": "#000000", + "backgroundOpacity": 0, + "outline": true, + "outlineColor": "#000000", + "highlightColor": "#FFD43B", + "activeWordHighlight": true, + "highlightStyle": "pill", + "animation": "pop", + "uppercase": true, + "fadeDuration": 0.12 + } + ], + "colorLooks": [ + { + "id": "warm", + "name": "Warm", + "values": { + "temperature": 0.3, + "splitTone": -0.1, + "vignette": 0.2 + } + } + ], + "contentHash": "86ab657f98fac8d58f07d4302806796ddec85a48c4241bb977285cdf504fae78" + } + ], + "blocked": [] +} diff --git a/packages/app-store/tsconfig.json b/packages/app-store/tsconfig.json new file mode 100644 index 00000000000..f9b29b1b82e --- /dev/null +++ b/packages/app-store/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../config/base.tsconfig.json", + "exclude": ["node_modules", "dist"], + "include": ["src/**/*.ts", "test/**/*.ts"], + "compilerOptions": { + "moduleResolution": "bundler", + "composite": true, + "outDir": "dist", + "noEmit": false, + "emitDeclarationOnly": true, + "types": ["node"] + } +} diff --git a/packages/database/migrations/0062_app_store.sql b/packages/database/migrations/0062_app_store.sql new file mode 100644 index 00000000000..733128676bd --- /dev/null +++ b/packages/database/migrations/0062_app_store.sql @@ -0,0 +1,35 @@ +CREATE TABLE `app_store_events` ( + `id` varchar(64) NOT NULL, + `type` varchar(64) NOT NULL, + `videoId` varchar(15) NOT NULL, + `createdAt` timestamp NOT NULL DEFAULT (now()), + CONSTRAINT `app_store_events_id` PRIMARY KEY(`id`) +); +--> statement-breakpoint +CREATE TABLE `app_store_installations` ( + `id` varchar(15) NOT NULL, + `appId` varchar(64) NOT NULL, + `scope` varchar(16) NOT NULL, + `scopeKey` varchar(64) NOT NULL, + `userId` varchar(15), + `organizationId` varchar(15), + `installedByUserId` varchar(15) NOT NULL, + `appVersion` varchar(32) NOT NULL, + `grantedPermissions` json NOT NULL, + `grantedEvents` json NOT NULL, + `encryptedSettings` text, + `status` varchar(16) NOT NULL DEFAULT 'active', + `disabledReason` varchar(64), + `consecutiveFailures` int NOT NULL DEFAULT 0, + `failingSince` timestamp, + `lastDeliveryAt` timestamp, + `lastDeliveryStatus` varchar(32), + `createdAt` timestamp NOT NULL DEFAULT (now()), + `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP, + CONSTRAINT `app_store_installations_id` PRIMARY KEY(`id`), + CONSTRAINT `app_store_installations_app_scope_idx` UNIQUE(`appId`,`scopeKey`) +); +--> statement-breakpoint +CREATE INDEX `app_store_events_created_at_idx` ON `app_store_events` (`createdAt`);--> statement-breakpoint +CREATE INDEX `app_store_installations_user_idx` ON `app_store_installations` (`userId`);--> statement-breakpoint +CREATE INDEX `app_store_installations_organization_idx` ON `app_store_installations` (`organizationId`); \ No newline at end of file diff --git a/packages/database/migrations/meta/0062_snapshot.json b/packages/database/migrations/meta/0062_snapshot.json new file mode 100644 index 00000000000..4e9aa24e073 --- /dev/null +++ b/packages/database/migrations/meta/0062_snapshot.json @@ -0,0 +1,6557 @@ +{ + "version": "5", + "dialect": "mysql", + "id": "6c14a52c-de82-4ac9-86af-cffa1c6bd8aa", + "prevId": "45632039-82de-46d3-b9b4-96c0a5a6b756", + "tables": { + "accounts": { + "name": "accounts", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "providerAccountId": { + "name": "providerAccountId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_in": { + "name": "expires_in", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_in": { + "name": "refresh_token_expires_in", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_type": { + "name": "token_type", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "tempColumn": { + "name": "tempColumn", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + }, + "provider_account_id_idx": { + "name": "provider_account_id_idx", + "columns": ["providerAccountId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "accounts_id": { + "name": "accounts_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_authorization_codes": { + "name": "agent_api_authorization_codes", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeHash": { + "name": "codeHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeChallenge": { + "name": "codeChallenge", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirectUri": { + "name": "redirectUri", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scopes": { + "name": "scopes", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consumedAt": { + "name": "consumedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "code_hash_idx": { + "name": "code_hash_idx", + "columns": ["codeHash"], + "isUnique": true + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + }, + "user_created_at_idx": { + "name": "user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_authorization_codes_id": { + "name": "agent_api_authorization_codes_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_idempotency": { + "name": "agent_api_idempotency", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation": { + "name": "operation", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyHash": { + "name": "keyHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "requestHash": { + "name": "requestHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "statusCode": { + "name": "statusCode", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "response": { + "name": "response", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "user_operation_key_idx": { + "name": "user_operation_key_idx", + "columns": ["userId", "operation", "keyHash"], + "isUnique": true + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_idempotency_id": { + "name": "agent_api_idempotency_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_keys": { + "name": "agent_api_keys", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tokenHash": { + "name": "tokenHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Cap CLI'" + }, + "scopes": { + "name": "scopes", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "lastUsedAt": { + "name": "lastUsedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "token_hash_idx": { + "name": "token_hash_idx", + "columns": ["tokenHash"], + "isUnique": true + }, + "user_created_at_idx": { + "name": "user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_keys_id": { + "name": "agent_api_keys_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_operations": { + "name": "agent_api_operations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resourceId": { + "name": "resourceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resultResourceId": { + "name": "resultResourceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "payload": { + "name": "payload", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorCode": { + "name": "errorCode", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorMessage": { + "name": "errorMessage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "completedAt": { + "name": "completedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "user_created_at_idx": { + "name": "user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + }, + "state_updated_at_idx": { + "name": "state_updated_at_idx", + "columns": ["state", "updatedAt"], + "isUnique": false + }, + "resource_id_idx": { + "name": "resource_id_idx", + "columns": ["resourceId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_operations_id": { + "name": "agent_api_operations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "app_store_events": { + "name": "app_store_events", + "columns": { + "id": { + "name": "id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "app_store_events_created_at_idx": { + "name": "app_store_events_created_at_idx", + "columns": ["createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "app_store_events_id": { + "name": "app_store_events_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "app_store_installations": { + "name": "app_store_installations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scopeKey": { + "name": "scopeKey", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "installedByUserId": { + "name": "installedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appVersion": { + "name": "appVersion", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grantedPermissions": { + "name": "grantedPermissions", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grantedEvents": { + "name": "grantedEvents", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedSettings": { + "name": "encryptedSettings", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "disabledReason": { + "name": "disabledReason", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consecutiveFailures": { + "name": "consecutiveFailures", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "failingSince": { + "name": "failingSince", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastDeliveryAt": { + "name": "lastDeliveryAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastDeliveryStatus": { + "name": "lastDeliveryStatus", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "app_store_installations_app_scope_idx": { + "name": "app_store_installations_app_scope_idx", + "columns": ["appId", "scopeKey"], + "isUnique": true + }, + "app_store_installations_user_idx": { + "name": "app_store_installations_user_idx", + "columns": ["userId"], + "isUnique": false + }, + "app_store_installations_organization_idx": { + "name": "app_store_installations_organization_idx", + "columns": ["organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "app_store_installations_id": { + "name": "app_store_installations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "auth_api_keys": { + "name": "auth_api_keys", + "columns": { + "id": { + "name": "id", + "type": "varchar(36)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "user_id_created_at_idx": { + "name": "user_id_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "auth_api_keys_id": { + "name": "auth_api_keys_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "comments": { + "name": "comments", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "authorId": { + "name": "authorId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "parentCommentId": { + "name": "parentCommentId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mediaKey": { + "name": "mediaKey", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mediaDuration": { + "name": "mediaDuration", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mediaMeta": { + "name": "mediaMeta", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "video_type_created_idx": { + "name": "video_type_created_idx", + "columns": ["videoId", "type", "createdAt", "id"], + "isUnique": false + }, + "author_id_idx": { + "name": "author_id_idx", + "columns": ["authorId"], + "isUnique": false + }, + "parent_comment_id_idx": { + "name": "parent_comment_id_idx", + "columns": ["parentCommentId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "comments_id": { + "name": "comments_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_api_keys": { + "name": "developer_api_keys", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyType": { + "name": "keyType", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyPrefix": { + "name": "keyPrefix", + "type": "varchar(12)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyHash": { + "name": "keyHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedKey": { + "name": "encryptedKey", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lastUsedAt": { + "name": "lastUsedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "key_hash_idx": { + "name": "key_hash_idx", + "columns": ["keyHash"], + "isUnique": true + }, + "app_key_type_idx": { + "name": "app_key_type_idx", + "columns": ["appId", "keyType"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_api_keys_appId_developer_apps_id_fk": { + "name": "developer_api_keys_appId_developer_apps_id_fk", + "tableFrom": "developer_api_keys", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_api_keys_id": { + "name": "developer_api_keys_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_app_domains": { + "name": "developer_app_domains", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "domain": { + "name": "domain", + "type": "varchar(253)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": { + "developer_app_domains_appId_developer_apps_id_fk": { + "name": "developer_app_domains_appId_developer_apps_id_fk", + "tableFrom": "developer_app_domains", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_app_domains_id": { + "name": "developer_app_domains_id", + "columns": ["id"] + } + }, + "uniqueConstraints": { + "app_domain_unique": { + "name": "app_domain_unique", + "columns": ["appId", "domain"] + } + }, + "checkConstraint": {} + }, + "developer_apps": { + "name": "developer_apps", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logoUrl": { + "name": "logoUrl", + "type": "varchar(1024)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "owner_deleted_idx": { + "name": "owner_deleted_idx", + "columns": ["ownerId", "deletedAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "developer_apps_id": { + "name": "developer_apps_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_credit_accounts": { + "name": "developer_credit_accounts", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "balanceMicroCredits": { + "name": "balanceMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "stripeCustomerId": { + "name": "stripeCustomerId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripePaymentMethodId": { + "name": "stripePaymentMethodId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "autoTopUpEnabled": { + "name": "autoTopUpEnabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "autoTopUpThresholdMicroCredits": { + "name": "autoTopUpThresholdMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "autoTopUpAmountCents": { + "name": "autoTopUpAmountCents", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "app_id_unique": { + "name": "app_id_unique", + "columns": ["appId"], + "isUnique": true + }, + "owner_idx": { + "name": "owner_idx", + "columns": ["ownerId"], + "isUnique": false + }, + "auto_top_up_idx": { + "name": "auto_top_up_idx", + "columns": ["autoTopUpEnabled"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_credit_accounts_appId_developer_apps_id_fk": { + "name": "developer_credit_accounts_appId_developer_apps_id_fk", + "tableFrom": "developer_credit_accounts", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_credit_accounts_id": { + "name": "developer_credit_accounts_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_credit_transactions": { + "name": "developer_credit_transactions", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accountId": { + "name": "accountId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "amountMicroCredits": { + "name": "amountMicroCredits", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "balanceAfterMicroCredits": { + "name": "balanceAfterMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "referenceId": { + "name": "referenceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "referenceType": { + "name": "referenceType", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "account_type_created_idx": { + "name": "account_type_created_idx", + "columns": ["accountId", "type", "createdAt"], + "isUnique": false + }, + "account_created_idx": { + "name": "account_created_idx", + "columns": ["accountId", "createdAt"], + "isUnique": false + }, + "account_ref_dedup_idx": { + "name": "account_ref_dedup_idx", + "columns": ["accountId", "referenceId", "referenceType"], + "isUnique": false + }, + "reference_type_id_idx": { + "name": "reference_type_id_idx", + "columns": ["referenceType", "referenceId"], + "isUnique": false + } + }, + "foreignKeys": { + "dev_credit_txn_account_fk": { + "name": "dev_credit_txn_account_fk", + "tableFrom": "developer_credit_transactions", + "tableTo": "developer_credit_accounts", + "columnsFrom": ["accountId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_credit_transactions_id": { + "name": "developer_credit_transactions_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_daily_storage_snapshots": { + "name": "developer_daily_storage_snapshots", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snapshotDate": { + "name": "snapshotDate", + "type": "varchar(10)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "totalDurationMinutes": { + "name": "totalDurationMinutes", + "type": "float", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "videoCount": { + "name": "videoCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "microCreditsCharged": { + "name": "microCreditsCharged", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "processedAt": { + "name": "processedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": { + "developer_daily_storage_snapshots_appId_developer_apps_id_fk": { + "name": "developer_daily_storage_snapshots_appId_developer_apps_id_fk", + "tableFrom": "developer_daily_storage_snapshots", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_daily_storage_snapshots_id": { + "name": "developer_daily_storage_snapshots_id", + "columns": ["id"] + } + }, + "uniqueConstraints": { + "app_date_unique": { + "name": "app_date_unique", + "columns": ["appId", "snapshotDate"] + } + }, + "checkConstraint": {} + }, + "developer_delivery_daily": { + "name": "developer_delivery_daily", + "columns": { + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tier": { + "name": "tier", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seconds": { + "name": "seconds", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "bytes": { + "name": "bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "requests": { + "name": "requests", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "abandonedBytes": { + "name": "abandonedBytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "final": { + "name": "final", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "finalizedAt": { + "name": "finalizedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "day_idx": { + "name": "day_idx", + "columns": ["day"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_delivery_daily_appId_developer_apps_id_fk": { + "name": "developer_delivery_daily_appId_developer_apps_id_fk", + "tableFrom": "developer_delivery_daily", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_delivery_daily_appId_day_tier_pk": { + "name": "developer_delivery_daily_appId_day_tier_pk", + "columns": ["appId", "day", "tier"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_delivery_log_files": { + "name": "developer_delivery_log_files", + "columns": { + "logFile": { + "name": "logFile", + "type": "varchar(191)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "etag": { + "name": "etag", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logHour": { + "name": "logHour", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parts": { + "name": "parts", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "processedAt": { + "name": "processedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "log_hour_idx": { + "name": "log_hour_idx", + "columns": ["logHour"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "developer_delivery_log_files_logFile": { + "name": "developer_delivery_log_files_logFile", + "columns": ["logFile"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_transcripts": { + "name": "developer_transcripts", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "externalUserId": { + "name": "externalUserId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Untitled'" + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceType": { + "name": "sourceType", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceUrl": { + "name": "sourceUrl", + "type": "varchar(2048)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requestedAt": { + "name": "requestedAt", + "type": "timestamp(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "s3Key": { + "name": "s3Key", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resultKey": { + "name": "resultKey", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sourceBytes": { + "name": "sourceBytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "durationSeconds": { + "name": "durationSeconds", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requestedLanguage": { + "name": "requestedLanguage", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "mediumtext", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wordCount": { + "name": "wordCount", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reservedMicroCredits": { + "name": "reservedMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "billedMicroCredits": { + "name": "billedMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "errorCode": { + "name": "errorCode", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorMessage": { + "name": "errorMessage", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "runId": { + "name": "runId", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "queuedAt": { + "name": "queuedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "startedAt": { + "name": "startedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completedAt": { + "name": "completedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "dev_transcripts_app_list_idx": { + "name": "dev_transcripts_app_list_idx", + "columns": ["appId", "deletedAt", "createdAt", "id"], + "isUnique": false + }, + "dev_transcripts_app_user_idx": { + "name": "dev_transcripts_app_user_idx", + "columns": ["appId", "externalUserId", "createdAt"], + "isUnique": false + }, + "dev_transcripts_app_status_idx": { + "name": "dev_transcripts_app_status_idx", + "columns": ["appId", "status", "createdAt"], + "isUnique": false + }, + "dev_transcripts_status_updated_idx": { + "name": "dev_transcripts_status_updated_idx", + "columns": ["status", "updatedAt"], + "isUnique": false + }, + "dev_transcripts_app_completed_idx": { + "name": "dev_transcripts_app_completed_idx", + "columns": [ + "appId", + "status", + "completedAt", + "durationSeconds", + "billedMicroCredits" + ], + "isUnique": false + }, + "dev_transcripts_app_status_held_idx": { + "name": "dev_transcripts_app_status_held_idx", + "columns": [ + "appId", + "status", + "createdAt", + "deletedAt", + "reservedMicroCredits" + ], + "isUnique": false + }, + "dev_transcripts_app_video_idx": { + "name": "dev_transcripts_app_video_idx", + "columns": ["appId", "videoId", "requestedAt", "id"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_transcripts_appId_developer_apps_id_fk": { + "name": "developer_transcripts_appId_developer_apps_id_fk", + "tableFrom": "developer_transcripts", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_transcripts_id": { + "name": "developer_transcripts_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_video_imports": { + "name": "developer_video_imports", + "columns": { + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyId": { + "name": "keyId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceUrl": { + "name": "sourceUrl", + "type": "varchar(2048)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'downloading'" + }, + "bytes": { + "name": "bytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorCode": { + "name": "errorCode", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "startedAt": { + "name": "startedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "finishedAt": { + "name": "finishedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "dev_imports_app_state_idx": { + "name": "dev_imports_app_state_idx", + "columns": ["appId", "state"], + "isUnique": false + }, + "dev_imports_key_created_idx": { + "name": "dev_imports_key_created_idx", + "columns": ["keyId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_video_imports_appId_developer_apps_id_fk": { + "name": "developer_video_imports_appId_developer_apps_id_fk", + "tableFrom": "developer_video_imports", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_video_imports_videoId": { + "name": "developer_video_imports_videoId", + "columns": ["videoId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_videos": { + "name": "developer_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "externalUserId": { + "name": "externalUserId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Untitled'" + }, + "duration": { + "name": "duration", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "width": { + "name": "width", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "height": { + "name": "height", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fps": { + "name": "fps", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "s3Key": { + "name": "s3Key", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcriptionStatus": { + "name": "transcriptionStatus", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'uploading'" + }, + "playbackId": { + "name": "playbackId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "maxResolutionTier": { + "name": "maxResolutionTier", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'1080p'" + }, + "renditions": { + "name": "renditions", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storedBytes": { + "name": "storedBytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorReason": { + "name": "errorReason", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "processing": { + "name": "processing", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storagePaidUntil": { + "name": "storagePaidUntil", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "filesDeletedAt": { + "name": "filesDeletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "app_created_idx": { + "name": "app_created_idx", + "columns": ["appId", "createdAt"], + "isUnique": false + }, + "app_user_idx": { + "name": "app_user_idx", + "columns": ["appId", "externalUserId"], + "isUnique": false + }, + "app_deleted_idx": { + "name": "app_deleted_idx", + "columns": ["appId", "deletedAt"], + "isUnique": false + }, + "playback_id_idx": { + "name": "playback_id_idx", + "columns": ["playbackId"], + "isUnique": true + }, + "files_pending_idx": { + "name": "files_pending_idx", + "columns": ["filesDeletedAt", "deletedAt"], + "isUnique": false + }, + "app_storage_idx": { + "name": "app_storage_idx", + "columns": [ + "appId", + "deletedAt", + "status", + "maxResolutionTier", + "width", + "height", + "storagePaidUntil", + "duration", + "createdAt" + ], + "isUnique": false + }, + "first_month_due_idx": { + "name": "first_month_due_idx", + "columns": ["storagePaidUntil", "status", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_videos_appId_developer_apps_id_fk": { + "name": "developer_videos_appId_developer_apps_id_fk", + "tableFrom": "developer_videos", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_videos_id": { + "name": "developer_videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_webhook_endpoints": { + "name": "developer_webhook_endpoints", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "varchar(2048)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secretPrefix": { + "name": "secretPrefix", + "type": "varchar(12)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedSecret": { + "name": "encryptedSecret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "disabledReason": { + "name": "disabledReason", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastDeliveryAt": { + "name": "lastDeliveryAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastDeliveryStatus": { + "name": "lastDeliveryStatus", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastResponseStatus": { + "name": "lastResponseStatus", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastErrorCode": { + "name": "lastErrorCode", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consecutiveFailures": { + "name": "consecutiveFailures", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "failingSince": { + "name": "failingSince", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "dev_webhooks_app_list_idx": { + "name": "dev_webhooks_app_list_idx", + "columns": ["appId", "deletedAt", "createdAt", "id"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_webhook_endpoints_appId_developer_apps_id_fk": { + "name": "developer_webhook_endpoints_appId_developer_apps_id_fk", + "tableFrom": "developer_webhook_endpoints", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_webhook_endpoints_id": { + "name": "developer_webhook_endpoints_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "directory_users": { + "name": "directory_users", + "columns": { + "id": { + "name": "id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "directoryId": { + "name": "directoryId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "directory_users_organization_id_idx": { + "name": "directory_users_organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "directory_users_user_org_idx": { + "name": "directory_users_user_org_idx", + "columns": ["userId", "organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "directory_users_id": { + "name": "directory_users_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "folders": { + "name": "folders", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdById": { + "name": "createdById", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parentId": { + "name": "parentId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "spaceId": { + "name": "spaceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "created_by_id_idx": { + "name": "created_by_id_idx", + "columns": ["createdById"], + "isUnique": false + }, + "parent_id_idx": { + "name": "parent_id_idx", + "columns": ["parentId"], + "isUnique": false + }, + "space_id_idx": { + "name": "space_id_idx", + "columns": ["spaceId"], + "isUnique": false + }, + "public_parent_id_idx": { + "name": "public_parent_id_idx", + "columns": ["public", "parentId"], + "isUnique": false + }, + "public_space_parent_id_idx": { + "name": "public_space_parent_id_idx", + "columns": ["public", "spaceId", "parentId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "folders_id": { + "name": "folders_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "imported_videos": { + "name": "imported_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "orgId": { + "name": "orgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "id_idx": { + "name": "id_idx", + "columns": ["id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "imported_videos_orgId_source_source_id_pk": { + "name": "imported_videos_orgId_source_source_id_pk", + "columns": ["orgId", "source", "source_id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "integration_installations": { + "name": "integration_installations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "externalId": { + "name": "externalId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "displayName": { + "name": "displayName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installedByUserId": { + "name": "installedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedCredentials": { + "name": "encryptedCredentials", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "provider_external_id_idx": { + "name": "provider_external_id_idx", + "columns": ["provider", "externalId"], + "isUnique": true + }, + "organization_provider_display_name_idx": { + "name": "organization_provider_display_name_idx", + "columns": ["organizationId", "provider", "displayName"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "integration_installations_id": { + "name": "integration_installations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "loom_migration_imports": { + "name": "loom_migration_imports", + "columns": { + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "requestId": { + "name": "requestId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "loom_migration_imports_request_idx": { + "name": "loom_migration_imports_request_idx", + "columns": ["requestId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "loom_migration_imports_videoId": { + "name": "loom_migration_imports_videoId", + "columns": ["videoId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "loom_migration_requests": { + "name": "loom_migration_requests", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activeOrganizationId": { + "name": "activeOrganizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requestedByUserId": { + "name": "requestedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workspaceName": { + "name": "workspaceName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customerNote": { + "name": "customerNote", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customerReply": { + "name": "customerReply", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "invitedAt": { + "name": "invitedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "capMessage": { + "name": "capMessage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expectedVideoCount": { + "name": "expectedVideoCount", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "importedVideoCount": { + "name": "importedVideoCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "queuedVideoCount": { + "name": "queuedVideoCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "activeImportCount": { + "name": "activeImportCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "activeImportLeaseToken": { + "name": "activeImportLeaseToken", + "type": "varchar(36)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activeImportLeaseUntil": { + "name": "activeImportLeaseUntil", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastOperatorUserId": { + "name": "lastOperatorUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastOperatorAt": { + "name": "lastOperatorAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completedAt": { + "name": "completedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updatedAt": { + "name": "updatedAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "loom_migration_active_org_idx": { + "name": "loom_migration_active_org_idx", + "columns": ["activeOrganizationId"], + "isUnique": true + }, + "loom_migration_org_created_idx": { + "name": "loom_migration_org_created_idx", + "columns": ["organizationId", "createdAt"], + "isUnique": false + }, + "loom_migration_status_created_idx": { + "name": "loom_migration_status_created_idx", + "columns": ["status", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "loom_migration_requests_id": { + "name": "loom_migration_requests_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "loops_sync_jobs": { + "name": "loops_sync_jobs", + "columns": { + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision": { + "name": "revision", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "nextAttemptAt": { + "name": "nextAttemptAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "leaseToken": { + "name": "leaseToken", + "type": "varchar(36)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "leaseUntil": { + "name": "leaseUntil", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "failures": { + "name": "failures", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "lastError": { + "name": "lastError", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "profileHash": { + "name": "profileHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "teammateJoinedAt": { + "name": "teammateJoinedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "syncedEmail": { + "name": "syncedEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastSyncedAt": { + "name": "lastSyncedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "loops_sync_due_idx": { + "name": "loops_sync_due_idx", + "columns": ["nextAttemptAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "loops_sync_jobs_userId": { + "name": "loops_sync_jobs_userId", + "columns": ["userId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_clients": { + "name": "mcp_oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientId": { + "name": "clientId", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientName": { + "name": "clientName", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirectUris": { + "name": "redirectUris", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activatedAt": { + "name": "activatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "client_id_idx": { + "name": "client_id_idx", + "columns": ["clientId"], + "isUnique": true + }, + "inactive_created_at_idx": { + "name": "inactive_created_at_idx", + "columns": ["activatedAt", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_clients_id": { + "name": "mcp_oauth_clients_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_codes": { + "name": "mcp_oauth_codes", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientId": { + "name": "clientId", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeHash": { + "name": "codeHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeChallenge": { + "name": "codeChallenge", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirectUri": { + "name": "redirectUri", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consumedAt": { + "name": "consumedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "code_hash_idx": { + "name": "code_hash_idx", + "columns": ["codeHash"], + "isUnique": true + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_codes_id": { + "name": "mcp_oauth_codes_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_registration_quotas": { + "name": "mcp_oauth_registration_quotas", + "columns": { + "windowId": { + "name": "windowId", + "type": "varchar(10)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "registrations": { + "name": "registrations", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_registration_quotas_windowId": { + "name": "mcp_oauth_registration_quotas_windowId", + "columns": ["windowId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_tokens": { + "name": "mcp_oauth_tokens", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientId": { + "name": "clientId", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "familyId": { + "name": "familyId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accessHash": { + "name": "accessHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refreshHash": { + "name": "refreshHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accessExpiresAt": { + "name": "accessExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refreshExpiresAt": { + "name": "refreshExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "access_hash_idx": { + "name": "access_hash_idx", + "columns": ["accessHash"], + "isUnique": true + }, + "refresh_hash_idx": { + "name": "refresh_hash_idx", + "columns": ["refreshHash"], + "isUnique": true + }, + "family_id_idx": { + "name": "family_id_idx", + "columns": ["familyId"], + "isUnique": false + }, + "client_active_idx": { + "name": "client_active_idx", + "columns": ["clientId", "revokedAt", "refreshExpiresAt"], + "isUnique": false + }, + "refresh_expires_at_idx": { + "name": "refresh_expires_at_idx", + "columns": ["refreshExpiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_tokens_id": { + "name": "mcp_oauth_tokens_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "media_processing_budgets": { + "name": "media_processing_budgets", + "columns": { + "id": { + "name": "id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reserved_bytes": { + "name": "reserved_bytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_bytes": { + "name": "limit_bytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "media_budget_expiry_idx": { + "name": "media_budget_expiry_idx", + "columns": ["expires_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "media_processing_budgets_id": { + "name": "media_processing_budgets_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "messenger_conversations": { + "name": "messenger_conversations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent": { + "name": "agent", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mode": { + "name": "mode", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'agent'" + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "anonymousId": { + "name": "anonymousId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "takeoverByUserId": { + "name": "takeoverByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "takeoverAt": { + "name": "takeoverAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "lastMessageAt": { + "name": "lastMessageAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "user_last_message_idx": { + "name": "user_last_message_idx", + "columns": ["userId", "lastMessageAt"], + "isUnique": false + }, + "anonymous_last_message_idx": { + "name": "anonymous_last_message_idx", + "columns": ["anonymousId", "lastMessageAt"], + "isUnique": false + }, + "mode_last_message_idx": { + "name": "mode_last_message_idx", + "columns": ["mode", "lastMessageAt"], + "isUnique": false + }, + "updated_at_idx": { + "name": "updated_at_idx", + "columns": ["updatedAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "messenger_conversations_id": { + "name": "messenger_conversations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "messenger_messages": { + "name": "messenger_messages", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversationId": { + "name": "conversationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "anonymousId": { + "name": "anonymousId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "conversation_created_at_idx": { + "name": "conversation_created_at_idx", + "columns": ["conversationId", "createdAt"], + "isUnique": false + }, + "role_created_at_idx": { + "name": "role_created_at_idx", + "columns": ["role", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "messenger_messages_conversationId_messenger_conversations_id_fk": { + "name": "messenger_messages_conversationId_messenger_conversations_id_fk", + "tableFrom": "messenger_messages", + "tableTo": "messenger_conversations", + "columnsFrom": ["conversationId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "messenger_messages_id": { + "name": "messenger_messages_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "messenger_support_emails": { + "name": "messenger_support_emails", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversationId": { + "name": "conversationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userEmail": { + "name": "userEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject": { + "name": "subject", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "support_email_user_created_at_idx": { + "name": "support_email_user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + }, + "support_email_conversation_created_at_idx": { + "name": "support_email_conversation_created_at_idx", + "columns": ["conversationId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "support_email_conversation_fk": { + "name": "support_email_conversation_fk", + "tableFrom": "messenger_support_emails", + "tableTo": "messenger_conversations", + "columnsFrom": ["conversationId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "messenger_support_emails_id": { + "name": "messenger_support_emails_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mobile_push_claims": { + "name": "mobile_push_claims", + "columns": { + "id": { + "name": "id", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "created_at_idx": { + "name": "created_at_idx", + "columns": ["createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mobile_push_claims_id": { + "name": "mobile_push_claims_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mobile_push_tokens": { + "name": "mobile_push_tokens", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sessionHash": { + "name": "sessionHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "varchar(10)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "token_idx": { + "name": "token_idx", + "columns": ["token"], + "isUnique": true + }, + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + }, + "session_hash_idx": { + "name": "session_hash_idx", + "columns": ["sessionHash"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mobile_push_tokens_id": { + "name": "mobile_push_tokens_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "notifications": { + "name": "notifications", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "orgId": { + "name": "orgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recipientId": { + "name": "recipientId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "data": { + "name": "data", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupKey": { + "name": "dedupKey", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "readAt": { + "name": "readAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "org_id_idx": { + "name": "org_id_idx", + "columns": ["orgId"], + "isUnique": false + }, + "type_idx": { + "name": "type_idx", + "columns": ["type"], + "isUnique": false + }, + "read_at_idx": { + "name": "read_at_idx", + "columns": ["readAt"], + "isUnique": false + }, + "created_at_idx": { + "name": "created_at_idx", + "columns": ["createdAt"], + "isUnique": false + }, + "recipient_read_idx": { + "name": "recipient_read_idx", + "columns": ["recipientId", "readAt"], + "isUnique": false + }, + "recipient_created_idx": { + "name": "recipient_created_idx", + "columns": ["recipientId", "createdAt"], + "isUnique": false + }, + "dedup_key_idx": { + "name": "dedup_key_idx", + "columns": ["dedupKey"], + "isUnique": true + }, + "type_recipient_created_idx": { + "name": "type_recipient_created_idx", + "columns": ["type", "recipientId", "createdAt"], + "isUnique": false + }, + "type_recipient_video_created_idx": { + "name": "type_recipient_video_created_idx", + "columns": ["type", "recipientId", "videoId", "createdAt"], + "isUnique": false + }, + "video_id_idx": { + "name": "video_id_idx", + "columns": ["videoId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "notifications_id": { + "name": "notifications_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_directory_sync": { + "name": "organization_directory_sync", + "columns": { + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "requestedAt": { + "name": "requestedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "syncedAt": { + "name": "syncedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "leaseExpiresAt": { + "name": "leaseExpiresAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastError": { + "name": "lastError", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "heldRemovals": { + "name": "heldRemovals", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "removalsApprovedAt": { + "name": "removalsApprovedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_directory_sync_organizationId": { + "name": "organization_directory_sync_organizationId", + "columns": ["organizationId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_invites": { + "name": "organization_invites", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invitedEmail": { + "name": "invitedEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invitedByUserId": { + "name": "invitedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "invited_email_idx": { + "name": "invited_email_idx", + "columns": ["invitedEmail"], + "isUnique": false + }, + "invited_by_user_id_idx": { + "name": "invited_by_user_id_idx", + "columns": ["invitedByUserId"], + "isUnique": false + }, + "status_idx": { + "name": "status_idx", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_invites_id": { + "name": "organization_invites_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_members": { + "name": "organization_members", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hasProSeat": { + "name": "hasProSeat", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "user_id_organization_id_idx": { + "name": "user_id_organization_id_idx", + "columns": ["userId", "organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_members_id": { + "name": "organization_members_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_sso": { + "name": "organization_sso", + "columns": { + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purchasedByUserId": { + "name": "purchasedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripeCustomerId": { + "name": "stripeCustomerId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionId": { + "name": "stripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripePriceId": { + "name": "stripePriceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unpaid'" + }, + "paidThrough": { + "name": "paidThrough", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "currentPeriodEnd": { + "name": "currentPeriodEnd", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancelAtPeriodEnd": { + "name": "cancelAtPeriodEnd", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "checkoutAttemptId": { + "name": "checkoutAttemptId", + "type": "varchar(36)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutCurrency": { + "name": "checkoutCurrency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutPriceId": { + "name": "checkoutPriceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutSessionId": { + "name": "checkoutSessionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutStartedAt": { + "name": "checkoutStartedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "sso_stripe_subscription_id_idx": { + "name": "sso_stripe_subscription_id_idx", + "columns": ["stripeSubscriptionId"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_sso_organizationId": { + "name": "organization_sso_organizationId", + "columns": ["organizationId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organizations": { + "name": "organizations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tombstoneAt": { + "name": "tombstoneAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "allowedEmailDomain": { + "name": "allowedEmailDomain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "defaultVideoVisibility": { + "name": "defaultVideoVisibility", + "type": "varchar(7)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customDomain": { + "name": "customDomain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "domainVerified": { + "name": "domainVerified", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "iconUrl": { + "name": "iconUrl", + "type": "varchar(1024)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "shareableLinkIconUrl": { + "name": "shareableLinkIconUrl", + "type": "varchar(1024)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "workosOrganizationId": { + "name": "workosOrganizationId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workosConnectionId": { + "name": "workosConnectionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "owner_id_tombstone_idx": { + "name": "owner_id_tombstone_idx", + "columns": ["ownerId", "tombstoneAt"], + "isUnique": false + }, + "custom_domain_idx": { + "name": "custom_domain_idx", + "columns": ["customDomain"], + "isUnique": false + }, + "workos_organization_id_idx": { + "name": "workos_organization_id_idx", + "columns": ["workosOrganizationId"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organizations_id": { + "name": "organizations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "s3_buckets": { + "name": "s3_buckets", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "region": { + "name": "region", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bucketName": { + "name": "bucketName", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accessKeyId": { + "name": "accessKeyId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secretAccessKey": { + "name": "secretAccessKey", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('aws')" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "owner_organization_idx": { + "name": "owner_organization_idx", + "columns": ["ownerId", "organizationId"], + "isUnique": false + }, + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "organization_active_idx": { + "name": "organization_active_idx", + "columns": ["organizationId", "active", "updatedAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "s3_buckets_id": { + "name": "s3_buckets_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sessionToken": { + "name": "sessionToken", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires": { + "name": "expires", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "session_token_idx": { + "name": "session_token_idx", + "columns": ["sessionToken"], + "isUnique": true + }, + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "sessions_id": { + "name": "sessions_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "shared_videos": { + "name": "shared_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "folderId": { + "name": "folderId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sharedByUserId": { + "name": "sharedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sharedAt": { + "name": "sharedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "folder_id_idx": { + "name": "folder_id_idx", + "columns": ["folderId"], + "isUnique": false + }, + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "shared_by_user_id_idx": { + "name": "shared_by_user_id_idx", + "columns": ["sharedByUserId"], + "isUnique": false + }, + "video_id_organization_id_idx": { + "name": "video_id_organization_id_idx", + "columns": ["videoId", "organizationId"], + "isUnique": false + }, + "video_id_folder_id_idx": { + "name": "video_id_folder_id_idx", + "columns": ["videoId", "folderId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "shared_videos_id": { + "name": "shared_videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "signed_baas": { + "name": "signed_baas", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "stripeSubscriptionId": { + "name": "stripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "entityName": { + "name": "entityName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entityType": { + "name": "entityType", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entityAddress": { + "name": "entityAddress", + "type": "varchar(500)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signerName": { + "name": "signerName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signerTitle": { + "name": "signerTitle", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "noticesEmail": { + "name": "noticesEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signatureData": { + "name": "signatureData", + "type": "longtext", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signedAt": { + "name": "signedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "emailSentAt": { + "name": "emailSentAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "signed_baa_organization_id_idx": { + "name": "signed_baa_organization_id_idx", + "columns": ["organizationId"], + "isUnique": true + }, + "signed_baa_stripe_subscription_idx": { + "name": "signed_baa_stripe_subscription_idx", + "columns": ["stripeSubscriptionId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "signed_baas_id": { + "name": "signed_baas_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "space_members": { + "name": "space_members", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "spaceId": { + "name": "spaceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'member'" + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "space_members_id": { + "name": "space_members_id", + "columns": ["id"] + } + }, + "uniqueConstraints": { + "space_id_user_id_unique": { + "name": "space_id_user_id_unique", + "columns": ["spaceId", "userId"] + } + }, + "checkConstraint": {} + }, + "space_videos": { + "name": "space_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "spaceId": { + "name": "spaceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "folderId": { + "name": "folderId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "addedById": { + "name": "addedById", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "addedAt": { + "name": "addedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "folder_id_idx": { + "name": "folder_id_idx", + "columns": ["folderId"], + "isUnique": false + }, + "video_id_idx": { + "name": "video_id_idx", + "columns": ["videoId"], + "isUnique": false + }, + "added_by_id_idx": { + "name": "added_by_id_idx", + "columns": ["addedById"], + "isUnique": false + }, + "space_id_video_id_idx": { + "name": "space_id_video_id_idx", + "columns": ["spaceId", "videoId"], + "isUnique": false + }, + "space_id_folder_id_idx": { + "name": "space_id_folder_id_idx", + "columns": ["spaceId", "folderId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "space_videos_id": { + "name": "space_videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "spaces": { + "name": "spaces", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "primary": { + "name": "primary", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdById": { + "name": "createdById", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "iconUrl": { + "name": "iconUrl", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "varchar(1000)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "privacy": { + "name": "privacy", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Private'" + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "created_by_id_idx": { + "name": "created_by_id_idx", + "columns": ["createdById"], + "isUnique": false + }, + "public_organization_id_idx": { + "name": "public_organization_id_idx", + "columns": ["public", "organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "spaces_id": { + "name": "spaces_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "storage_integrations": { + "name": "storage_integrations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "displayName": { + "name": "displayName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "encryptedConfig": { + "name": "encryptedConfig", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "googleDriveAccessToken": { + "name": "googleDriveAccessToken", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveAccessTokenExpiresAt": { + "name": "googleDriveAccessTokenExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveTokenRefreshLeaseId": { + "name": "googleDriveTokenRefreshLeaseId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveTokenRefreshLeaseExpiresAt": { + "name": "googleDriveTokenRefreshLeaseExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveStorageQuotaCache": { + "name": "googleDriveStorageQuotaCache", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "owner_provider_idx": { + "name": "owner_provider_idx", + "columns": ["ownerId", "provider"], + "isUnique": false + }, + "owner_active_idx": { + "name": "owner_active_idx", + "columns": ["ownerId", "active"], + "isUnique": false + }, + "organization_provider_idx": { + "name": "organization_provider_idx", + "columns": ["organizationId", "provider"], + "isUnique": false + }, + "organization_active_idx": { + "name": "organization_active_idx", + "columns": ["organizationId", "active", "status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "storage_integrations_id": { + "name": "storage_integrations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "storage_objects": { + "name": "storage_objects", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "integrationId": { + "name": "integrationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "objectKey": { + "name": "objectKey", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "objectKeyHash": { + "name": "objectKeyHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "providerObjectId": { + "name": "providerObjectId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "uploadSessionUrl": { + "name": "uploadSessionUrl", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "uploadStatus": { + "name": "uploadStatus", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "contentType": { + "name": "contentType", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "contentLength": { + "name": "contentLength", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "integration_key_hash_idx": { + "name": "integration_key_hash_idx", + "columns": ["integrationId", "objectKeyHash"], + "isUnique": true + }, + "integration_status_idx": { + "name": "integration_status_idx", + "columns": ["integrationId", "uploadStatus"], + "isUnique": false + }, + "integration_object_key_prefix_idx": { + "name": "integration_object_key_prefix_idx", + "columns": ["integrationId", "`objectKey`(191)"], + "isUnique": false + }, + "video_id_idx": { + "name": "video_id_idx", + "columns": ["videoId"], + "isUnique": false + }, + "owner_id_idx": { + "name": "owner_id_idx", + "columns": ["ownerId"], + "isUnique": false + } + }, + "foreignKeys": { + "storage_objects_integrationId_storage_integrations_id_fk": { + "name": "storage_objects_integrationId_storage_integrations_id_fk", + "tableFrom": "storage_objects", + "tableTo": "storage_integrations", + "columnsFrom": ["integrationId"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "storage_objects_id": { + "name": "storage_objects_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastName": { + "name": "lastName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "emailVerified": { + "name": "emailVerified", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeCustomerId": { + "name": "stripeCustomerId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionId": { + "name": "stripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thirdPartyStripeSubscriptionId": { + "name": "thirdPartyStripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionStatus": { + "name": "stripeSubscriptionStatus", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionPriceId": { + "name": "stripeSubscriptionPriceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "preferences": { + "name": "preferences", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "('null')" + }, + "activeOrganizationId": { + "name": "activeOrganizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "onboardingSteps": { + "name": "onboardingSteps", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "onboarding_completed_at": { + "name": "onboarding_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customBucket": { + "name": "customBucket", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "inviteQuota": { + "name": "inviteQuota", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "defaultOrgId": { + "name": "defaultOrgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "authSessionVersion": { + "name": "authSessionVersion", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "marketingOrigin": { + "name": "marketingOrigin", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + } + }, + "indexes": { + "email_idx": { + "name": "email_idx", + "columns": ["email"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "users_id": { + "name": "users_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "verification_tokens": { + "name": "verification_tokens", + "columns": { + "identifier": { + "name": "identifier", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires": { + "name": "expires", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "verification_tokens_identifier": { + "name": "verification_tokens_identifier", + "columns": ["identifier"] + } + }, + "uniqueConstraints": { + "verification_tokens_token_unique": { + "name": "verification_tokens_token_unique", + "columns": ["token"] + } + }, + "checkConstraint": {} + }, + "video_edits": { + "name": "video_edits", + "columns": { + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceKey": { + "name": "sourceKey", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "editSpec": { + "name": "editSpec", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": { + "video_edits_videoId_videos_id_fk": { + "name": "video_edits_videoId_videos_id_fk", + "tableFrom": "video_edits", + "tableTo": "videos", + "columnsFrom": ["videoId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "video_edits_videoId": { + "name": "video_edits_videoId", + "columns": ["videoId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "video_processing_jobs": { + "name": "video_processing_jobs", + "columns": { + "video_id": { + "name": "video_id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_sha256": { + "name": "manifest_sha256", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'committing'" + }, + "attempt_id": { + "name": "attempt_id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workflow_run_id": { + "name": "workflow_run_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remote_job_id": { + "name": "remote_job_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verification": { + "name": "verification", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output": { + "name": "output", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "processing_state_retry_video_idx": { + "name": "processing_state_retry_video_idx", + "columns": ["state", "next_retry_at", "video_id"], + "isUnique": false + }, + "processing_state_lease_video_idx": { + "name": "processing_state_lease_video_idx", + "columns": ["state", "lease_expires_at", "video_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "video_processing_jobs_video_id": { + "name": "video_processing_jobs_video_id", + "columns": ["video_id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "video_uploads": { + "name": "video_uploads", + "columns": { + "video_id": { + "name": "video_id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "uploaded": { + "name": "uploaded", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "mode": { + "name": "mode", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phase": { + "name": "phase", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'uploading'" + }, + "processing_progress": { + "name": "processing_progress", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "processing_message": { + "name": "processing_message", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "processing_error": { + "name": "processing_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_file_key": { + "name": "raw_file_key", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "phase_updated_at_video_id_idx": { + "name": "phase_updated_at_video_id_idx", + "columns": ["phase", "updated_at", "video_id"], + "isUnique": false + }, + "started_at_idx": { + "name": "started_at_idx", + "columns": ["started_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "video_uploads_video_id": { + "name": "video_uploads_video_id", + "columns": ["video_id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "video_viewer_grants": { + "name": "video_viewer_grants", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invitedByUserId": { + "name": "invitedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "video_email_idx": { + "name": "video_email_idx", + "columns": ["videoId", "email"], + "isUnique": true + } + }, + "foreignKeys": { + "video_viewer_grants_videoId_videos_id_fk": { + "name": "video_viewer_grants_videoId_videos_id_fk", + "tableFrom": "video_viewer_grants", + "tableTo": "videos", + "columnsFrom": ["videoId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "video_viewer_grants_id": { + "name": "video_viewer_grants_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "videos": { + "name": "videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "orgId": { + "name": "orgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'My Video'" + }, + "bucket": { + "name": "bucket", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storageIntegrationId": { + "name": "storageIntegrationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration": { + "name": "duration", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "width": { + "name": "width", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "height": { + "name": "height", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fps": { + "name": "fps", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcriptionStatus": { + "name": "transcriptionStatus", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('{\"type\":\"MediaConvert\"}')" + }, + "folderId": { + "name": "folderId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "effectiveCreatedAt": { + "name": "effectiveCreatedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "generated": { + "as": "COALESCE(\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%s.%fZ'),\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%sZ'),\n `createdAt`\n )", + "type": "stored" + } + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "xStreamInfo": { + "name": "xStreamInfo", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "firstViewEmailSentAt": { + "name": "firstViewEmailSentAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "isScreenshot": { + "name": "isScreenshot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "awsRegion": { + "name": "awsRegion", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awsBucket": { + "name": "awsBucket", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "videoStartTime": { + "name": "videoStartTime", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "audioStartTime": { + "name": "audioStartTime", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "jobId": { + "name": "jobId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "jobStatus": { + "name": "jobStatus", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skipProcessing": { + "name": "skipProcessing", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "owner_id_idx": { + "name": "owner_id_idx", + "columns": ["ownerId"], + "isUnique": false + }, + "owner_updated_id_idx": { + "name": "owner_updated_id_idx", + "columns": ["ownerId", "updatedAt", "id"], + "isUnique": false + }, + "is_public_idx": { + "name": "is_public_idx", + "columns": ["public"], + "isUnique": false + }, + "folder_id_idx": { + "name": "folder_id_idx", + "columns": ["folderId"], + "isUnique": false + }, + "storage_integration_id_idx": { + "name": "storage_integration_id_idx", + "columns": ["storageIntegrationId"], + "isUnique": false + }, + "org_owner_folder_idx": { + "name": "org_owner_folder_idx", + "columns": ["orgId", "ownerId", "folderId"], + "isUnique": false + }, + "org_owner_folder_effective_idx": { + "name": "org_owner_folder_effective_idx", + "columns": ["orgId", "ownerId", "folderId", "effectiveCreatedAt"], + "isUnique": false + }, + "org_effective_created_idx": { + "name": "org_effective_created_idx", + "columns": ["orgId", "effectiveCreatedAt"], + "isUnique": false + }, + "screenshot_transcription_created_idx": { + "name": "screenshot_transcription_created_idx", + "columns": ["isScreenshot", "transcriptionStatus", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "videos_storageIntegrationId_storage_integrations_id_fk": { + "name": "videos_storageIntegrationId_storage_integrations_id_fk", + "tableFrom": "videos", + "tableTo": "storage_integrations", + "columnsFrom": ["storageIntegrationId"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "videos_id": { + "name": "videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + } + }, + "views": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "tables": {}, + "indexes": { + "integration_object_key_prefix_idx": { + "columns": { + "`objectKey`(191)": { + "isExpression": true + } + } + } + } + } +} diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json index c689b934826..fdedc83c492 100644 --- a/packages/database/migrations/meta/_journal.json +++ b/packages/database/migrations/meta/_journal.json @@ -435,6 +435,13 @@ "when": 1794582375191, "tag": "0061_developer_delivery_metering", "breakpoints": true + }, + { + "idx": 62, + "version": "5", + "when": 1794635053920, + "tag": "0062_app_store", + "breakpoints": true } ] } diff --git a/packages/database/schema.ts b/packages/database/schema.ts index 9fc6d3ff653..278582fb387 100644 --- a/packages/database/schema.ts +++ b/packages/database/schema.ts @@ -249,6 +249,7 @@ export const organizations = mysqlTable( aiGenerationLanguage?: AiGenerationLanguage; defaultPlaybackSpeed?: number; allowPublicLinkOverride?: boolean; + appStoreAdminsOnly?: boolean; }>(), iconUrl: varchar("iconUrl", { length: 1024, @@ -402,6 +403,67 @@ export const integrationInstallations = mysqlTable( }), ); +export type AppStoreInstallationScope = "user" | "organization"; +export type AppStoreInstallationStatus = "active" | "disabled"; + +export const appStoreInstallations = mysqlTable( + "app_store_installations", + { + id: nanoId("id").notNull().primaryKey(), + appId: varchar("appId", { length: 64 }).notNull(), + scope: varchar("scope", { length: 16 }) + .notNull() + .$type(), + scopeKey: varchar("scopeKey", { length: 64 }).notNull(), + userId: nanoIdNullable("userId").$type(), + organizationId: + nanoIdNullable("organizationId").$type(), + installedByUserId: nanoId("installedByUserId") + .notNull() + .$type(), + appVersion: varchar("appVersion", { length: 32 }).notNull(), + grantedPermissions: json("grantedPermissions").notNull().$type(), + grantedEvents: json("grantedEvents").notNull().$type(), + encryptedSettings: encryptedTextNullable("encryptedSettings"), + status: varchar("status", { length: 16 }) + .notNull() + .default("active") + .$type(), + disabledReason: varchar("disabledReason", { length: 64 }), + consecutiveFailures: int("consecutiveFailures").notNull().default(0), + failingSince: timestamp("failingSince"), + lastDeliveryAt: timestamp("lastDeliveryAt"), + lastDeliveryStatus: varchar("lastDeliveryStatus", { length: 32 }), + createdAt: timestamp("createdAt").notNull().defaultNow(), + updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(), + }, + (table) => ({ + appScopeIndex: uniqueIndex("app_store_installations_app_scope_idx").on( + table.appId, + table.scopeKey, + ), + userIndex: index("app_store_installations_user_idx").on(table.userId), + organizationIndex: index("app_store_installations_organization_idx").on( + table.organizationId, + ), + }), +); + +export const appStoreEvents = mysqlTable( + "app_store_events", + { + id: varchar("id", { length: 64 }).notNull().primaryKey(), + type: varchar("type", { length: 64 }).notNull(), + videoId: nanoId("videoId").notNull().$type(), + createdAt: timestamp("createdAt").notNull().defaultNow(), + }, + (table) => ({ + createdAtIndex: index("app_store_events_created_at_idx").on( + table.createdAt, + ), + }), +); + export const organizationInvites = mysqlTable( "organization_invites", { diff --git a/turbo.json b/turbo.json index 50364f1fb66..5bb5e36eff1 100644 --- a/turbo.json +++ b/turbo.json @@ -8,6 +8,40 @@ "dependsOn": ["^build"], "outputs": [".next/**", "!.next/cache/**", "dist/**"] }, + "@cap/web#build": { + "inputs": [ + "**/*.ts", + "**/*.tsx", + "!node_modules/**", + "$TURBO_ROOT$/app-store/**", + "$TURBO_ROOT$/packages/app-store/src/**" + ], + "dependsOn": ["^build"], + "outputs": [ + ".next/**", + "!.next/cache/**", + "dist/**", + "public/app-store/**", + "lib/app-store/generated/**" + ] + }, + "@cap/web#build:web": { + "inputs": [ + "**/*.ts", + "**/*.tsx", + "!node_modules/**", + "$TURBO_ROOT$/app-store/**", + "$TURBO_ROOT$/packages/app-store/src/**" + ], + "dependsOn": ["^build"], + "outputs": [ + ".next/**", + "!.next/cache/**", + "dist/**", + "public/app-store/**", + "lib/app-store/generated/**" + ] + }, "@cap/chrome-extension#build": { "inputs": [ "**/*.ts",