Compare commits

..
22 Commits
Author SHA1 Message Date
dhkatz 096ee32fa5 The hub as an OpenID Connect provider for T5DE Music
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m30s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped
2026-11-19 01:22:33 -08:00
dhkatz f0a9661f8e Discord sign-in and basic accounts
Pull request / title (pull_request) Successful in 1s
CI / test (pull_request) Successful in 1m28s
CI / image (apps/api/Dockerfile, t5de-hub-api) (pull_request) Skipped
CI / image (apps/web/Dockerfile, t5de-hub-web) (pull_request) Skipped
Discord sign-in makes a basic account (Discord's verified email, no username
or password) for T5DE's other sites; it finishes setting up with a username
and password to use the hub. Implicit linking by email is off; members link
Discord from their account page. Better Auth 1.7.26.
2026-11-19 01:11:51 -08:00
dhkatz a66a3a4b6a docs: Music and shared accounts plan (#21)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m30s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 8s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 20s
Plan for T5DE Music and the account and payment changes it needs. Docs only; no code changes.

- `docs/music.md`: an IMVU room music bot. The website is music.t5de.dev (at home); streams are radio.t5de.dev (Oracle Cloud's free tier, dhkatz/infra `music-oracle`). Covers one account system with Discord sign-in and basic accounts, the hub as an OIDC provider with Music as its first client, room ownership from linked IMVU accounts, chat commands and permissions, pluggable sources modelled on HorizonRadio's (stations, own streams, YouTube), relayed vs direct streams, and the paid tier (sell the hosting; $1.99 a month per room).
- `docs/payments.md`: billing in the hub's API, shared by Music and the hub. Separate merchants per product (adult content needs different processors), processor adapters, entitlements, credits, and selling as an individual.
- `README.md`: links to both.

Decisions are marked **Decided**; the rest are proposals, with the open ones at the end of each doc.

Plan for T5DE Music and the account and payment changes it needs. Docs only; no code changes.

- `docs/music.md`: an IMVU room music bot. The website is music.t5de.dev (at home); streams are radio.t5de.dev (Oracle Cloud's free tier, dhkatz/infra `music-oracle`). Covers one account system with Discord sign-in and basic accounts, the hub as an OIDC provider with Music as its first client, room ownership from linked IMVU accounts, chat commands and permissions, pluggable sources modelled on HorizonRadio's (stations, own streams, YouTube), relayed vs direct streams, and the paid tier (sell the hosting; $1.99 a month per room).
- `docs/payments.md`: billing in the hub's API, shared by Music and the hub. Separate merchants per product (adult content needs different processors), processor adapters, entitlements, credits, and selling as an individual.
- `README.md`: links to both.

Decisions are marked **Decided**; the rest are proposals, with the open ones at the end of each doc.

Co-authored-by: dhkatz <[email protected]>
2026-11-18 22:29:48 +00:00
dhkatz cc6959082c feat(imports): Access Pass products through the importer's signed-in account (#20)
Release / release (push) Successful in 4s
CI / test (push) Successful in 7m28s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 16s
Co-authored-by: dhkatz <[email protected]>
2026-11-08 16:10:34 +00:00
dhkatz 56d25f7507 feat(imports): job claims carry IMVU's rating (#19)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m35s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 4s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 18s
Co-authored-by: dhkatz <[email protected]>
2026-11-08 14:37:33 +00:00
dhkatz 79c98078cb docs: peer review of ratings (design for later) (#18)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m35s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 3s
2026-11-08 14:10:33 +00:00
dhkatz 26cc8aec84 docs: import spike findings (#17)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m37s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 4s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 4s
Co-authored-by: dhkatz <[email protected]>
2026-11-08 13:40:19 +00:00
dhkatz efc7d6b808 feat: whole shops listed on IMVU, and GET /imports/available (#16)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m35s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 14s
Co-authored-by: dhkatz <[email protected]>
2026-11-08 00:51:00 +00:00
dhkatz 8f6dacba10 feat: recorded import grants, unclaimed creators and claiming (#15)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m24s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 7s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 13s
Co-authored-by: dhkatz <[email protected]>
2026-11-07 22:49:06 +00:00
dhkatz e6a97be894 feat: importer IMVU accounts and settings from the console (#14)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m25s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 14s
Co-authored-by: dhkatz <[email protected]>
2026-11-07 19:00:01 +00:00
dhkatz 7ece681eef feat: IMVU imports on the hub: grants, requests and the importer's job queue (#13)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m25s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 7s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 15s
Phase 4a (docs/imports.md): the hub's side of IMVU imports.

**Grants**
- A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`).
- The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products.
- The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it.
- Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog.
- Unlinking an IMVU account, or someone else linking it, suspends its grants.

**Requests**
- Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of:
  - `added`: already imported, and now in their library
  - `queued`: delivered to their library once imported
  - `suggested`: the creator grants by listed products, and will see the request
  - `counted`: no grant covers it yet
- Creators see request counts for their accounts, and moderators see the most-requested creators.
- At most 50 requests a day per person.

**Importer**
- Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`).
- Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes.
- Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts.
- `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too.
- Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions.

**Website**
- `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page.
- The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`:
  - importer on, off, pause and resume, and a new key
  - pending grants to accept or decline
  - grants to end
  - the queue, filtered by status, with retry
- Notification text for the two new notification types.

**Checks**
- **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass.
- **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer."
- **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them.

**Formatting**
- `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120.

**Still to do (4b and later)**
- admin-recorded grants, proofs and unclaimed creators (and claiming them)
- `GET /imports/available` for the proxy's shop button
- t5de-catalog accepting `t5de-import` tokens on uploads
- the spike, then `t5de-importer`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 4a (docs/imports.md): the hub's side of IMVU imports.

**Grants**
- A creator picks one of their linked IMVU accounts and a catalog with imports on. They choose the whole shop (with exclusions) or listed products, listed or unlisted, and agree to a versioned consent text (`imports.ts` `consent`).
- The catalog's team (`import:accept`) accepts or declines, and the creator is notified. Accepting queues what people already asked for, plus a grant's listed products.
- The creator can change what's covered or withdraw it; the team (`import:withdraw`, which moderators also have) can end it.
- Withdrawn products are removed the way moderation removes products: their hosting is dropped and their files go in the catalogs' changes feed. If another catalog's active grant still covers a product, it's only delisted from this catalog.
- Unlinking an IMVU account, or someone else linking it, suspends its grants.

**Requests**
- Anyone signed in can ask for an IMVU product (an ID or a shop link). The answer is one of:
  - `added`: already imported, and now in their library
  - `queued`: delivered to their library once imported
  - `suggested`: the creator grants by listed products, and will see the request
  - `counted`: no grant covers it yet
- Creators see request counts for their accounts, and moderators see the most-requested creators.
- At most 50 requests a day per person.

**Importer**
- Importers sign in with `Authorization: Importer <catalog>:<key>`; turning imports on returns the key once. The catalog's importer can be paused (`import:pause`).
- Importers claim jobs, get `t5de-import` tokens for a revision, and report outcomes.
- Claims time out after 30 minutes. Failures retry after 1 min, 10 min, 1 h, then daily, and fail for good after 5 attempts.
- `POST /catalog/revisions` takes `importToken` instead of `uploadToken`. The result is a published product owned by the creator (`product.imvu_product`, `product_revision.imvu_revision`). If another catalog already imported the same IMVU revision, this catalog hosts it too.
- Every hour, the API rechecks a batch of imported products with IMVU (each at most once a day). A product gone from IMVU, or now another creator's, is withdrawn. One rated AP becomes adult. If it's still covered, a recheck job looks for new revisions.

**Website**
- `/imports`: ask for a product; bring your products; change or withdraw a grant; what people asked for. It's linked from the account page.
- The console's catalog page has an Imports card leading to `/console/catalogs/:id/imports`:
  - importer on, off, pause and resume, and a new key
  - pending grants to accept or decline
  - grants to end
  - the queue, filtered by status, with retry
- Notification text for the two new notification types.

**Checks**
- **Tests:** `test/imports.test.ts` covers the whole flow, from grant to withdrawal. All 58 API tests pass, and type checks pass.
- **Scratch hub:** through the console forms, I turned imports on (the key was shown once), paused and resumed. I checked that importer claims accept the key and refuse a wrong one, that `/imports` renders, and that a request while IMVU is unreachable says "IMVU didn't answer."
- **IMVU fields not checked live:** `api.imvu.com` times out from the dev machine. The product fields (`product_name`, `creator_cid`, `creator_name`, `rating`, `is_purchasable`) are what the design recorded; the spike will check them.

**Formatting**
- `two-factor-card.tsx`, `signin-form.tsx` and `console-nav.tsx` are only reformatted. I'd run Prettier on them at its default 80 columns in #12, but the repo is wrapped at about 120.

**Still to do (4b and later)**
- admin-recorded grants, proofs and unclaimed creators (and claiming them)
- `GET /imports/available` for the proxy's shop button
- t5de-catalog accepting `t5de-import` tokens on uploads
- the spike, then `t5de-importer`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-07 16:29:03 +00:00
dhkatz eca1884918 feat: two-factor sign-in, required for sensitive permissions (#12)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m16s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 13s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 19s
Phase 3d (docs/design.md): two-factor sign-in, required for sensitive permissions.

- **Sign-in:** Better Auth's `twoFactor` plugin, using an authenticator app (TOTP) with 10 backup codes. Once it's on, signing in asks for a code from the app or a backup code, and each backup code works once.
- **Account page:** a new Two-Factor Sign-In card.
  - To turn it on: enter your password, scan the QR code (the key is also shown as text), keep the backup codes, and confirm with a code.
  - Once it's on, you can make new backup codes or turn it off; both ask for the password.
  - If you hold sensitive permissions, the card lists the ones that need it.
- **Enforcement:** the sensitive permissions are `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`, `catalog:suspend`, `import:grant-on-behalf` and `settings:edit` (`permissions.ts` `sensitive`). Without two-factor on, they answer 403 `two_factor_required`, and API tokens get the same check through their owner.
  - Routes guarded only by the moderator check now also check the permission: removing products, ban and unban, roles, and settings.
- **Console:** a reminder on every console page while two-factor is needed. The People list notes staff without two-factor, and each person's page shows "two-factor on".
- **Closed Better Auth admin endpoints:** `/api/auth/admin/*` now answers 404. Admins could have used these endpoints to ban people or change roles without the check or the audit log.
- **Tests:** a new end-to-end test, `test/two-factor.test.ts`. Moderation tests turn two-factor on for their accounts directly (`test/two-factor.ts`). All 57 API tests pass, and type checks pass.
- **Checked on the scratch hub through the website:**
  - turning it on with a real code
  - the console reminder appearing and disappearing
  - signing in again needing a code
  - a Ban form while two-factor is off showing "Turn on two-factor sign-in on your account page first."
- **Not checked in a browser:** the QR and sign-in code screens.
- **Dependency:** `uqr` draws the QR code; it has no dependencies of its own.

Phase 3d (docs/design.md): two-factor sign-in, required for sensitive permissions.

- **Sign-in:** Better Auth's `twoFactor` plugin, using an authenticator app (TOTP) with 10 backup codes. Once it's on, signing in asks for a code from the app or a backup code, and each backup code works once.
- **Account page:** a new Two-Factor Sign-In card.
  - To turn it on: enter your password, scan the QR code (the key is also shown as text), keep the backup codes, and confirm with a code.
  - Once it's on, you can make new backup codes or turn it off; both ask for the password.
  - If you hold sensitive permissions, the card lists the ones that need it.
- **Enforcement:** the sensitive permissions are `product:remove`, `person:ban`, `person:role`, `audit:read-sensitive`, `catalog:transfer`, `catalog:suspend`, `import:grant-on-behalf` and `settings:edit` (`permissions.ts` `sensitive`). Without two-factor on, they answer 403 `two_factor_required`, and API tokens get the same check through their owner.
  - Routes guarded only by the moderator check now also check the permission: removing products, ban and unban, roles, and settings.
- **Console:** a reminder on every console page while two-factor is needed. The People list notes staff without two-factor, and each person's page shows "two-factor on".
- **Closed Better Auth admin endpoints:** `/api/auth/admin/*` now answers 404. Admins could have used these endpoints to ban people or change roles without the check or the audit log.
- **Tests:** a new end-to-end test, `test/two-factor.test.ts`. Moderation tests turn two-factor on for their accounts directly (`test/two-factor.ts`). All 57 API tests pass, and type checks pass.
- **Checked on the scratch hub through the website:**
  - turning it on with a real code
  - the console reminder appearing and disappearing
  - signing in again needing a code
  - a Ban form while two-factor is off showing "Turn on two-factor sign-in on your account page first."
- **Not checked in a browser:** the QR and sign-in code screens.
- **Dependency:** `uqr` draws the QR code; it has no dependencies of its own.

Later: auditing when two-factor is turned on or off, and an optional "trust this browser".

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Later: auditing when two-factor is turned on or off, and an optional "trust this browser".

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-06 03:23:02 +00:00
dhkatz 69c55a72fb feat: personal API tokens (#11)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m13s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 12s
Phase 3, part 3 (`docs/design.md`, "Next"): personal API tokens, for scripts. Two-factor sign-in comes next as its own PR.

**Making them**
- On the account page, in a new API Tokens card. You give each token:
  - a name
  - how long it lasts: 7 days, 30 days, 90 days or 1 year
  - what it may do: permissions you hold, picked for each product of yours or catalog whose team you're on (moderators and admins can also pick everywhere)
- The token is shown once, with a Copy button. Only its hash is stored.
- The card lists active tokens: what each grants, when it expires, and when it was last used. Each can be revoked; revoked and expired ones are folded away below.
- Tokens are made and revoked only from a website session, so a token can't make tokens. Limits: 20 active tokens, 50 grants each, 1 year at most.

**Using them**
- Send `Authorization: Bearer t5de_pat_...`.
- A token works only on routes that check a permission:
  - product info, publishing, locks and history
  - uploading and retracting revisions of a product: these now check `revision:upload` and `revision:retract`
  - a catalog's settings, key, team, members, invites and hosted products
  - file blocks, and assigning cases
- Everywhere else answers 403 `token_not_allowed`, including making a new product, reports, `/me` and the console. A wrong, revoked or expired token gets 401 `bad_token`.
- Each check is the intersection of what the token grants and what the person holds now: a token never does more than its owner can, and losing a role takes it from the token at once.

**Audit**
- Actions taken with a token are recorded as the person, with `token: <name>` added to the details.
- Making and revoking a token are audited as `token.create` and `token.revoke`.

**Migration** `0014_api_tokens`: the `api_token` table.

**Checks**
- 56 API tests pass. The new `tokens.test.ts` covers:
  - only permissions held now can be granted
  - grants are limited to their product or catalog
  - session-only routes refuse tokens
  - uploads by token
  - the audit marking and last use
  - revoked and expired tokens
  - a moderator demoted while their token was active
- Type checks pass.
- On a local hub, through the website:
  - the card shows what can be granted
  - making a token (refused without any permission chosen); the token was shown once
  - using it for a granted edit and the member list; refused for what it wasn't given, and on `/me`
  - its last use on the account page, and the audit entry naming it
  - Revoke, after which the token got 401

Phase 3, part 3 (`docs/design.md`, "Next"): personal API tokens, for scripts. Two-factor sign-in comes next as its own PR.

**Making them**
- On the account page, in a new API Tokens card. You give each token:
  - a name
  - how long it lasts: 7 days, 30 days, 90 days or 1 year
  - what it may do: permissions you hold, picked for each product of yours or catalog whose team you're on (moderators and admins can also pick everywhere)
- The token is shown once, with a Copy button. Only its hash is stored.
- The card lists active tokens: what each grants, when it expires, and when it was last used. Each can be revoked; revoked and expired ones are folded away below.
- Tokens are made and revoked only from a website session, so a token can't make tokens. Limits: 20 active tokens, 50 grants each, 1 year at most.

**Using them**
- Send `Authorization: Bearer t5de_pat_...`.
- A token works only on routes that check a permission:
  - product info, publishing, locks and history
  - uploading and retracting revisions of a product: these now check `revision:upload` and `revision:retract`
  - a catalog's settings, key, team, members, invites and hosted products
  - file blocks, and assigning cases
- Everywhere else answers 403 `token_not_allowed`, including making a new product, reports, `/me` and the console. A wrong, revoked or expired token gets 401 `bad_token`.
- Each check is the intersection of what the token grants and what the person holds now: a token never does more than its owner can, and losing a role takes it from the token at once.

**Audit**
- Actions taken with a token are recorded as the person, with `token: <name>` added to the details.
- Making and revoking a token are audited as `token.create` and `token.revoke`.

**Migration** `0014_api_tokens`: the `api_token` table.

**Checks**
- 56 API tests pass. The new `tokens.test.ts` covers:
  - only permissions held now can be granted
  - grants are limited to their product or catalog
  - session-only routes refuse tokens
  - uploads by token
  - the audit marking and last use
  - revoked and expired tokens
  - a moderator demoted while their token was active
- Type checks pass.
- On a local hub, through the website:
  - the card shows what can be granted
  - making a token (refused without any permission chosen); the token was shown once
  - using it for a granted edit and the member list; refused for what it wasn't given, and on `/me`
  - its last use on the account page, and the audit entry naming it
  - Revoke, after which the token got 401

Note: the permission list also offers permissions for which no route takes tokens yet, such as `import:*` and `stats:read`. They'll work once those features have routes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Note: the permission list also offers permissions for which no route takes tokens yet, such as `import:*` and `stats:read`. They'll work once those features have routes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-06 02:58:12 +00:00
dhkatz 58a3e70a63 feat: file blocks (#10)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m13s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 12s
Phase 3, part 2 (`docs/design.md`, "Next"): file blocks. Moderators block a file network-wide by its sha256, so a removed product can't come back under another name or catalog.

**Blocking**
- A file's page (Console → Blocks → a file) shows whether it's blocked and the products using it, so a moderator sees what a block removes before confirming ("Block and remove 2 products").
- Moderators reach it from a product's files (each has a Block link for them) or by pasting a sha256 into the Blocks tab, which also lists blocked files.
- Blocking a file:
  - removes every product with a revision using it. Each removal is audited as `product.remove` with the file, so creators are notified and can appeal it as before.
  - puts a `{type: "block", sha256}` change in the changes feed of every catalog hosting it, meaning: delete it whatever uses it. (t5de-catalog doesn't read the feed yet.)
  - refuses uploads with it from then on (409 `blocked`). Each attempt is audited as `file.blocked_upload` with the person and catalog, so moderators see who tried.
- Unblocking lets the file in again. The products it removed stay removed until a moderator restores them, one by one.
- Who: `product:remove` hub-wide (moderators and admins). The Blocks tab shows only for them.

**API**: `GET /api/v1/blocks`, and `GET`/`PUT`/`DELETE /api/v1/blocks/:sha256` (`docs/products.md`).

**Migration** `0013_file_blocks`: the `file_block` table, and a GIN index on revisions' file lists, so finding the products using a file doesn't scan every revision.

**Checks**
- 53 API tests pass. The new `blocks.test.ts` covers:
  - who may block
  - the preview of what a block removes
  - removal of every product using the file, across catalogs and creators
  - the changes feed, notifications and appeals
  - refused uploads and their audit entry
  - unblocking, and restoring a removed product afterwards
- Type checks pass.
- On a local hub, through the website's own forms:
  - the Block link on a product's files, for moderators only
  - the Blocks tab, for moderators only (404 for the creator)
  - the file's page, then blocking: the product is gone, its creator notified and offered Appeal
  - a re-upload through the catalog API: refused, and audited
  - unblocking, then Restore
  - Fixed along the way: an empty reason gave a generic "Some of that isn't right"; it now says "Give a reason."

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 3, part 2 (`docs/design.md`, "Next"): file blocks. Moderators block a file network-wide by its sha256, so a removed product can't come back under another name or catalog.

**Blocking**
- A file's page (Console → Blocks → a file) shows whether it's blocked and the products using it, so a moderator sees what a block removes before confirming ("Block and remove 2 products").
- Moderators reach it from a product's files (each has a Block link for them) or by pasting a sha256 into the Blocks tab, which also lists blocked files.
- Blocking a file:
  - removes every product with a revision using it. Each removal is audited as `product.remove` with the file, so creators are notified and can appeal it as before.
  - puts a `{type: "block", sha256}` change in the changes feed of every catalog hosting it, meaning: delete it whatever uses it. (t5de-catalog doesn't read the feed yet.)
  - refuses uploads with it from then on (409 `blocked`). Each attempt is audited as `file.blocked_upload` with the person and catalog, so moderators see who tried.
- Unblocking lets the file in again. The products it removed stay removed until a moderator restores them, one by one.
- Who: `product:remove` hub-wide (moderators and admins). The Blocks tab shows only for them.

**API**: `GET /api/v1/blocks`, and `GET`/`PUT`/`DELETE /api/v1/blocks/:sha256` (`docs/products.md`).

**Migration** `0013_file_blocks`: the `file_block` table, and a GIN index on revisions' file lists, so finding the products using a file doesn't scan every revision.

**Checks**
- 53 API tests pass. The new `blocks.test.ts` covers:
  - who may block
  - the preview of what a block removes
  - removal of every product using the file, across catalogs and creators
  - the changes feed, notifications and appeals
  - refused uploads and their audit entry
  - unblocking, and restoring a removed product afterwards
- Type checks pass.
- On a local hub, through the website's own forms:
  - the Block link on a product's files, for moderators only
  - the Blocks tab, for moderators only (404 for the creator)
  - the file's page, then blocking: the product is gone, its creator notified and offered Appeal
  - a re-upload through the catalog API: refused, and audited
  - unblocking, then Restore
  - Fixed along the way: an empty reason gave a generic "Some of that isn't right"; it now says "Give a reason."

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-05 22:48:07 +00:00
dhkatz 7299e10b08 feat: cases (reports, reviews, requests, appeals) and notifications (#9)
Release / release (push) Successful in 3s
CI / test (push) Successful in 17m26s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 15s
Phase 3, part 1 (`docs/design.md`, "Next"): cases and notifications. File blocks, API tokens and two-factor sign-in come as separate PRs.

**Cases**
- One queue (Console → Cases) for everything someone has to decide. Each case has:
  - a thread of notes, where internal notes are visible only to those deciding
  - an assignee (moderators assign cases to moderators)
  - a decision, Resolve or Decline, with a written resolution that the person who opened it sees
- **Reports:** anyone signed in can report a product or catalog from its page (the API also takes rooms and people).
  - Limits: 10 an hour, one open report per person and thing, and you can't report yourself.
  - Reports about a product go to the teams of the catalogs hosting it, as well as to moderators.
  - Only the reporter and moderators know who reported. The audit entry for a report isn't tagged with what it's about, so a product's creator can't find out from their audit log either.
- **Rating reviews:** a creator lowering a rating from adult to general now opens a review instead of being refused. The rest of the edit still saves. Resolving the review lowers the rating, recorded in the product's history.
- **Removal requests:** a catalog's team can ask moderators to remove a product it hosts, everywhere. Resolving it removes the product.
- **Deletion requests:** a catalog's owner asks for deletion from the catalog's console page, and a moderator decides, as agreed. Resolving it marks the catalog `deleted`: its key stops working, nothing is available from it, and its changes feed says so.
- **Appeals:**
  - From the audit log, the person an action affected can appeal it, once: their product removed, delisted or edited by someone else; their catalog suspended or rejected; a ban from a catalog or a declined request to join.
  - Another moderator decides. An admin may decide an appeal of their own action, and the audit log flags it.
  - Resolving records the decision; the moderator then undoes the action where it's done. For that, there's now a Restore for removed products (Console → Products, for moderators); the design mentioned one, but it was never built.
- The console shows a "Cases" tab, and a to-do with the number of open cases the person could decide.

**Notifications**
- A bell in the header with the unread count, and a notifications page with "Mark all as read".
- Each is also sent to the person's proxies over the realtime connection (`{"type": "notification"}`), so the client can show them later.
- They cover:
  - a moderator edited or locked your product, or undid a change (with the reason)
  - your product was removed or restored
  - your case was decided
  - someone replied on your case
  - a catalog decided your membership

**Also changed**
- A product's creator and moderators can now see it when it's adult, even without an adult account. Before, a creator who made their own product adult couldn't open its page any more, and neither could moderators. Getting and wearing adult products still need an adult account.

**Not done yet** (in `docs/console.md`): email notifications (the hub sends no email yet), canned reasons, private moderator notes on people and products, and second approval for the most destructive actions.

**Migration** `0012_cases`: the `moderation_case`, `case_note` and `notification` tables. (`case` is a reserved word in SQL, hence the table's name.)

**Checks**
- 51 API tests pass. The 7 in the new `cases.test.ts` cover:
  - who sees and decides each kind of case, and that the reporter stays private
  - rate limits and duplicate reports
  - the thread and internal notes, and assigning
  - what deciding each kind of case does
  - appeals by the person affected only, decided by another moderator
  - restoring a removed product
  - the notifications
- Type checks pass.
- On a local hub I went through every flow with the website's own forms: report from a product page; the catalog owner's note and decision; assigning, an internal note and a decision as admin; removal by a moderator, the creator's appeal from the audit log, the admin's decision and Restore; a creator's rating review and the decision lowering the rating; a deletion request and its decline; the notifications, the bell's count, and Mark all as read.
- Fixed along the way:
  - The catalog's team could see who reported.
  - A missing Resolve/Decline choice was treated as Decline; now it's refused.
  - The Unassign button sent the typed name instead of nothing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 3, part 1 (`docs/design.md`, "Next"): cases and notifications. File blocks, API tokens and two-factor sign-in come as separate PRs.

**Cases**
- One queue (Console → Cases) for everything someone has to decide. Each case has:
  - a thread of notes, where internal notes are visible only to those deciding
  - an assignee (moderators assign cases to moderators)
  - a decision, Resolve or Decline, with a written resolution that the person who opened it sees
- **Reports:** anyone signed in can report a product or catalog from its page (the API also takes rooms and people).
  - Limits: 10 an hour, one open report per person and thing, and you can't report yourself.
  - Reports about a product go to the teams of the catalogs hosting it, as well as to moderators.
  - Only the reporter and moderators know who reported. The audit entry for a report isn't tagged with what it's about, so a product's creator can't find out from their audit log either.
- **Rating reviews:** a creator lowering a rating from adult to general now opens a review instead of being refused. The rest of the edit still saves. Resolving the review lowers the rating, recorded in the product's history.
- **Removal requests:** a catalog's team can ask moderators to remove a product it hosts, everywhere. Resolving it removes the product.
- **Deletion requests:** a catalog's owner asks for deletion from the catalog's console page, and a moderator decides, as agreed. Resolving it marks the catalog `deleted`: its key stops working, nothing is available from it, and its changes feed says so.
- **Appeals:**
  - From the audit log, the person an action affected can appeal it, once: their product removed, delisted or edited by someone else; their catalog suspended or rejected; a ban from a catalog or a declined request to join.
  - Another moderator decides. An admin may decide an appeal of their own action, and the audit log flags it.
  - Resolving records the decision; the moderator then undoes the action where it's done. For that, there's now a Restore for removed products (Console → Products, for moderators); the design mentioned one, but it was never built.
- The console shows a "Cases" tab, and a to-do with the number of open cases the person could decide.

**Notifications**
- A bell in the header with the unread count, and a notifications page with "Mark all as read".
- Each is also sent to the person's proxies over the realtime connection (`{"type": "notification"}`), so the client can show them later.
- They cover:
  - a moderator edited or locked your product, or undid a change (with the reason)
  - your product was removed or restored
  - your case was decided
  - someone replied on your case
  - a catalog decided your membership

**Also changed**
- A product's creator and moderators can now see it when it's adult, even without an adult account. Before, a creator who made their own product adult couldn't open its page any more, and neither could moderators. Getting and wearing adult products still need an adult account.

**Not done yet** (in `docs/console.md`): email notifications (the hub sends no email yet), canned reasons, private moderator notes on people and products, and second approval for the most destructive actions.

**Migration** `0012_cases`: the `moderation_case`, `case_note` and `notification` tables. (`case` is a reserved word in SQL, hence the table's name.)

**Checks**
- 51 API tests pass. The 7 in the new `cases.test.ts` cover:
  - who sees and decides each kind of case, and that the reporter stays private
  - rate limits and duplicate reports
  - the thread and internal notes, and assigning
  - what deciding each kind of case does
  - appeals by the person affected only, decided by another moderator
  - restoring a removed product
  - the notifications
- Type checks pass.
- On a local hub I went through every flow with the website's own forms: report from a product page; the catalog owner's note and decision; assigning, an internal note and a decision as admin; removal by a moderator, the creator's appeal from the audit log, the admin's decision and Restore; a creator's rating review and the decision lowering the rating; a deletion request and its decline; the notifications, the bell's count, and Mark all as read.
- Fixed along the way:
  - The catalog's team could see who reported.
  - A missing Resolve/Decline choice was treated as Decline; now it's refused.
  - The Unassign button sent the typed name instead of nothing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-05 22:14:08 +00:00
dhkatz e07a6c6dac feat: product drafts, moderator edits, info history, unlisted products, tags and categories (#8)
Release / release (push) Successful in 13s
CI / test (push) Successful in 1m5s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 4s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 16s
Phase 2 of the plan in `docs/design.md` ("Next"): product info.

**Drafts**
- A new upload is a draft. Only its creator and moderators can see it, and nobody can get or wear it.
- After uploading, the website goes straight to the product's review page, where the creator checks its info and presses Publish.
- Drafts not published within 30 days are deleted (checked every 10 minutes), and their catalogs get `delete` entries in their changes feed.
- The console's overview shows a "Drafts" to-do.

**Editing is a permission check now** (`product:edit`, from #7)
- Moderators can edit anyone's product. They must give a reason, which the creator sees.
- Moderators can lock fields (`product:lock`). Once a field is locked, only people with `product:edit-locked` can change it, so the creator sees it greyed out with "Locked by a moderator."
- Raising a rating to adult is immediate for anyone who can edit. Lowering it takes `product:rate-lower` (moderators), and is refused while any revision's files are rated adult. With cases (phase 3), a creator's request to lower it will open a rating review.

**Info history**
- Every edit, publish, lock change and undo is recorded with who, when, what changed (before and after) and why.
- It's shown on the edit page to the creator and moderators.
- "Undo" puts back what an entry changed, as a new entry, by the same rules (a creator can't undo a moderator's change to a field that's now locked).
- Moderator actions are also in the creator's audit log.

**Unlisted products and tags**
- An unlisted product is left out of search, lists and creator pages, except for its creator. Its link still works and people can still get it.
- Tags: up to 10 per product, lowercased.
- `/products` filters by `tag` and `catalog`, and a product's tags link to the filtered list.
- People who don't manage a product don't see its state labels (draft, unlisted, locks).

**Console → Products**
- Lists your products with drafts included; moderators can switch to everyone's.
- Filters: draft, published, unlisted, locked, deleted, removed, plus search.
- Shows how many libraries each product is in, and an Edit or Review button.

**Category**
- A product can be filed under a different IMVU category from its parent's.
- The choices are every category path the hub has seen on any product's parent, plus each level of those paths. They're limited to the same top-level category as the parent's, so a product stays the same kind (clothing, furniture or rooms), which the proxy relies on for the shop and inventory tabs.
- The list grows as products are uploaded. IMVU's own category tree, if it has a public one, would replace it.
- Category works like the other info fields: it can be locked, it's in the history, and it can be undone. The product list's category filter, and everything that shows a product's categories (including what the proxy gets), use the chosen path.

**Migration** `0011_product_info`: new product columns and the `product_info_change` table. Existing products count as published (with `published_at` set from their creation date) and listed.

**Compatibility**
- `t5de-catalog` needs no change: the hub's new `draft` field in the registration answer is ignored, and the website doesn't rely on it.
- The proxy only loads products from libraries, and drafts can't be added to one.

**Checks**
- 44 API tests pass, including a new one for moderator edits, locks, history, undo, unlisted, tags, the console list and draft purging, and new checks for category choices.
- Type checks pass.
- On a local hub I loaded the pages as the creator, an admin, another person and a signed-out visitor.
- I submitted the forms through the website, the way a browser does without JavaScript: save info, publish, choosing a category (and undoing it), a moderator's save with and without a reason, save locks, and undo, including a creator's undo refused by a lock. Each saved or refused correctly with the right message.
- Not tried: the upload form's redirect after a real upload to a running catalog.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 2 of the plan in `docs/design.md` ("Next"): product info.

**Drafts**
- A new upload is a draft. Only its creator and moderators can see it, and nobody can get or wear it.
- After uploading, the website goes straight to the product's review page, where the creator checks its info and presses Publish.
- Drafts not published within 30 days are deleted (checked every 10 minutes), and their catalogs get `delete` entries in their changes feed.
- The console's overview shows a "Drafts" to-do.

**Editing is a permission check now** (`product:edit`, from #7)
- Moderators can edit anyone's product. They must give a reason, which the creator sees.
- Moderators can lock fields (`product:lock`). Once a field is locked, only people with `product:edit-locked` can change it, so the creator sees it greyed out with "Locked by a moderator."
- Raising a rating to adult is immediate for anyone who can edit. Lowering it takes `product:rate-lower` (moderators), and is refused while any revision's files are rated adult. With cases (phase 3), a creator's request to lower it will open a rating review.

**Info history**
- Every edit, publish, lock change and undo is recorded with who, when, what changed (before and after) and why.
- It's shown on the edit page to the creator and moderators.
- "Undo" puts back what an entry changed, as a new entry, by the same rules (a creator can't undo a moderator's change to a field that's now locked).
- Moderator actions are also in the creator's audit log.

**Unlisted products and tags**
- An unlisted product is left out of search, lists and creator pages, except for its creator. Its link still works and people can still get it.
- Tags: up to 10 per product, lowercased.
- `/products` filters by `tag` and `catalog`, and a product's tags link to the filtered list.
- People who don't manage a product don't see its state labels (draft, unlisted, locks).

**Console → Products**
- Lists your products with drafts included; moderators can switch to everyone's.
- Filters: draft, published, unlisted, locked, deleted, removed, plus search.
- Shows how many libraries each product is in, and an Edit or Review button.

**Category**
- A product can be filed under a different IMVU category from its parent's.
- The choices are every category path the hub has seen on any product's parent, plus each level of those paths. They're limited to the same top-level category as the parent's, so a product stays the same kind (clothing, furniture or rooms), which the proxy relies on for the shop and inventory tabs.
- The list grows as products are uploaded. IMVU's own category tree, if it has a public one, would replace it.
- Category works like the other info fields: it can be locked, it's in the history, and it can be undone. The product list's category filter, and everything that shows a product's categories (including what the proxy gets), use the chosen path.

**Migration** `0011_product_info`: new product columns and the `product_info_change` table. Existing products count as published (with `published_at` set from their creation date) and listed.

**Compatibility**
- `t5de-catalog` needs no change: the hub's new `draft` field in the registration answer is ignored, and the website doesn't rely on it.
- The proxy only loads products from libraries, and drafts can't be added to one.

**Checks**
- 44 API tests pass, including a new one for moderator edits, locks, history, undo, unlisted, tags, the console list and draft purging, and new checks for category choices.
- Type checks pass.
- On a local hub I loaded the pages as the creator, an admin, another person and a signed-out visitor.
- I submitted the forms through the website, the way a browser does without JavaScript: save info, publish, choosing a category (and undoing it), a moderator's save with and without a reason, save locks, and undo, including a creator's undo refused by a lock. Each saved or refused correctly with the right message.
- Not tried: the upload form's redirect after a real upload to a running catalog.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-05 14:23:26 +00:00
dhkatz 2cbedd26fc feat: permissions, a scoped console, and catalog management (#7)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m8s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 14s
Phase 1 of `docs/console.md` (builds on #6, whose docs commit it includes; merge #6 first).

**API**
- `permissions.ts`: `resource:action` permissions, built-in roles as bundles at a scope (hub, catalog, product), `can`/`require`, "may give" checks. A missing permission answers 403 with `missing: {permission, scope}`.
- Catalog management: settings (incl. rating ceiling, upload policy, mirroring), key rotation, operators, membership (open / approval / invite links, bans), delisting, suspension by moderators, and `GET /api/v1/catalog/changes` for catalogs.
- Membership is enforced: getting a product (403 `members_only` with the catalogs to join), the library list, and outfits relayed to others. Seeing products still needs no membership.
- Console for everyone who controls a catalog, product or hosted room; `/console/audit` (tagged entries, scoped by permission, with filters), `/console/permissions`; `/me` says whether the console is for them.
- Migration 0010: `role_assignment`, `catalog_member`, `catalog_invite`, `catalog_change`, catalog settings, audit `tags` (backfilled from old entries).

**Website**
- Console overview by what you manage; audit log page with filters; catalog list scoped to your teams; a catalog management page (settings, key, team, members, invitations, products, moderation, recent changes).
- Public catalog pages with join / ask / accept invitation / leave; product pages say "members only" and link the catalogs.

**Checked**: 43 API tests pass (8 new in `catalogs.test.ts`); API, web and db type checks; every new page rendered against a local hub for owner, operator, member, outsider and admin; the Eden DELETE-with-query calls tested against the API. Server-action forms weren't clicked through in a browser.

Not in this PR (later phases): catalog deletion requests (with cases), drafts and moderator product edits, notifications, API tokens, two-factor, imports, charts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Phase 1 of `docs/console.md` (builds on #6, whose docs commit it includes; merge #6 first).

**API**
- `permissions.ts`: `resource:action` permissions, built-in roles as bundles at a scope (hub, catalog, product), `can`/`require`, "may give" checks. A missing permission answers 403 with `missing: {permission, scope}`.
- Catalog management: settings (incl. rating ceiling, upload policy, mirroring), key rotation, operators, membership (open / approval / invite links, bans), delisting, suspension by moderators, and `GET /api/v1/catalog/changes` for catalogs.
- Membership is enforced: getting a product (403 `members_only` with the catalogs to join), the library list, and outfits relayed to others. Seeing products still needs no membership.
- Console for everyone who controls a catalog, product or hosted room; `/console/audit` (tagged entries, scoped by permission, with filters), `/console/permissions`; `/me` says whether the console is for them.
- Migration 0010: `role_assignment`, `catalog_member`, `catalog_invite`, `catalog_change`, catalog settings, audit `tags` (backfilled from old entries).

**Website**
- Console overview by what you manage; audit log page with filters; catalog list scoped to your teams; a catalog management page (settings, key, team, members, invitations, products, moderation, recent changes).
- Public catalog pages with join / ask / accept invitation / leave; product pages say "members only" and link the catalogs.

**Checked**: 43 API tests pass (8 new in `catalogs.test.ts`); API, web and db type checks; every new page rendered against a local hub for owner, operator, member, outsider and admin; the Eden DELETE-with-query calls tested against the API. Server-action forms weren't clicked through in a browser.

Not in this PR (later phases): catalog deletion requests (with cases), drafts and moderator product edits, notifications, API tokens, two-factor, imports, charts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-05 13:13:42 +00:00
dhkatz ed3a188b82 docs: permissions, console and imported IMVU products (#6)
Release / release (push) Successful in 5s
CI / test (push) Successful in 1m4s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 21s
Design for the next phases (discussed 2026-11-04):

- `docs/console.md` (new): permissions (`resource:action`), roles as bundles given at a scope (hub, catalog, product, room), one console for everyone who controls something, a tagged audit log scoped by permission, cases (reports, appeals, reviews, catalog deletion), notifications, API tokens, two-factor sign-in for sensitive permissions, "why can't I" and view-as, charts.
- `docs/imports.md` (new): catalogs importing IMVU products with the creator's grant (whole shop or chosen products), admin-recorded grants, requests, unclaimed creators, the job queue, `t5de-importer`, withdrawal, the spike.
- `docs/products.md`: drafts, unlisted products, membership enforced, catalog management routes, moderator edits, info history and locks, file blocks, the catalogs' changes feed, mirroring, the `t5de-import` token and importer routes.
- `docs/design.md`: pointers, phases and the later list.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Design for the next phases (discussed 2026-11-04):

- `docs/console.md` (new): permissions (`resource:action`), roles as bundles given at a scope (hub, catalog, product, room), one console for everyone who controls something, a tagged audit log scoped by permission, cases (reports, appeals, reviews, catalog deletion), notifications, API tokens, two-factor sign-in for sensitive permissions, "why can't I" and view-as, charts.
- `docs/imports.md` (new): catalogs importing IMVU products with the creator's grant (whole shop or chosen products), admin-recorded grants, requests, unclaimed creators, the job queue, `t5de-importer`, withdrawal, the spike.
- `docs/products.md`: drafts, unlisted products, membership enforced, catalog management routes, moderator edits, info history and locks, file blocks, the catalogs' changes feed, mirroring, the `t5de-import` token and importer routes.
- `docs/design.md`: pointers, phases and the later list.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-05 13:05:58 +00:00
dhkatz d5cd2be5d0 feat: age verification with an ID document (Didit), and closed registration (#4)
Release / release (push) Successful in 4s
CI / test (push) Successful in 1m19s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 7s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 20s
## Age verification with Didit

A new provider (`apps/api/src/age/didit.ts`) behind the existing vendor-neutral age interface. A person verifies once with an ID document, a passive liveness check and a face match; after that, all their linked IMVU accounts count as adult. The hub keeps only "over 18": never the document, photo or birth date.

- Webhooks are checked against Didit's signatures (the raw body or V2, with `-Previous` during secret rotation), and old ones are rejected. If the webhook has no decision, the hub fetches it from Didit.
- A later answer replaces an earlier one. An approval that's taken back (say, after a manual review) becomes `revoked`. A check still in review stays pending.
- Limits, for every provider: one unfinished check per person (starting again resumes it), at most 3 checks in 30 days, none once verified, and a monthly cap (`DIDIT_MONTHLY_LIMIT`, default 30: since 2026-11-01, Didit's free plan is $10 of credit a month, and a check costs $0.30).
- People are only ever sent back to the hub's website.
- The Account page gets an Age Verification card.
- Configuration: `AGE_PROVIDERS=imvu,didit`, `DIDIT_API_KEY`, `DIDIT_WORKFLOW_ID`, `DIDIT_WEBHOOK_SECRET`. The webhook is `<API_URL>/api/v1/age/webhook/didit`.

## Closed registration

Registration is open or closed. It's an admin's setting in the console, with its default from `REGISTRATION`.

- When it's closed, new accounts can only sign in until a moderator approves them, or declines them (which deletes the account).
- The website shows people who are waiting a waiting page, and the API treats them as signed out everywhere but `/me`.
- The console gets a Waiting count, a Waiting for approval filter, Approve and Decline on a person's page, and a Registration setting.
- The migration adds `user.approved` (existing accounts stay approved) and `hub_setting`.

## Testing

- New tests cover Didit (with a fake Didit server), the limits, revocation, return addresses and registration.
- `bun run test`: 35 pass. `bun run check-types` passes.
- Checked locally: the account, waiting, sign-up and console pages render.
- Not run against Didit itself yet. The sandbox workflow "T5DE Age Check" is published, and the next step is a real webhook once this is on staging.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

## Age verification with Didit

A new provider (`apps/api/src/age/didit.ts`) behind the existing vendor-neutral age interface. A person verifies once with an ID document, a passive liveness check and a face match; after that, all their linked IMVU accounts count as adult. The hub keeps only "over 18": never the document, photo or birth date.

- Webhooks are checked against Didit's signatures (the raw body or V2, with `-Previous` during secret rotation), and old ones are rejected. If the webhook has no decision, the hub fetches it from Didit.
- A later answer replaces an earlier one. An approval that's taken back (say, after a manual review) becomes `revoked`. A check still in review stays pending.
- Limits, for every provider: one unfinished check per person (starting again resumes it), at most 3 checks in 30 days, none once verified, and a monthly cap (`DIDIT_MONTHLY_LIMIT`, default 30: since 2026-11-01, Didit's free plan is $10 of credit a month, and a check costs $0.30).
- People are only ever sent back to the hub's website.
- The Account page gets an Age Verification card.
- Configuration: `AGE_PROVIDERS=imvu,didit`, `DIDIT_API_KEY`, `DIDIT_WORKFLOW_ID`, `DIDIT_WEBHOOK_SECRET`. The webhook is `<API_URL>/api/v1/age/webhook/didit`.

## Closed registration

Registration is open or closed. It's an admin's setting in the console, with its default from `REGISTRATION`.

- When it's closed, new accounts can only sign in until a moderator approves them, or declines them (which deletes the account).
- The website shows people who are waiting a waiting page, and the API treats them as signed out everywhere but `/me`.
- The console gets a Waiting count, a Waiting for approval filter, Approve and Decline on a person's page, and a Registration setting.
- The migration adds `user.approved` (existing accounts stay approved) and `hub_setting`.

## Testing

- New tests cover Didit (with a fake Didit server), the limits, revocation, return addresses and registration.
- `bun run test`: 35 pass. `bun run check-types` passes.
- Checked locally: the account, waiting, sign-up and console pages render.
- Not run against Didit itself yet. The sandbox workflow "T5DE Age Check" is published, and the next step is a real webhook once this is on staging.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-04 11:37:21 +00:00
release-bot 86ebe976ba chore(release): v0.2.0 (#3)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m10s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 6s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 4s
Merging this releases **v0.2.0**: release-bot tags it on main, CI builds its image, and Komodo deploys it to prod. It updates itself as pull requests are merged.

## 0.2.0 (2026-11-03)

### Features

- **web:** Download link to t5de.dev in the header (#2)

Merging this releases **v0.2.0**: release-bot tags it on main, CI builds its image, and Komodo deploys it to prod. It updates itself as pull requests are merged.

## 0.2.0 (2026-11-03)

### Features

- **web:** Download link to t5de.dev in the header (#2)

Co-authored-by: release-bot <[email protected]>
2026-11-03 11:29:26 +00:00
dhkatz efd5d52198 feat(web): Download link to t5de.dev in the header (#2)
Release / release (push) Successful in 3s
CI / test (push) Successful in 1m2s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 4s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 12s
A Download link in the header, beside the account menu or Sign in, to t5de.dev/download: T5DE's website with the latest setup, its version and checksum. Gitea's release pages are confusing for people new to it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

A Download link in the header, beside the account menu or Sign in, to t5de.dev/download: T5DE's website with the latest setup, its version and checksum. Gitea's release pages are confusing for people new to it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: dhkatz <[email protected]>
2026-11-03 10:54:20 +00:00
dhkatz f8ab3f965e ci: release pull requests, and conventional-commit PR titles (#1)
Release / release (push) Successful in 2s
CI / test (push) Successful in 57s
CI / image (apps/web/Dockerfile, t5de-hub-web) (push) Successful in 5s
CI / image (apps/api/Dockerfile, t5de-hub-api) (push) Successful in 5s
Releases as pull requests, the same in all five app repos (hub, catalog, live, riftbound, karaoke). The Gitea side (PRs only into main, squash merges, required checks, `v*` tags only by release-bot, its `RELEASE_TOKEN` org secret) is dhkatz/infra `modules/app-repo`.

- **`.gitea/workflows/pull-request.yml`**: the PR title must be a conventional commit (`feat(api): …`, `fix: …`, `feat!: …`); it becomes the commit on main. `chore(release)` only from release-bot's `release` branch. Required to merge (`Pull request / title`).
- **`.gitea/default_merge_message/SQUASH_TEMPLATE.md`**: the squash commit is `<PR title> (#<n>)` plus the description.
- **`.gitea/workflows/release.yml`**, on every push to main, as release-bot (`RELEASE_TOKEN`):
  - if the commit is a merged `chore(release): vX.Y.Z`: tag it vX.Y.Z (lightweight), push the tag (CI builds the image, Komodo deploys prod), publish the release with git-cliff's notes;
  - otherwise, if anything releasable landed since the last tag: rewrite the `release` branch (CHANGELOG.md) and open or update `chore(release): vX.Y.Z`.
- **`cliff.toml`** (git-cliff 2.14.2, pinned by sha512): feat → minor, fix/perf/revert → patch, breaking → minor while 0.x; chore/ci/docs/test/style/build/refactor alone don't release. Only conventional commits count, so the history before this is left out.
- **`CHANGELOG.md`**: header only; release PRs fill it.
- Agent notes (CLAUDE.md / AGENTS.md): the PR flow and title format; never tag by hand.

After merging, `Release` runs on main and should report nothing to release (this PR is `ci:`); the first `feat:`/`fix:` PR merged after it opens the first release PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #1
Co-authored-by: dhkatz <[email protected]>
2026-11-03 08:40:29 +00:00
141 changed files with 70962 additions and 564 deletions

No files matched your search

@@ -0,0 +1,3 @@
${PullRequestTitle} (#${PullRequestIndex})
${PullRequestDescription}
+30
View File
@@ -0,0 +1,30 @@
# A pull request's title becomes its commit on main (squash merges, .gitea/default_merge_message), so it must be a
# conventional commit: the release workflow versions releases and writes the changelog from them. Required to merge
# (branch protection, dhkatz/infra modules/app-repo).
name: Pull request
on:
pull_request:
types: [opened, edited, reopened, synchronize]
jobs:
title:
runs-on: ubuntu-latest
steps:
- name: Conventional commit title
env:
TITLE: ${{ github.event.pull_request.title }}
BRANCH: ${{ github.head_ref }}
AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
types="feat|fix|perf|refactor|docs|test|build|ci|chore|style|revert"
conventional="^($types)(\([a-z0-9][a-z0-9./_-]*\))?!?: [^ ]"
if ! [[ "$TITLE" =~ $conventional ]]; then
echo "::error::The title becomes the commit on main, so it must be a conventional commit: type(scope): summary, e.g. \"feat(api): room bans\" or \"fix: crash on an empty catalog\" (! before the colon for a breaking change). Types: ${types//|/, }."
exit 1
fi
if [[ "$TITLE" =~ ^chore\(release\) ]] && [[ "$BRANCH" != release || "$AUTHOR" != release-bot ]]; then
echo "::error::chore(release) is release-bot's: merging its release pull request is what tags a release."
exit 1
fi
echo "OK: $TITLE"
+86
View File
@@ -0,0 +1,86 @@
# Releases. release-bot keeps one pull request open from the `release` branch, "chore(release): vX.Y.Z": the next
# version and its CHANGELOG.md entry, which git-cliff (cliff.toml) works out from the conventional commits on main
# since the last tag. Merging it makes release-bot tag vX.Y.Z on main and publish the release notes; the tag builds the
# image (ci.yml) and Komodo deploys it to prod (dhkatz/infra). Only release-bot may create v* tags. It acts with its
# own token (the org secret RELEASE_TOKEN), not this workflow's: Gitea starts no workflows for what that one does, so
# the release pull request's checks and the tag's build would never run.
name: Release
on:
push:
branches: [main]
concurrency:
group: release
jobs:
release:
runs-on: ubuntu-latest
env:
CLIFF_VERSION: 2.14.2
CLIFF_SHA512: 95b0c55ab3e351ca7c0285fbbde8f1e8c42906466a173e6884f5c7ca814523bda44cbd4ab26b0aa28cace4c02c5ee6b553e9742bd9d7df47a73b9ef58ea429a9
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Install git-cliff
run: |
archive="git-cliff-$CLIFF_VERSION-x86_64-unknown-linux-musl.tar.gz"
curl -fsSLO "https://github.com/orhun/git-cliff/releases/download/v$CLIFF_VERSION/$archive"
echo "$CLIFF_SHA512 $archive" | sha512sum -c -
mkdir -p "$HOME/.local/bin"
tar -xzf "$archive" --strip-components=1 -C "$HOME/.local/bin" "git-cliff-$CLIFF_VERSION/git-cliff"
rm "$archive"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: Tag a merged release, or update the release pull request
env:
TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: |
set -euo pipefail
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY"
host="${GITHUB_SERVER_URL#https://}"
git config user.name release-bot
git config user.email "release-bot@${host#git.}"
basic=$(printf 'release-bot:%s' "$TOKEN" | base64 -w0)
push() { git -c http.extraHeader="Authorization: Basic $basic" push "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$@"; }
gitea() { curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" "$@"; }
# The release pull request was merged: tag its commit and publish the release.
if [[ "$(git log -1 --format=%s)" =~ ^chore\(release\):\ (v[0-9]+\.[0-9]+\.[0-9]+) ]]; then
tag="${BASH_REMATCH[1]}"
if git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then echo "$tag exists already"; exit 0; fi
git tag "$tag"
push "refs/tags/$tag"
jq -n --arg tag "$tag" --arg body "$(git cliff --latest --strip all)" '{tag_name: $tag, name: $tag, body: $body}' |
gitea -o /dev/null -X POST "$api/releases" -d @-
echo "Released $tag"
exit 0
fi
# Otherwise: anything to release since the last tag? (Nothing printed when no commit counts.)
last=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
next=$(git cliff --bumped-version 2>/dev/null || true)
next="v${next#v}"
if [ "$next" = v ] || [ "$next" = "$last" ]; then echo "Nothing to release since ${last:-the start}"; exit 0; fi
notes=$(git cliff --unreleased --bump --strip all)
git switch -C release
git cliff --bump --output CHANGELOG.md
git add CHANGELOG.md
git commit -q -m "chore(release): $next"
push --force HEAD:refs/heads/release
title="chore(release): $next"
body=$(printf 'Merging this releases **%s**: release-bot tags it on main, CI builds its image, and Komodo deploys it to prod. It updates itself as pull requests are merged.\n\n%s\n' "$next" "$notes")
payload=$(jq -n --arg title "$title" --arg body "$body" '{title: $title, body: $body}')
open=$(gitea "$api/pulls?state=open&limit=50" | jq -r '[.[] | select(.head.ref == "release")][0].number // empty')
if [ -n "$open" ]; then
gitea -o /dev/null -X PATCH "$api/pulls/$open" -d "$payload"
echo "Updated the release pull request #$open: $title"
else
jq '. + {head: "release", base: "main"}' <<<"$payload" | gitea -o /dev/null -X POST "$api/pulls" -d @-
echo "Opened the release pull request: $title"
fi
+44
View File
@@ -0,0 +1,44 @@
# Changelog
Written by release-bot's release pull requests, from the titles of the pull requests merged since the last release.
## 0.2.0 (2026-11-03)
### Features
- **web:** Download link to t5de.dev in the header (#2)
## 0.1.0 (2026-11-02)
### Badges
- The proxy asks which IMVU accounts show the T5 badge
### CI
- Test against a Postgres service (embedded Postgres won't run as root)
### Design
- T5 products in the client's shop and inventory
- Everywhere the T5 badge appears
### Hub
- Accounts, IMVU linking by tagline, proxy sign-in, presence, console
### Presence
- Count an account as soon as it's linked; accept an empty outfit
### Products
- Images need https addresses; lowering a rating waits for review; library shows creators
- Carry the IMVU parent's image and categories
### Website
- Next.js app for accounts, linking, who's online, device sign-in and the console
- Products, library, catalogs and their console page
+7
View File
@@ -10,6 +10,13 @@ T5DE's hub (see README.md and docs/design.md). Related repositories, usually che
in our own words are fine.
- Test with a throwaway IMVU account, never a real one.
- Commits: author "dhkatz <dev@t5de.dev>"; never the user's real name or email.
- Changes reach main only through pull requests, squash-merged: the PR's title becomes the commit on main, so it must
be a conventional commit (`feat(api): …`, `fix(web): …`, `docs: …`; `!` before the colon for a breaking change),
checked by `.gitea/workflows/pull-request.yml`. Commits on the branch can be anything. Push a branch and open the
pull request on git.t5de.dev (web UI or API); the user merges.
- Releases: release-bot keeps a `chore(release): vX.Y.Z` pull request open (`release.yml`, git-cliff from those
titles); merging it tags vX.Y.Z, which builds the image and deploys prod. Never tag by hand (v* tags are
release-bot's).
- IMVU session keys never leave the user's machine; the hub never asks for them.
## Notes
+15 -3
View File
@@ -3,16 +3,28 @@
T5DE's hub: accounts linked to IMVU accounts, presence, and (to come) the registry of community products and
catalogs, T5DE-hosted rooms, and the moderation console. Part of T5DE (git.t5de.dev/t5de). Design:
[docs/design.md](docs/design.md); the API: [docs/api.md](docs/api.md); what a room needs from a server:
[docs/imq-rooms.md](docs/imq-rooms.md).
[docs/imq-rooms.md](docs/imq-rooms.md); Music and shared accounts (plan): [docs/music.md](docs/music.md), with
payments in [docs/payments.md](docs/payments.md).
## What works
- **Accounts** (Better Auth): sign-up with email, username and password; sign-in by username. The first account is
an admin; roles user, moderator, admin.
an admin; roles user, moderator, admin. Registration open or closed (new accounts wait for a moderator's
approval): an admin's setting in the console, defaulting to the API's `REGISTRATION`.
- **Discord sign-in** (when `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set; Discord redirects to
`<API_URL>/api/auth/callback/discord`): the first time it makes a basic account (Discord's verified email,
no username or password) for T5DE's other sites, such as Music (docs/music.md); it finishes setting up
with a username and password to use the hub. Members link Discord from their account page. Accounts are
never linked by matching email.
- **Signing in on T5DE's other sites**: the hub is an OpenID Connect provider (issuer `<API_URL>/api/auth`) for
T5DE Music (`MUSIC_CLIENT_SECRET`, `MUSIC_REDIRECT_URIS`), with an `imvu` scope for the person's linked IMVU
accounts and `imvu:link` for linking them from Music (docs/api.md).
- **Linking IMVU accounts**: the person puts a code in the account's tagline; the hub reads it from IMVU's public
API. The most recent proof wins (an account linked elsewhere moves, with a new pairwise ID). Link caps per person
(default 10).
- **Age**: an IMVU account counts as adult if IMVU says it's age verified or has Access Pass, checked by the hub.
- **Age**: an IMVU account counts as adult if IMVU says it's age verified or has Access Pass, checked by the hub, or
if its person verified their age with an ID document and a selfie (Didit, when configured: `AGE_PROVIDERS`, see
`apps/api/src/index.ts` and docs/design.md, "Age").
- **Proxy sign-in**: OAuth 2.0 device authorization (`t5de-proxy signin` shows a code to enter at `/device`); the
proxy then uses its session as a bearer token. JWTs with published keys (`/.well-known/jwks.json`) for catalogs.
- **Presence**: signed-in proxies keep a WebSocket (`/api/v1/realtime`) telling the hub which IMVU account is in
+2 -1
View File
@@ -12,8 +12,9 @@
"check-types": "tsc --noEmit"
},
"dependencies": {
"@better-auth/oauth-provider": "1.7.26",
"@t5de/db": "workspace:*",
"better-auth": "1.7.14",
"better-auth": "1.7.26",
"elysia": "1.4.30",
"jose": "6.2.14",
"sanitize-html": "2.18.1"
+123
View File
@@ -0,0 +1,123 @@
// Age from an ID document and a selfie, by Didit's hosted check (https://docs.didit.me). Its workflow (set up in
// Didit's console) checks the document, liveness and that the face matches the document; the hub only keeps whether
// the person is over 18, worked out from the age Didit read off the document. Didit keeps the rest.
//
// A check: the hub creates a session (vendor_data is the person's hub ID, so Didit gives an unfinished session
// again rather than a new one), sends the person to its page, and Didit reports the outcome by a signed webhook.
import { createHmac, timingSafeEqual } from "node:crypto";
import type { AgeResult, Provider } from "./index";
export type DiditConfig = {
apiKey: string;
workflowId: string;
/** The webhook destination's secret_shared_key. */
webhookSecret: string;
/** Checks started a month at most (what the month's credit pays for). */
monthlyLimit?: number;
baseURL?: string;
fetch?: typeof fetch;
};
/** How far a webhook's X-Timestamp may be from now. */
const timestampTolerance = 300;
/** Statuses with an answer: a session approved, or one that will never be. The rest (in progress, in review) wait. */
const failedStatuses = new Set(["Declined", "Abandoned", "Expired"]);
type Decision = { id_verifications?: { age?: number | null; date_of_birth?: string | null }[] };
/** Age in whole years on a date, from an ISO birth date. */
export function ageOn(birth: string, today: Date): number | undefined {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(birth);
if (!m) return undefined;
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
let age = today.getUTCFullYear() - y;
if (today.getUTCMonth() + 1 < mo || (today.getUTCMonth() + 1 === mo && today.getUTCDate() < d)) age--;
return age;
}
/** The age on the session's ID document, or undefined if it has none. */
function documentAge(decision: Decision | undefined): number | undefined {
const id = decision?.id_verifications?.[0];
if (typeof id?.age === "number") return id.age;
return id?.date_of_birth ? ageOn(id.date_of_birth, new Date()) : undefined;
}
/** Didit's V2 signature input: the body's JSON with keys sorted, compact. */
function canonical(v: unknown): unknown {
if (Array.isArray(v)) return v.map(canonical);
if (v && typeof v === "object")
return Object.fromEntries(Object.keys(v).sort().map((k) => [k, canonical((v as Record<string, unknown>)[k])]));
return v;
}
function hmacMatches(secret: string, input: string, signature: string | null): boolean {
if (!signature) return false;
const expected = Buffer.from(createHmac("sha256", secret).update(input, "utf8").digest("hex"));
const given = Buffer.from(signature.trim().toLowerCase());
return expected.length === given.length && timingSafeEqual(expected, given);
}
export function diditAgeProvider(config: DiditConfig): Provider {
const base = (config.baseURL ?? "https://verification.didit.me").replace(/\/+$/, "");
const fetcher = config.fetch ?? fetch;
const call = async (method: string, path: string, body?: unknown) => {
const res = await fetcher(base + path, {
method,
headers: { "x-api-key": config.apiKey, ...(body !== undefined ? { "Content-Type": "application/json" } : {}) },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!res.ok) throw new Error(`Didit ${method} ${path}: ${res.status} ${await res.text()}`);
return res.json();
};
return {
id: "didit",
label: "ID document and selfie",
vendor: "Didit",
scope: "person",
monthlyLimit: config.monthlyLimit,
async start(subject, { returnURL }) {
const s = (await call("POST", "/v3/session/", {
workflow_id: config.workflowId,
vendor_data: subject.userId,
callback: returnURL,
})) as { session_id: string; url: string };
return { kind: "redirect", url: s.url, ref: s.session_id };
},
async webhook(request) {
const raw = await request.text();
const timestamp = Number(request.headers.get("x-timestamp"));
if (!(Math.abs(Date.now() / 1000 - timestamp) <= timestampTolerance)) throw new Error("stale webhook");
const body = JSON.parse(raw) as {
webhook_type?: string;
session_id?: string;
status?: string;
decision?: Decision;
};
// The raw body's signature, else the V2 one (of the parsed body), each also with the previous secret's header
// during a rotation.
const v2 = JSON.stringify(canonical(body));
const signed = ["", "-previous"].some(
(suffix) =>
hmacMatches(config.webhookSecret, raw, request.headers.get(`x-signature${suffix}`)) ||
hmacMatches(config.webhookSecret, v2, request.headers.get(`x-signature-v2${suffix}`)),
);
if (!signed) throw new Error("bad signature");
if (body.webhook_type !== "status.updated" && body.webhook_type !== "data.updated") return null;
if (!body.session_id || !body.status) return null;
const ref = body.session_id;
if (failedStatuses.has(body.status)) return { ref, result: "failed" };
if (body.status !== "Approved") return null;
const decision =
body.decision ?? ((await call("GET", `/v3/session/${encodeURIComponent(ref)}/decision/`)) as Decision);
const age = documentAge(decision);
if (age === undefined) return { ref, result: "failed" };
const result: AgeResult = { overEighteen: age >= 18, method: "id_document", ref };
return { ref, result };
},
};
}
+1
View File
@@ -19,6 +19,7 @@ export function imvuAgeProvider(imvu: ImvuClient): Provider {
return {
id: "imvu",
label: "IMVU's age verification or Access Pass",
vendor: "IMVU",
scope: "imvu_account",
start: async (subject) => ({ kind: "done", result: await check(subject) }),
recheck: check,
+80 -17
View File
@@ -1,7 +1,7 @@
// Age verification, vendor-neutral: providers (IMVU, later phone wallets and Didit) plug in behind one interface,
// results go in one table (age_check), and one rule says whether an IMVU account counts as adult.
// See docs/design.md, "Age".
import { and, eq, gt, inArray, isNull, lte, or, schema, type Database } from "@t5de/db";
import { and, count, eq, gt, gte, inArray, isNull, lte, or, schema, type Database } from "@t5de/db";
const { ageCheck } = schema;
@@ -27,13 +27,19 @@ export type Started =
export type Provider = {
id: string;
/** Shown to people. */
/** Shown to people: the way of checking, and who does it. */
label: string;
vendor: string;
/** Whether it checks a person, or an IMVU account. */
scope: "person" | "imvu_account";
/** At most this many checks started each calendar month (UTC), for a provider's free allowance; none: no cap. */
monthlyLimit?: number;
start(subject: Subject, options: { returnURL: string }): Promise<Started>;
/** Finishes a check from the provider's webhook; throws if the request isn't really from the provider. */
webhook?(request: Request): Promise<{ ref: string; result: AgeResult | "failed" }>;
/**
* A check's answer from the provider's webhook, or null if it has none yet (still in progress or in review). Throws
* if the request isn't really from the provider.
*/
webhook?(request: Request): Promise<{ ref: string; result: AgeResult | "failed" } | null>;
/** Finishes a check the browser completed (wallets): the browser's response for ref. */
complete?(ref: string, response: unknown): Promise<AgeResult | "failed">;
/** Checks a subject again, for answers that can change. */
@@ -41,6 +47,12 @@ export type Provider = {
};
export class AgeError extends Error {}
/** A check that can't be started now; the message is for the person. */
export class AgeRefused extends Error {}
/** Checks of a person a provider will start for them in attemptWindow (failed and abandoned ones count). */
export const attemptsPerPerson = 3;
const attemptWindow = 30 * 24 * 60 * 60 * 1000;
const randomID = () => Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url");
@@ -56,7 +68,7 @@ export class AgeService {
/** The providers in use, for the website. */
list() {
return [...this.providers.values()].map((p) => ({ id: p.id, label: p.label, scope: p.scope }));
return [...this.providers.values()].map((p) => ({ id: p.id, label: p.label, vendor: p.vendor, scope: p.scope }));
}
provider(id: string): Provider {
@@ -87,13 +99,25 @@ export class AgeService {
await this.db.insert(ageCheck).values({ id: randomID(), ...values });
}
/** Begins a check with a provider; checks answered at once are recorded now, the rest stay pending. */
/**
* Begins a check with a provider; checks answered at once are recorded now, the rest stay pending. A person whose
* check is unfinished goes back to it (providers give the same session again); new checks of a person are
* limited, per person and by the provider's monthly allowance.
*/
async start(subject: Subject, providerId: string, returnURL: string): Promise<Started> {
const p = this.provider(providerId);
const ofPerson = subject.imvuId === undefined;
const pending = ofPerson ? await this.pendingCheck(subject.userId, p.id) : undefined;
if (ofPerson) {
if (await this.personAdult(subject.userId)) throw new AgeRefused("Your age is already verified.");
if (!pending) await this.checkLimits(subject.userId, p);
}
const started = await p.start(subject, { returnURL });
if (started.kind === "done") {
await this.record(subject, p.id, started.result);
} else {
} else if (pending?.providerRef !== started.ref) {
// An unfinished check the provider replaced with a new one (it expired there) won't be answered.
if (pending) await this.db.update(ageCheck).set({ status: "failed", checkedAt: new Date() }).where(eq(ageCheck.id, pending.id));
await this.db.insert(ageCheck).values({
id: randomID(),
userId: subject.userId,
@@ -106,11 +130,55 @@ export class AgeService {
return started;
}
/** Finishes a pending check (from a webhook or the browser). */
async finish(providerId: string, ref: string, result: AgeResult | "failed") {
private async pendingCheck(userId: string, provider: string) {
const [row] = await this.db
.select()
.from(ageCheck)
.where(
and(eq(ageCheck.userId, userId), eq(ageCheck.provider, provider), isNull(ageCheck.imvuId), eq(ageCheck.status, "pending")),
);
return row;
}
private async personAdult(userId: string) {
const now = new Date();
return (await this.personChecks(userId)).some(
(c) => c.status === "complete" && c.overEighteen && (c.expiresAt === null || c.expiresAt > now),
);
}
private async checkLimits(userId: string, p: Provider) {
const started = async (...where: Parameters<typeof and>) =>
(await this.db.select({ n: count() }).from(ageCheck).where(and(eq(ageCheck.provider, p.id), isNull(ageCheck.imvuId), ...where)))[0]!.n;
const since = new Date(Date.now() - attemptWindow);
if ((await started(eq(ageCheck.userId, userId), gte(ageCheck.createdAt, since))) >= attemptsPerPerson)
throw new AgeRefused(`You've started ${attemptsPerPerson} checks in the last 30 days. Try again later.`);
if (p.monthlyLimit !== undefined) {
const now = new Date();
const month = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
if ((await started(gte(ageCheck.createdAt, month))) >= p.monthlyLimit)
throw new AgeRefused("This month's ID checks are used up. Try again next month.");
}
}
/**
* Finishes a check. From the browser (wallets), only a pending check; from a provider's webhook (anyStatus), also
* one already answered, since the provider can change its answer (say, after a manual review). An adult answer
* taken back is revoked.
*/
async finish(providerId: string, ref: string, result: AgeResult | "failed", { anyStatus = false } = {}) {
const [row] = await this.db
.select()
.from(ageCheck)
.where(and(eq(ageCheck.provider, providerId), eq(ageCheck.providerRef, ref)));
if (!row || (!anyStatus && row.status !== "pending")) throw new AgeError("no such pending check");
const done =
result === "failed"
? { status: "failed", overEighteen: false, checkedAt: new Date() }
? {
status: (row.status === "complete" && row.overEighteen) || row.status === "revoked" ? "revoked" : "failed",
overEighteen: false,
checkedAt: new Date(),
}
: {
status: "complete",
overEighteen: result.overEighteen,
@@ -118,13 +186,8 @@ export class AgeService {
checkedAt: new Date(),
expiresAt: result.expiresAt ?? null,
};
const rows = await this.db
.update(ageCheck)
.set(done)
.where(and(eq(ageCheck.provider, providerId), eq(ageCheck.providerRef, ref), eq(ageCheck.status, "pending")))
.returning();
if (rows.length === 0) throw new AgeError("no such pending check");
return rows[0]!;
const [updated] = await this.db.update(ageCheck).set(done).where(eq(ageCheck.id, row.id)).returning();
return updated!;
}
/** Removes an IMVU account's checks (it was unlinked or moved to another person). */
+2333 -83
View File
File diff suppressed because it is too large. Load diff
+197 -13
View File
@@ -1,10 +1,14 @@
// Accounts, sessions and proxy sign-in, by Better Auth: email and password with usernames, roles and bans (admin),
// device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the proxy's requests, and JWTs with published keys
// (for catalogs later).
// Discord sign-in (basic accounts, docs/music.md), device sign-in for T5DE's proxy (RFC 8628), bearer tokens for the
// proxy's requests, JWTs with published keys, two-factor sign-in (an authenticator app, with backup codes), and the
// hub as an OAuth 2.1 / OpenID Connect provider for T5DE's own sites (Music first).
import { timingSafeEqual } from "node:crypto";
import { oauthProvider } from "@better-auth/oauth-provider";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { admin, bearer, deviceAuthorization, jwt, username } from "better-auth/plugins";
import { count, schema, type Database } from "@t5de/db";
import { admin, bearer, deviceAuthorization, jwt, twoFactor, username } from "better-auth/plugins";
import { and, asc, count, eq, schema, type Database } from "@t5de/db";
import { Settings } from "./settings";
export type AuthConfig = {
/** The API's own address, e.g. https://hub-api.t5de.dev. */
@@ -15,22 +19,121 @@ export type AuthConfig = {
secret: string;
/** Rate limits on sign-up, sign-in and the rest (on unless false: tests turn them off). */
rateLimit?: boolean;
/** Whether new accounts wait for approval (default: the hub's settings, with no environment defaults). */
settings?: Settings;
/** Discord sign-in (an application at discord.com/developers, redirecting to API_URL/api/auth/callback/discord);
* off without it. */
discord?: { clientId: string; clientSecret: string };
/** T5DE's own sites that sign people in through the hub (OpenID Connect): trusted, so there's no consent screen,
* and they may ask for the `imvu` scope. Made or updated at startup (seedClients). */
clients?: FirstPartyClient[];
/** Let clients use plain-HTTP redirect URIs on localhost (development only: a client running locally). */
localRedirects?: boolean;
};
/** A T5DE site that signs people in through the hub. */
export type FirstPartyClient = {
/** e.g. t5de-music */
clientId: string;
/** Shown to people, e.g. T5DE Music */
name: string;
/** At least 32 random characters; the hub keeps only its hash. */
secret: string;
/** Where the hub may send people back with a code, e.g. https://music.t5de.dev/api/auth/callback */
redirectUris: string[];
};
/**
* What OpenID Connect clients may ask for. `imvu`: the person's linked IMVU accounts, real IDs and names (first-party
* sites only: they act in IMVU rooms). `imvu:link`: link and unlink IMVU accounts on the person's behalf, through the
* hub's API.
*/
export const oauthScopes = ["openid", "profile", "email", "offline_access", "imvu", "imvu:link"] as const;
/** The hub's own API as an OAuth resource: access tokens for it (`resource` in the request) are JWTs it checks. */
export const hubResource = (apiURL: string) => `${apiURL.replace(/\/+$/, "")}/api/v1`;
/** How client secrets are kept (SHA-256, base64url); seedClients stores first-party secrets the same way. */
async function hashSecret(secret: string): Promise<string> {
return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret))).toString("base64url");
}
async function verifySecret(secret: string, stored: string): Promise<boolean> {
const a = Buffer.from(await hashSecret(secret));
const b = Buffer.from(stored);
return a.length === b.length && timingSafeEqual(a, b);
}
/** A person's linked IMVU accounts, as the `imvu` claim gives them. */
async function imvuClaim(db: Database, userId: string) {
return db
.select({ id: schema.imvuLink.imvuId, username: schema.imvuLink.username })
.from(schema.imvuLink)
.where(eq(schema.imvuLink.userId, userId))
.orderBy(asc(schema.imvuLink.linkedAt));
}
/** The proxy's client ID in device sign-in. */
export const proxyClientID = "t5de-proxy";
/** Usernames: letters, digits and underscores; imvu_<ID> is reserved for unclaimed creators (docs/imports.md). */
export const usernameRules = { min: 3, max: 32 };
export const validUsername = (name: string) =>
name.length >= usernameRules.min &&
name.length <= usernameRules.max &&
/^[A-Za-z0-9_]+$/.test(name) &&
!/^imvu_/i.test(name);
/** Passwords' lengths (Better Auth's emailAndPassword). */
export const passwordRules = { min: 10, max: 256 };
/** Errors Discord sign-in can end with, as Better Auth names them (the website shows a sentence for each). */
export const discordErrors = {
/** The Discord account's email isn't verified, or it has none (phone-only accounts). */
emailNotVerified: "email_not_verified",
} as const;
export function createAuth(db: Database, config: AuthConfig) {
const settings = config.settings ?? new Settings(db);
return betterAuth({
baseURL: config.apiURL,
basePath: "/api/auth",
secret: config.secret,
trustedOrigins: [config.webURL],
database: drizzleAdapter(db, { provider: "pg", schema }),
emailAndPassword: { enabled: true, minPasswordLength: 10, maxPasswordLength: 256 },
// The JWT plugin's /token (a session as a JWT) is off: the OAuth provider issues tokens instead.
disabledPaths: ["/token"],
emailAndPassword: { enabled: true, minPasswordLength: passwordRules.min, maxPasswordLength: passwordRules.max },
socialProviders: config.discord
? { discord: { clientId: config.discord.clientId, clientSecret: config.discord.clientSecret } }
: {},
account: {
accountLinking: {
enabled: true,
// Never link or merge by matching email: Discord is linked to an account only from that account's own
// session (Account page). Otherwise anyone who puts a member's address on a Discord account could sign in
// as them. A Discord sign-in whose email belongs to an account it isn't linked to ends with
// `account_not_linked`.
disableImplicitLinking: true,
// A member's Discord account may use another address than the member does.
allowDifferentEmails: true,
// A basic account's only way in is Discord: it can't be unlinked.
allowUnlinkingAll: false,
},
},
user: {
additionalFields: {
linkCap: { type: "number", defaultValue: 10, input: false },
approved: { type: "boolean", defaultValue: true, input: false },
kind: { type: "string", defaultValue: "member", input: false },
},
// A new account from Discord takes Discord's email, and only a verified one.
validateUserInfo: ({ user, source }) => {
if (source.action !== "create-user" || source.method !== "oauth") return;
if (!user.email || user.emailVerified !== true)
return {
error: discordErrors.emailNotVerified,
errorDescription: "Verify your email in Discord, then sign in again.",
};
},
},
// Proxies stay signed in for months; a session is extended when it's used.
@@ -40,19 +143,26 @@ export function createAuth(db: Database, config: AuthConfig) {
databaseHooks: {
user: {
create: {
// The first account runs the hub.
before: async (u) => {
const [row] = await db.select({ n: count() }).from(schema.user);
return { data: { ...u, role: (row?.n ?? 0) === 0 ? "admin" : "user" } };
before: async (u, ctx) => {
// Made by signing in with Discord (the OAuth callback): a basic account. It can use T5DE's other sites
// at once; the hub's features wait until it finishes setting up (and then for approval, if registration
// is closed).
if (ctx?.path?.startsWith("/callback/"))
return { data: { ...u, role: "user", approved: true, kind: "basic" } };
// The first member runs the hub; with registration closed, the others wait for approval.
const [row] = await db.select({ n: count() }).from(schema.user).where(eq(schema.user.kind, "member"));
const first = (row?.n ?? 0) === 0;
const approved = first || (await settings.registration()) === "open";
return { data: { ...u, role: first ? "admin" : "user", approved, kind: "member" } };
},
},
},
},
plugins: [
username({
minUsernameLength: 3,
maxUsernameLength: 32,
usernameValidator: (name) => /^[A-Za-z0-9_]+$/.test(name),
minUsernameLength: usernameRules.min,
maxUsernameLength: usernameRules.max,
usernameValidator: validUsername,
}),
admin({ defaultRole: "user", adminRoles: ["admin"] }),
deviceAuthorization({
@@ -62,9 +172,83 @@ export function createAuth(db: Database, config: AuthConfig) {
validateClient: (clientId) => clientId === proxyClientID,
}),
bearer(),
jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } } }),
// Once it's on, signing in asks for a code from the app (or a backup code). The hub's own routes require it for
// sensitive permissions (permissions.ts `sensitive`).
twoFactor({ issuer: "T5DE", backupCodeOptions: { amount: 10, length: 10 } }),
jwt({ jwks: { keyPairConfig: { alg: "EdDSA", crv: "Ed25519" } }, disableSettingJwtHeader: true }),
// The issuer is API_URL/api/auth (discovery at /api/auth/.well-known/openid-configuration). People sign in on the
// website's /signin, which sends them back to the authorize endpoint; trusted clients skip /consent.
oauthProvider({
loginPage: `${config.webURL}/signin`,
consentPage: `${config.webURL}/consent`,
scopes: [...oauthScopes],
cachedTrustedClients: new Set((config.clients ?? []).map((c) => c.clientId)),
storeClientSecret: { hash: hashSecret, verify: verifySecret },
allowInsecureRedirectUri: (url) => config.localRedirects === true && ["localhost", "127.0.0.1"].includes(url.hostname),
resources: [{ identifier: hubResource(config.apiURL), name: "T5DE Hub API", allowedScopes: [...oauthScopes] }],
advertisedMetadata: {
scopes_supported: [...oauthScopes],
claims_supported: [
"sub", "iss", "aud", "exp", "iat", "sid", "scope", "azp",
"name", "preferred_username", "email", "email_verified", "picture", "imvu",
],
},
customUserInfoClaims: async ({ user, scopes }) => ({
...(scopes.includes("profile") && typeof user.username === "string"
? { preferred_username: typeof user.displayUsername === "string" ? user.displayUsername : user.username }
: {}),
...(scopes.includes("imvu") ? { imvu: await imvuClaim(db, user.id) } : {}),
}),
customIdTokenClaims: async ({ user, scopes }) => (scopes.includes("imvu") ? { imvu: await imvuClaim(db, user.id) } : {}),
}),
],
});
}
export type Auth = ReturnType<typeof createAuth>;
/**
* Makes or updates T5DE's own sites as OAuth clients: their secret's hash, redirect URIs and scopes, trusted (no
* consent screen), and allowed to ask for tokens for the hub's API. Run at startup, before serving.
*/
export async function seedClients(db: Database, apiURL: string, clients: FirstPartyClient[]) {
const now = new Date();
const resource = hubResource(apiURL);
for (const c of clients) {
if (c.secret.length < 32) throw new Error(`${c.clientId}: the client secret needs at least 32 characters`);
if (c.redirectUris.length === 0) throw new Error(`${c.clientId}: no redirect URIs`);
const values = {
clientSecret: await hashSecret(c.secret),
name: c.name,
redirectUris: c.redirectUris,
scopes: [...oauthScopes],
skipConsent: true,
disabled: false,
subjectType: "public",
tokenEndpointAuthMethod: "client_secret_basic",
grantTypes: ["authorization_code", "refresh_token"],
responseTypes: ["code"],
applicationType: "web",
requirePKCE: true,
updatedAt: now,
};
await db
.insert(schema.oauthClient)
.values({ id: crypto.randomUUID(), clientId: c.clientId, createdAt: now, ...values })
.onConflictDoUpdate({ target: schema.oauthClient.clientId, set: values });
}
// Each may ask for tokens for the hub's API (the plugin checks this link). The resource row is the plugin's
// (`resources` above, made when it starts); made here too in case this runs first.
await db
.insert(schema.oauthResource)
.values({ id: crypto.randomUUID(), identifier: resource, name: "T5DE Hub API", allowedScopes: [...oauthScopes], createdAt: now, updatedAt: now })
.onConflictDoNothing({ target: schema.oauthResource.identifier });
for (const c of clients) {
const [linked] = await db
.select({ id: schema.oauthClientResource.id })
.from(schema.oauthClientResource)
.where(and(eq(schema.oauthClientResource.clientId, c.clientId), eq(schema.oauthClientResource.resourceId, resource)));
if (!linked)
await db.insert(schema.oauthClientResource).values({ id: crypto.randomUUID(), clientId: c.clientId, resourceId: resource, createdAt: now });
}
}
+113
View File
@@ -0,0 +1,113 @@
// File blocks (docs/products.md): moderation blocks a file network-wide by its sha256, so a removed product can't
// come back under another name. Revisions with a blocked file can't be registered, products using it are removed,
// and the catalogs hosting it are told to delete it. The routes in app.ts check permissions, audit and notify.
import { and, desc, eq, inArray, isNull, lt, sql, schema, type Database } from "@t5de/db";
import { ProductError } from "./products";
const { catalogChange, fileBlock, hosting, product, productRevision, user } = schema;
export const isSha256 = (s: string) => /^[0-9a-f]{64}$/.test(s);
/** A product with a revision using a file. */
export type FileUse = {
id: string;
name: string;
creatorId: string;
creatorUsername: string | null;
removed: boolean;
revisions: number[];
};
export class Blocks {
constructor(private db: Database) {}
async get(sha256: string) {
const [b] = await this.db
.select({ block: fileBlock, by: user.username })
.from(fileBlock)
.leftJoin(user, eq(user.id, fileBlock.byId))
.where(eq(fileBlock.sha256, sha256));
return b;
}
/** Which of these files are blocked. */
async blocked(sha256s: string[]): Promise<string[]> {
if (sha256s.length === 0) return [];
const rows = await this.db.select({ sha256: fileBlock.sha256 }).from(fileBlock).where(inArray(fileBlock.sha256, sha256s));
return rows.map((r) => r.sha256);
}
/** The products with a revision using a file (what blocking it would remove), newest first. */
async usedBy(sha256: string): Promise<FileUse[]> {
const rows = await this.db
.select({ p: product, creatorUsername: user.username, number: productRevision.number })
.from(productRevision)
.innerJoin(product, eq(product.id, productRevision.productId))
.leftJoin(user, eq(user.id, product.creatorId))
.where(sql`${productRevision.files} @> ${JSON.stringify([{ sha256 }])}::jsonb`)
.orderBy(desc(product.createdAt), productRevision.number);
const out = new Map<string, FileUse>();
for (const r of rows) {
if (r.p.deletedAt && !r.p.removedAt) continue; // deleted by its creator: nothing to remove
const u = out.get(r.p.id) ?? {
id: r.p.id,
name: r.p.name,
creatorId: r.p.creatorId,
creatorUsername: r.creatorUsername,
removed: r.p.removedAt !== null,
revisions: [],
};
u.revisions.push(r.number);
out.set(r.p.id, u);
}
return [...out.values()];
}
/**
* Blocks a file: removes the products using it (those not removed already, which are returned) and tells the
* catalogs hosting it to delete it (a `block` change).
*/
async block(sha256: string, reason: string, byId: string): Promise<FileUse[]> {
if (!isSha256(sha256)) throw new ProductError(400, "invalid", "That isn't a file's sha256 (64 hex digits).");
const uses = await this.usedBy(sha256);
const ids = uses.map((u) => u.id);
const removed = uses.filter((u) => !u.removed);
await this.db.transaction(async (tx) => {
const [made] = await tx.insert(fileBlock).values({ sha256, reason, byId }).onConflictDoNothing().returning();
if (!made) throw new ProductError(409, "blocked", "That file is blocked already.");
if (removed.length)
await tx
.update(product)
.set({ removedAt: new Date(), removedReason: reason })
.where(and(inArray(product.id, removed.map((u) => u.id)), isNull(product.removedAt)));
if (ids.length) {
const hosts = await tx
.selectDistinct({ catalogId: hosting.catalogId })
.from(hosting)
.innerJoin(productRevision, and(eq(productRevision.productId, hosting.productId), eq(productRevision.number, hosting.number)))
.where(and(inArray(hosting.productId, ids), sql`${productRevision.files} @> ${JSON.stringify([{ sha256 }])}::jsonb`));
if (hosts.length) await tx.insert(catalogChange).values(hosts.map((h) => ({ catalogId: h.catalogId, data: { type: "block", sha256 } })));
}
});
return removed;
}
/** Unblocks a file. Products it removed stay removed (moderators restore them one by one); catalogs aren't told,
* since they deleted the file and get it again only with a new upload. */
async unblock(sha256: string) {
const [gone] = await this.db.delete(fileBlock).where(eq(fileBlock.sha256, sha256)).returning();
if (!gone) throw new ProductError(404, "not_found", "That file isn't blocked.");
return gone;
}
/** Blocks, newest first. */
async list(opts: { before?: Date; limit?: number } = {}) {
return this.db
.select({ block: fileBlock, by: user.username })
.from(fileBlock)
.leftJoin(user, eq(user.id, fileBlock.byId))
.where(opts.before ? lt(fileBlock.createdAt, opts.before) : undefined)
.orderBy(desc(fileBlock.createdAt))
.limit(opts.limit ?? 50);
}
}
+231
View File
@@ -0,0 +1,231 @@
// Cases (docs/console.md): one queue for everything someone has to decide. Reports, rating reviews, removal
// requests, catalogs' deletion requests and appeals. The routes in app.ts check who may open one and carry out a
// decision's effects; this keeps the cases, their threads, and who may see and decide them.
import { and, count, desc, eq, gt, inArray, lt, or, sql, schema, type AuditTags, type Database } from "@t5de/db";
import { ProductError } from "./products";
import { Permissions, type Permission, type Who } from "./permissions";
const { caseNote, catalog, hosting, moderationCase, product, user } = schema;
export const caseKinds = ["report", "rating-review", "removal-request", "catalog-deletion", "appeal"] as const;
export type CaseKind = (typeof caseKinds)[number];
export type Case = typeof moderationCase.$inferSelect;
/** The permission that decides each kind of case (moderators hold them hub-wide). */
const decidedWith: Record<CaseKind, Permission> = {
report: "case:resolve",
"rating-review": "product:rate-lower",
"removal-request": "product:remove",
"catalog-deletion": "catalog:delete-review",
appeal: "case:resolve",
};
/** The actions people can appeal, and whom they affect: a product's creator, a catalog's owner, or the person. */
export const appealable: Record<string, "creator" | "owner" | "person"> = {
"product.remove": "creator",
"product.edit": "creator",
"product.lock": "creator",
"product.revert": "creator",
"catalog.delist": "creator",
"catalog.suspend": "owner",
"catalog.reject": "owner",
"catalog.member_ban": "person",
"catalog.member_decline": "person",
};
/** Reports a person may open in an hour. */
export const reportsPerHour = 10;
export class Cases {
constructor(
private readonly db: Database,
private readonly perms: Permissions,
) {}
async get(id: number): Promise<Case> {
const [c] = await this.db.select().from(moderationCase).where(eq(moderationCase.id, id));
if (!c) throw new ProductError(404, "not_found", "No such case.");
return c;
}
/** The open case of a kind about a resource (one each), if any; with `openedBy`, only theirs. */
async findOpen(kind: CaseKind, tags: AuditTags, openedBy?: string): Promise<Case | undefined> {
const conds = [eq(moderationCase.kind, kind), eq(moderationCase.status, "open")];
for (const [k, v] of Object.entries(tags)) if (v) conds.push(sql`${moderationCase.tags}->>${k} = ${v}`);
if (openedBy) conds.push(eq(moderationCase.openedBy, openedBy));
const [c] = await this.db.select().from(moderationCase).where(and(...conds)).limit(1);
return c;
}
async open(kind: CaseKind, openedBy: string, tags: AuditTags, reason: string, data: Record<string, unknown> = {}) {
const [c] = await this.db
.insert(moderationCase)
.values({ kind, openedBy, tags, reason: reason.trim().slice(0, 2000), data })
.returning();
return c!;
}
/** A report: at most reportsPerHour an hour, and one open report per person and resource. */
async report(openedBy: string, tags: AuditTags, reason: string) {
if (!reason.trim()) throw new ProductError(400, "reason_needed", "Say what's wrong.");
const since = new Date(Date.now() - 60 * 60 * 1000);
const [recent] = await this.db
.select({ n: count() })
.from(moderationCase)
.where(and(eq(moderationCase.kind, "report"), eq(moderationCase.openedBy, openedBy), gt(moderationCase.createdAt, since)));
if ((recent?.n ?? 0) >= reportsPerHour)
throw new ProductError(429, "rate_limited", "That's a lot of reports. Try again in an hour.");
if (await this.findOpen("report", tags, openedBy))
throw new ProductError(409, "already_reported", "You reported that already; moderators will look at it.");
return this.open("report", openedBy, tags, reason);
}
/** The catalogs hosting a product (whose teams decide reports about it). */
private async hostsOf(productId: string): Promise<string[]> {
const rows = await this.db.selectDistinct({ id: hosting.catalogId }).from(hosting).where(eq(hosting.productId, productId));
return rows.map((r) => r.id);
}
/**
* Whether someone may decide a case: moderators by the kind's permission (an appeal by a different moderator than
* the one who acted, unless an admin, flagged in the audit log); reports about a product also its hosting catalogs'
* teams (case:resolve there).
*/
async canDecide(who: Who, c: Case): Promise<boolean> {
const perm = decidedWith[c.kind as CaseKind];
if (!perm) return false;
if (this.perms.hub(who).has(perm)) return !(c.kind === "appeal" && c.data.actorId === who.id && who.role !== "admin");
if (c.kind === "report" && c.tags.product)
for (const id of await this.hostsOf(c.tags.product))
if (await this.perms.can(who, "case:resolve", { type: "catalog", id })) return true;
return false;
}
/** Whether someone may see a case: its opener, its assignee, those deciding it, and (but for reports, which keep
* who reported private) those with case:read at what it's about. */
async canSee(who: Who, c: Case): Promise<boolean> {
if (c.openedBy === who.id || c.assignee === who.id) return true;
if (this.perms.hub(who).has("case:read") || (await this.canDecide(who, c))) return true;
if (c.kind === "report") return false;
if (c.tags.catalog && (await this.perms.can(who, "case:read", { type: "catalog", id: c.tags.catalog }))) return true;
if (c.tags.product && (await this.perms.can(who, "case:read", { type: "product", id: c.tags.product }))) return true;
return false;
}
/** The cases a person may see (as canSee), newest first. */
async list(who: Who, f: { status?: string; kind?: string; mine?: boolean; before?: number; limit?: number }) {
const conds = [];
if (f.mine) conds.push(eq(moderationCase.openedBy, who.id));
else if (!this.perms.hub(who).has("case:read")) {
const teams = await this.perms.teamCatalogs(who.id);
const own = await this.perms.ownProducts(who.id);
const visible = [eq(moderationCase.openedBy, who.id), eq(moderationCase.assignee, who.id)];
if (teams.length) {
visible.push(and(sql`${moderationCase.kind} <> 'report'`, inArray(sql`${moderationCase.tags}->>'catalog'`, teams))!);
visible.push(
and(
eq(moderationCase.kind, "report"),
sql`exists (select 1 from ${hosting} h where h.product_id = ${moderationCase.tags}->>'product' and h.catalog_id in ${teams})`,
)!,
);
}
if (own.length)
visible.push(and(sql`${moderationCase.kind} <> 'report'`, inArray(sql`${moderationCase.tags}->>'product'`, own))!);
conds.push(or(...visible)!);
}
if (f.status) conds.push(eq(moderationCase.status, f.status));
if (f.kind) conds.push(eq(moderationCase.kind, f.kind));
if (f.before) conds.push(lt(moderationCase.id, f.before));
return this.db
.select()
.from(moderationCase)
.where(conds.length ? and(...conds) : undefined)
.orderBy(desc(moderationCase.id))
.limit(Math.max(1, Math.min(f.limit ?? 50, 200)));
}
/** People's usernames and resources' names for cases (to show and link them). */
async names(cases: Case[]) {
const people = new Set<string>();
const products = new Set<string>();
const catalogs = new Set<string>();
for (const c of cases) {
for (const p of [c.openedBy, c.assignee, c.decidedBy, c.tags.person]) if (p) people.add(p);
if (c.tags.product) products.add(c.tags.product);
if (c.tags.catalog) catalogs.add(c.tags.catalog);
}
const [ps, prs, cs] = await Promise.all([
people.size
? this.db.select({ id: user.id, name: user.displayUsername, username: user.username }).from(user).where(inArray(user.id, [...people]))
: [],
products.size ? this.db.select({ id: product.id, name: product.name }).from(product).where(inArray(product.id, [...products])) : [],
catalogs.size ? this.db.select({ id: catalog.id, name: catalog.name }).from(catalog).where(inArray(catalog.id, [...catalogs])) : [],
]);
const names: Record<string, string> = {};
for (const p of ps) names[p.id] = p.name ?? p.username ?? "";
for (const x of [...prs, ...cs]) names[x.id] = x.name;
return names;
}
async decide(c: Case, by: string, status: "resolved" | "declined", resolution: string) {
if (c.status !== "open") throw new ProductError(409, "decided", "That case is decided already.");
const [updated] = await this.db
.update(moderationCase)
.set({ status, resolution: resolution.trim().slice(0, 2000), decidedBy: by, decidedAt: new Date() })
.where(and(eq(moderationCase.id, c.id), eq(moderationCase.status, "open")))
.returning();
if (!updated) throw new ProductError(409, "decided", "That case is decided already.");
return updated;
}
async assign(c: Case, assignee: string | null) {
const [updated] = await this.db.update(moderationCase).set({ assignee }).where(eq(moderationCase.id, c.id)).returning();
return updated!;
}
async notes(c: Case, internalToo: boolean) {
return this.db
.select({
id: caseNote.id,
by: user.displayUsername,
byId: caseNote.byId,
body: caseNote.body,
internal: caseNote.internal,
at: caseNote.createdAt,
})
.from(caseNote)
.leftJoin(user, eq(user.id, caseNote.byId))
.where(and(eq(caseNote.caseId, c.id), internalToo ? undefined : eq(caseNote.internal, false)))
.orderBy(caseNote.id);
}
async addNote(c: Case, byId: string, body: string, internal: boolean) {
body = body.trim().slice(0, 4000);
if (!body) throw new ProductError(400, "invalid", "Write something.");
await this.db.insert(caseNote).values({ caseId: c.id, byId, body, internal });
await this.db.update(moderationCase).set({ updatedAt: new Date() }).where(eq(moderationCase.id, c.id));
}
/** Open cases a person could decide (for the console's to-dos): every one for moderators, else reports about
* products their catalogs host. */
async openToDecide(who: Who): Promise<number> {
const open = eq(moderationCase.status, "open");
if (this.perms.hub(who).has("case:resolve")) {
const [row] = await this.db.select({ n: count() }).from(moderationCase).where(open);
return row?.n ?? 0;
}
const teams = await this.perms.teamCatalogs(who.id);
if (!teams.length) return 0;
const [row] = await this.db
.select({ n: count() })
.from(moderationCase)
.where(
and(
open,
eq(moderationCase.kind, "report"),
sql`exists (select 1 from ${hosting} h where h.product_id = ${moderationCase.tags}->>'product' and h.catalog_id in ${teams})`,
),
);
return row?.n ?? 0;
}
}
+400
View File
@@ -0,0 +1,400 @@
// Managing catalogs (docs/products.md, docs/console.md): settings, keys, teams, members, invites, what they host,
// suspension, and the changes feed catalogs poll. Permission checks are the routes'; this is what they do.
import { createHash } from "node:crypto";
import { and, asc, count, desc, eq, gt, inArray, isNull, or, sql, schema, type Database } from "@t5de/db";
import { ProductError } from "./products";
const { catalog, catalogChange, catalogInvite, catalogMember, hosting, product, productRevision, roleAssignment, user } =
schema;
export type Catalog = typeof catalog.$inferSelect;
export type MemberStatus = "requested" | "member" | "banned";
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
const randomKey = () => Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("base64url");
// Invite codes: 10 letters and digits without look-alikes.
const inviteCode = () => {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
return [...crypto.getRandomValues(new Uint8Array(10))].map((b) => alphabet[b % alphabet.length]).join("");
};
const plain = (s: unknown, max: number) => {
const v = typeof s === "string" ? s.trim() : "";
// eslint-disable-next-line no-control-regex
if (!v || v.length > max || /[\u0000-\u001f\u007f]/.test(v)) return undefined;
return v;
};
/** A catalog's address, checked and without a trailing slash (https, or localhost for development). */
export function catalogURL(input: string): string {
let url: URL;
try {
url = new URL(input);
} catch {
throw new ProductError(400, "invalid", "That address isn't a URL.");
}
if (url.protocol !== "https:" && url.hostname !== "localhost" && url.hostname !== "127.0.0.1")
throw new ProductError(400, "invalid", "Catalogs need an https address.");
return url.origin + url.pathname.replace(/\/+$/, "");
}
export type CatalogSettings = {
name?: string;
url?: string;
contact?: string;
visibility?: "public" | "private";
membership?: "open" | "approval" | "invite";
maxRating?: "general" | "adult";
uploads?: "anyone" | "members" | "team";
mirrors?: "auto" | "approve" | "off";
};
export class Catalogs {
constructor(
private readonly db: Database,
/** Whether a catalog answers at an address (its /health); checked when its address changes. */
private readonly healthy: (url: string) => Promise<boolean> = defaultHealthy,
) {}
async get(id: string): Promise<Catalog> {
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, id));
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c;
}
/** Changes a catalog's settings; returns the catalog and the fields that changed (old and new values). */
async update(id: string, input: CatalogSettings) {
const c = await this.get(id);
const set: Partial<Catalog> = {};
if (input.name !== undefined) {
const name = plain(input.name, 64);
if (!name) throw new ProductError(400, "invalid", "Names are 1-64 characters.");
set.name = name;
}
if (input.contact !== undefined) {
const contact = plain(input.contact, 200);
if (!contact) throw new ProductError(400, "invalid", "A takedown contact is needed.");
set.contact = contact;
}
if (input.url !== undefined) {
const url = catalogURL(input.url);
if (url !== c.url) {
const [taken] = await this.db.select({ id: catalog.id }).from(catalog).where(eq(catalog.url, url));
if (taken) throw new ProductError(409, "taken", "A catalog at that address is already registered.");
if (!(await this.healthy(url)))
throw new ProductError(400, "unreachable", "Nothing answered at that address's /health. Is the catalog running there?");
set.url = url;
}
}
for (const k of ["visibility", "membership", "maxRating", "uploads", "mirrors"] as const)
if (input[k] !== undefined) (set as Record<string, unknown>)[k] = input[k];
const changed: Record<string, { from: unknown; to: unknown }> = {};
for (const [k, v] of Object.entries(set)) {
const before = (c as Record<string, unknown>)[k];
if (before !== v) changed[k] = { from: before, to: v };
}
if (Object.keys(changed).length === 0) return { catalog: c, changed };
const [updated] = await this.db.update(catalog).set(set).where(eq(catalog.id, id)).returning();
return { catalog: updated!, changed };
}
/** A new key for the catalog; the old one stops working at once. */
async rotateKey(id: string): Promise<string> {
await this.get(id);
const key = randomKey();
await this.db.update(catalog).set({ keyHash: sha256(key) }).where(eq(catalog.id, id));
return key;
}
/** Suspends or reinstates an approved catalog; tells it through its changes feed. */
async setSuspended(id: string, suspended: boolean, reason: string) {
const c = await this.get(id);
if (suspended && c.status !== "approved")
throw new ProductError(409, "not_approved", "Only an approved catalog can be suspended.");
if (!suspended && c.status !== "suspended") throw new ProductError(409, "not_suspended", "That catalog isn't suspended.");
const status = suspended ? "suspended" : "approved";
const [updated] = await this.db
.update(catalog)
.set({ status, statusReason: suspended ? reason : "" })
.where(eq(catalog.id, id))
.returning();
await this.change(id, { type: "status", status });
return updated!;
}
/** Deletes a catalog (after a moderator accepted its deletion request): it stays on record as deleted, nothing
* is available from it, and it learns so from its changes feed. */
async markDeleted(id: string, reason: string) {
await this.get(id);
const [updated] = await this.db
.update(catalog)
.set({ status: "deleted", statusReason: reason })
.where(eq(catalog.id, id))
.returning();
await this.change(id, { type: "status", status: "deleted" });
return updated!;
}
// ---- teams ----
async addRole(catalogId: string, personId: string, role: string, by: string) {
const c = await this.get(catalogId);
if (c.ownerId === personId) throw new ProductError(409, "owner", "That's the catalog's owner.");
await this.db
.insert(roleAssignment)
.values({ userId: personId, role, scopeType: "catalog", scopeId: catalogId, grantedBy: by })
.onConflictDoNothing();
}
async removeRole(catalogId: string, personId: string, role: string) {
const gone = await this.db
.delete(roleAssignment)
.where(
and(
eq(roleAssignment.userId, personId),
eq(roleAssignment.role, role),
eq(roleAssignment.scopeType, "catalog"),
eq(roleAssignment.scopeId, catalogId),
),
)
.returning();
if (gone.length === 0) throw new ProductError(404, "not_found", "They don't have that role here.");
}
// ---- members ----
async membership(catalogId: string, personId: string): Promise<MemberStatus | undefined> {
const [m] = await this.db
.select({ status: catalogMember.status })
.from(catalogMember)
.where(and(eq(catalogMember.catalogId, catalogId), eq(catalogMember.userId, personId)));
return m?.status as MemberStatus | undefined;
}
/**
* A person joins: an open catalog at once, an approval one as a request, an invite one only with an invite (which
* also lets them into approval catalogs at once). Returns their status.
*/
async join(catalogId: string, personId: string, invite?: string): Promise<MemberStatus> {
const c = await this.get(catalogId);
if (c.status !== "approved") throw new ProductError(404, "not_found", "No such catalog.");
const now = await this.membership(catalogId, personId);
if (now === "banned") throw new ProductError(403, "banned", "This catalog's team banned you from it.");
if (now === "member") return "member";
let status: MemberStatus;
let usedInvite: string | null = null;
if (invite) {
const updated = await this.db
.update(catalogInvite)
.set({ uses: sql`${catalogInvite.uses} + 1` })
.where(
and(
eq(catalogInvite.code, invite),
eq(catalogInvite.catalogId, catalogId),
isNull(catalogInvite.revokedAt),
or(isNull(catalogInvite.expiresAt), gt(catalogInvite.expiresAt, new Date())),
or(isNull(catalogInvite.maxUses), sql`${catalogInvite.uses} < ${catalogInvite.maxUses}`),
),
)
.returning();
if (updated.length === 0) throw new ProductError(410, "invite_invalid", "That invitation is used up, expired or revoked.");
status = "member";
usedInvite = invite;
} else if (c.membership === "open") status = "member";
else if (c.membership === "approval") status = "requested";
else throw new ProductError(403, "invite_only", "This catalog takes members by invitation only.");
await this.db
.insert(catalogMember)
.values({ catalogId, userId: personId, status, invite: usedInvite })
.onConflictDoUpdate({ target: [catalogMember.catalogId, catalogMember.userId], set: { status, invite: usedInvite } });
return status;
}
/** A person leaves (or withdraws their request). A ban stays. */
async leave(catalogId: string, personId: string) {
await this.db
.delete(catalogMember)
.where(
and(eq(catalogMember.catalogId, catalogId), eq(catalogMember.userId, personId), sql`${catalogMember.status} <> 'banned'`),
);
}
async members(catalogId: string, status?: MemberStatus) {
const conds = [eq(catalogMember.catalogId, catalogId)];
if (status) conds.push(eq(catalogMember.status, status));
const rows = await this.db
.select({
personId: catalogMember.userId,
username: user.username,
name: user.displayUsername,
status: catalogMember.status,
invite: catalogMember.invite,
since: catalogMember.updatedAt,
})
.from(catalogMember)
.innerJoin(user, eq(user.id, catalogMember.userId))
.where(and(...conds))
.orderBy(desc(catalogMember.updatedAt))
.limit(500);
return rows.map((r) => ({
personId: r.personId,
username: r.name ?? r.username ?? "",
status: r.status as MemberStatus,
invited: r.invite !== null,
since: r.since.toISOString(),
}));
}
async memberCounts(catalogId: string) {
const rows = await this.db
.select({ status: catalogMember.status, n: count() })
.from(catalogMember)
.where(eq(catalogMember.catalogId, catalogId))
.groupBy(catalogMember.status);
const get = (s: string) => rows.find((r) => r.status === s)?.n ?? 0;
return { members: get("member"), requests: get("requested"), banned: get("banned") };
}
/** The team sets a person's membership: let them in, or ban them. */
async setMember(catalogId: string, personId: string, status: "member" | "banned", by: string) {
await this.get(catalogId);
await this.db
.insert(catalogMember)
.values({ catalogId, userId: personId, status, decidedBy: by })
.onConflictDoUpdate({ target: [catalogMember.catalogId, catalogMember.userId], set: { status, decidedBy: by } });
}
async removeMember(catalogId: string, personId: string) {
const gone = await this.db
.delete(catalogMember)
.where(and(eq(catalogMember.catalogId, catalogId), eq(catalogMember.userId, personId)))
.returning();
if (gone.length === 0) throw new ProductError(404, "not_found", "They aren't a member, and haven't asked to be.");
}
// ---- invites ----
async createInvite(catalogId: string, by: string, opts: { maxUses?: number; expiresInDays?: number }) {
await this.get(catalogId);
const [inv] = await this.db
.insert(catalogInvite)
.values({
code: inviteCode(),
catalogId,
createdBy: by,
maxUses: opts.maxUses ?? null,
expiresAt: opts.expiresInDays ? new Date(Date.now() + opts.expiresInDays * 86_400_000) : null,
})
.returning();
return inv!;
}
async invites(catalogId: string) {
return this.db
.select()
.from(catalogInvite)
.where(and(eq(catalogInvite.catalogId, catalogId), isNull(catalogInvite.revokedAt)))
.orderBy(desc(catalogInvite.createdAt));
}
async revokeInvite(catalogId: string, code: string) {
const r = await this.db
.update(catalogInvite)
.set({ revokedAt: new Date() })
.where(and(eq(catalogInvite.catalogId, catalogId), eq(catalogInvite.code, code), isNull(catalogInvite.revokedAt)))
.returning();
if (r.length === 0) throw new ProductError(404, "not_found", "No such invitation.");
}
// ---- what it hosts ----
/** The products a catalog hosts, newest first, with the revisions it hosts of each. */
async hosted(catalogId: string) {
const rows = await this.db
.select({
id: product.id,
name: product.name,
rating: product.rating,
creator: user.displayUsername,
creatorUsername: user.username,
removed: product.removedAt,
deleted: product.deletedAt,
revisions: sql<number[]>`array_agg(${hosting.number} order by ${hosting.number})`,
since: sql<string>`min(${hosting.createdAt})`,
})
.from(hosting)
.innerJoin(product, eq(product.id, hosting.productId))
.innerJoin(user, eq(user.id, product.creatorId))
.where(eq(hosting.catalogId, catalogId))
.groupBy(product.id, user.id)
.orderBy(desc(sql`min(${hosting.createdAt})`))
.limit(500);
return rows.map((r) => ({
id: r.id,
name: r.name,
rating: r.rating,
creator: r.creator ?? r.creatorUsername ?? "",
removed: r.removed !== null,
deleted: r.deleted !== null,
revisions: r.revisions,
since: new Date(r.since).toISOString(),
}));
}
async hostedCounts(catalogId: string) {
const [r] = await this.db
.select({
products: sql<number>`count(distinct ${hosting.productId})::int`,
revisions: sql<number>`count(*)::int`,
bytes: sql<number>`coalesce(sum((select sum((f->>'size')::bigint) from jsonb_array_elements(${productRevision.files}) f)), 0)::bigint`,
})
.from(hosting)
.innerJoin(
productRevision,
and(eq(productRevision.productId, hosting.productId), eq(productRevision.number, hosting.number)),
)
.where(eq(hosting.catalogId, catalogId));
return { products: r?.products ?? 0, revisions: r?.revisions ?? 0, bytes: Number(r?.bytes ?? 0) };
}
/** The catalog stops hosting every revision of a product; its files go in the changes feed for deletion. */
async delist(catalogId: string, productId: string) {
const gone = await this.db
.delete(hosting)
.where(and(eq(hosting.catalogId, catalogId), eq(hosting.productId, productId)))
.returning();
if (gone.length === 0) throw new ProductError(404, "not_found", "This catalog doesn't host that product.");
const revs = await this.db
.select({ number: productRevision.number, files: productRevision.files })
.from(productRevision)
.where(and(eq(productRevision.productId, productId), inArray(productRevision.number, gone.map((g) => g.number))));
for (const r of revs) await this.change(catalogId, { type: "delete", product: productId, revision: r.number, files: r.files });
return gone.map((g) => g.number);
}
// ---- the changes feed ----
async change(catalogId: string, data: Record<string, unknown>) {
await this.db.insert(catalogChange).values({ catalogId, data });
}
/** Changes after a cursor, oldest first (at most 500 at a time). */
async changes(catalogId: string, after: number) {
const rows = await this.db
.select()
.from(catalogChange)
.where(and(eq(catalogChange.catalogId, catalogId), gt(catalogChange.id, after)))
.orderBy(asc(catalogChange.id))
.limit(500);
return { changes: rows.map((r) => r.data), cursor: rows.length ? rows[rows.length - 1]!.id : after };
}
}
async function defaultHealthy(url: string): Promise<boolean> {
try {
const res = await fetch(`${url}/health`, { signal: AbortSignal.timeout(5000) });
return res.ok;
} catch {
return false;
}
}
+215
View File
@@ -0,0 +1,215 @@
// A catalog's importer program and the IMVU accounts it signs in with (docs/imports.md "IMVU accounts"). The importer
// sends its RSA public key; the console seals each account's password in the browser for that key; the hub keeps the
// sealed copy only until the importer has it. Everything but what the importer needs to reach the hub is set here,
// from the console. The routes are in app.ts.
import { createHash, createPublicKey } from "node:crypto";
import { and, asc, eq, lt, sql, schema, type Database, type ImporterSettings } from "@t5de/db";
import { newProductID, ProductError, type Catalog } from "./products";
const { catalog, importerAccount } = schema;
export type ImporterAccount = typeof importerAccount.$inferSelect;
export type AccountState = "waiting" | "received" | "ok" | "sign_in_failed" | "needs_password";
/** A sealed password the importer hasn't fetched within this long is dropped. */
export const sealedFor = 7 * 24 * 60 * 60 * 1000;
/** Accounts a catalog's importer may have. */
export const maxAccounts = 10;
/** Settings' bounds. */
export const settingsBounds = { rate: { min: 0.2, max: 10 }, concurrency: { min: 1, max: 8 } } as const;
/** sha256 of the key's SPKI, hex: what the console shows (shortened) and seals are checked against. */
export const fingerprint = (spkiBase64: string) => createHash("sha256").update(Buffer.from(spkiBase64, "base64")).digest("hex");
/** Checks an importer's public key: base64 SPKI of an RSA key of 3072 to 4096 bits. */
function checkPublicKey(spki: string) {
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(spki)) throw new ProductError(400, "invalid", "The public key isn't base64.");
let bits: number | undefined;
try {
const key = createPublicKey({ key: Buffer.from(spki, "base64"), format: "der", type: "spki" });
if (key.asymmetricKeyType !== "rsa") throw new Error("not RSA");
bits = key.asymmetricKeyDetails?.modulusLength;
} catch {
throw new ProductError(400, "invalid", "The public key isn't an RSA key (SPKI).");
}
if (!bits || bits < 3072 || bits > 4096) throw new ProductError(400, "invalid", "The public key must be RSA with 3072 to 4096 bits.");
}
/** Checks a sealed password: base64 of one RSA-OAEP block (384 or 512 bytes). */
function checkSealed(sealed: string) {
const bytes = /^[A-Za-z0-9+/]+={0,2}$/.test(sealed) ? Buffer.from(sealed, "base64").length : 0;
if (bytes !== 384 && bytes !== 512) throw new ProductError(400, "invalid", "That isn't a sealed password.");
}
export class Importers {
constructor(private readonly db: Database) {}
private async catalogOf(catalogId: string): Promise<Catalog> {
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, catalogId));
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c;
}
// ---- the importer program ----
/**
* The importer says hello: its version and public key. A new key (a new install) can't read passwords sealed for
* the old one, so those accounts need their passwords again.
*/
async hello(c: Catalog, version: string, publicKey: string): Promise<{ changed: boolean }> {
checkPublicKey(publicKey);
const print = fingerprint(publicKey);
const changed = c.importerFingerprint !== print;
await this.db.transaction(async (tx) => {
await tx
.update(catalog)
.set({ importerPublicKey: publicKey, importerFingerprint: print, importerVersion: version, importerSeenAt: new Date() })
.where(eq(catalog.id, c.id));
if (changed && c.importerFingerprint)
await tx
.update(importerAccount)
.set({ sealed: null, sealedFor: null, sealedAt: null, state: "needs_password", stateMessage: "The importer's key changed.", stateAt: new Date() })
.where(eq(importerAccount.catalogId, c.id));
});
return { changed };
}
/** What the importer runs with: paused or not, its settings, and its accounts in order (sealed passwords too). */
async config(c: Catalog) {
await this.db.update(catalog).set({ importerSeenAt: new Date() }).where(eq(catalog.id, c.id));
const accounts = await this.accounts(c.id);
return {
paused: c.importer === "paused",
settings: c.importerSettings,
fingerprint: c.importerFingerprint,
accounts: accounts.map((a) => ({
id: a.id,
imvuId: a.imvuId,
username: a.username,
// Only a password sealed for the key the importer has now.
sealed: a.sealed && a.sealedFor === c.importerFingerprint ? a.sealed : null,
})),
};
}
/** The importer reports on an account: it has the sealed password, and how signing in went. */
async report(c: Catalog, id: string, r: { received?: boolean; state?: "ok" | "sign_in_failed" | "needs_password"; accessPass?: boolean; message?: string }) {
const [a] = await this.db
.select()
.from(importerAccount)
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, c.id)));
if (!a) throw new ProductError(404, "not_found", "No such account.");
const set: Partial<ImporterAccount> = {};
if (r.received && a.sealed) Object.assign(set, { sealed: null, sealedFor: null, sealedAt: null, state: "received", stateMessage: "", stateAt: new Date() });
if (r.state) Object.assign(set, { state: r.state, stateMessage: (r.message ?? "").slice(0, 300), stateAt: new Date() });
if (r.accessPass !== undefined) set.accessPass = r.accessPass;
if (Object.keys(set).length === 0) return a;
const [updated] = await this.db.update(importerAccount).set(set).where(eq(importerAccount.id, a.id)).returning();
return updated!;
}
// ---- the console ----
async accounts(catalogId: string): Promise<ImporterAccount[]> {
return this.db
.select()
.from(importerAccount)
.where(eq(importerAccount.catalogId, catalogId))
.orderBy(asc(importerAccount.position), asc(importerAccount.createdAt));
}
/** Adds an account, its password sealed for the importer's key (which must be the one the console showed). */
async addAccount(
catalogId: string,
a: { imvuId: number; username: string; accessPass: boolean; ageVerified: boolean; sealed: string; fingerprint: string },
byId: string,
): Promise<ImporterAccount> {
const c = await this.catalogOf(catalogId);
this.checkSeal(c, a.sealed, a.fingerprint);
const existing = await this.accounts(c.id);
if (existing.some((x) => x.imvuId === a.imvuId))
throw new ProductError(409, "exists", "The importer has that account already: enter its password again instead.");
if (existing.length >= maxAccounts) throw new ProductError(409, "too_many", `An importer can have at most ${maxAccounts} accounts.`);
const [row] = await this.db
.insert(importerAccount)
.values({
id: newProductID(),
catalogId: c.id,
imvuId: a.imvuId,
username: a.username,
position: existing.length ? Math.max(...existing.map((x) => x.position)) + 1 : 0,
sealed: a.sealed,
sealedFor: a.fingerprint,
sealedAt: new Date(),
accessPass: a.accessPass,
ageVerified: a.ageVerified,
addedBy: byId,
})
.returning();
return row!;
}
/** A new password for an account. */
async setPassword(catalogId: string, id: string, sealed: string, print: string): Promise<ImporterAccount> {
const c = await this.catalogOf(catalogId);
this.checkSeal(c, sealed, print);
const [row] = await this.db
.update(importerAccount)
.set({ sealed, sealedFor: print, sealedAt: new Date(), state: "waiting", stateMessage: "", stateAt: new Date() })
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, c.id)))
.returning();
if (!row) throw new ProductError(404, "not_found", "No such account.");
return row;
}
private checkSeal(c: Catalog, sealed: string, print: string) {
if (!c.importerFingerprint) throw new ProductError(409, "no_importer", "Start the importer first: passwords are sealed for its key.");
if (print !== c.importerFingerprint)
throw new ProductError(409, "importer_key_changed", "The importer's key changed since this page was loaded. Load it again and retry.");
checkSealed(sealed);
}
/** Removes an account; the importer forgets it on its next look at its config. */
async removeAccount(catalogId: string, id: string): Promise<ImporterAccount> {
const [row] = await this.db
.delete(importerAccount)
.where(and(eq(importerAccount.id, id), eq(importerAccount.catalogId, catalogId)))
.returning();
if (!row) throw new ProductError(404, "not_found", "No such account.");
return row;
}
/** Moves an account one place earlier or later in the order the importer tries them. */
async moveAccount(catalogId: string, id: string, direction: "up" | "down"): Promise<void> {
const list = await this.accounts(catalogId);
const i = list.findIndex((a) => a.id === id);
if (i < 0) throw new ProductError(404, "not_found", "No such account.");
const j = direction === "up" ? i - 1 : i + 1;
if (j < 0 || j >= list.length) return;
[list[i], list[j]] = [list[j]!, list[i]!];
await this.db.transaction(async (tx) => {
for (const [n, a] of list.entries()) await tx.update(importerAccount).set({ position: n }).where(eq(importerAccount.id, a.id));
});
}
async setSettings(catalogId: string, s: ImporterSettings): Promise<ImporterSettings> {
const { rate, concurrency } = settingsBounds;
if (!(s.rate >= rate.min && s.rate <= rate.max)) throw new ProductError(400, "invalid", `Requests a second: ${rate.min} to ${rate.max}.`);
if (!Number.isInteger(s.concurrency) || s.concurrency < concurrency.min || s.concurrency > concurrency.max)
throw new ProductError(400, "invalid", `Jobs at once: ${concurrency.min} to ${concurrency.max}.`);
const settings = { rate: Math.round(s.rate * 10) / 10, concurrency: s.concurrency };
const [c] = await this.db.update(catalog).set({ importerSettings: settings }).where(eq(catalog.id, catalogId)).returning();
if (!c) throw new ProductError(404, "not_found", "No such catalog.");
return c.importerSettings;
}
/** Drops sealed passwords no importer fetched in time; their accounts need their passwords again. */
async expireSealed(): Promise<number> {
const rows = await this.db
.update(importerAccount)
.set({ sealed: null, sealedFor: null, sealedAt: null, state: "needs_password", stateMessage: "The importer didn't fetch the password within 7 days.", stateAt: new Date() })
.where(and(sql`${importerAccount.sealed} is not null`, lt(importerAccount.sealedAt, new Date(Date.now() - sealedFor))))
.returning({ id: importerAccount.id });
return rows.length;
}
}
File diff suppressed because it is too large. Load diff
+82 -7
View File
@@ -26,15 +26,31 @@ export type ImvuRoom = {
expired: boolean;
};
/** An IMVU product's public info, as T5 products derived from it show it. */
/** An IMVU product's public info: as T5 products derived from it show it, and as imports need it. */
export type ImvuProduct = {
image: string | null; // https, on *.imvu.com
categories: { id: number; name: string }[]; // outermost first, e.g. Clothing / Clothing for Female / Tops
gender: string; // "female", "male", or "" (either)
name: string;
creatorId: number; // the creator's IMVU account (0 if IMVU didn't say)
creatorName: string;
adult: boolean; // rated AP
purchasable: boolean; // false once retired
};
/** A shop's products as IMVU lists them to the signed out: general-rated ones only. */
export type ImvuShop = {
products: (ImvuProduct & { id: number })[];
total: number; // IMVU's count; more than products.length if the listing stopped early
};
// IMVU's listing pages overlap when paged in small pages (2026-11-07: 100 a page gave 580 different products of 639),
// but one page of up to 1000 holds them all, so shops are listed in pages of 1000, at most this many.
const shopPage = 1000;
const shopPages = 10;
export class NoSuchImvuUser extends Error {
constructor() {
constructor(readonly status = 404) {
super("no such IMVU account");
}
}
@@ -78,13 +94,46 @@ export class ImvuClient {
* Access Pass ones). Throws ImvuUnavailable if IMVU can't be reached.
*/
async product(id: number): Promise<ImvuProduct | null> {
if (!Number.isSafeInteger(id) || id <= 0) return null;
const p = await this.lookup(id);
return typeof p === "string" ? null : p;
}
/**
* Like product(), but tells "missing" (404) from "hidden": IMVU answers 401 alike for Access Pass products,
* deleted ones and IDs that never existed, so a hidden product may still exist.
*/
async lookup(id: number): Promise<ImvuProduct | "missing" | "hidden"> {
if (!Number.isSafeInteger(id) || id <= 0) return "missing";
let answer: unknown;
try {
return parseProduct(await this.get(`/product/product-${id}`, [401, 403]), id);
answer = await this.get(`/product/product-${id}`, [401, 403]);
} catch (e) {
if (e instanceof NoSuchImvuUser) return null;
if (e instanceof NoSuchImvuUser) return e.status === 404 ? "missing" : "hidden";
throw e;
}
return parseProduct(answer, id) ?? "missing";
}
/** The products IMVU lists for a shop (by its current username), at most 10,000. */
async shop(username: string): Promise<ImvuShop> {
const name = username.trim();
if (!name || name.length > 64) throw new NoSuchImvuUser();
const seen = new Map<number, ImvuProduct & { id: number }>();
let total = 0;
let path: string | undefined = `/product?creator=${encodeURIComponent(name)}&limit=${shopPage}`;
for (let page = 0; path && page < shopPages; page++) {
const answer = await this.get(path);
const listed = parseShop(answer);
if (!listed) throw new ImvuUnavailable("IMVU's shop listing wasn't understood");
total = Math.max(total, listed.total);
for (const id of listed.items) {
const p = seen.has(id) ? undefined : parseProduct(answer, id);
if (p) seen.set(id, { ...p, id });
}
// Only ever follow IMVU's own API.
path = listed.next?.startsWith(this.base + "/") ? listed.next.slice(this.base.length) : undefined;
}
return { products: [...seen.values()], total };
}
private async wait() {
@@ -106,7 +155,7 @@ export class ImvuClient {
} catch (e) {
throw new ImvuUnavailable(String(e));
}
if (response.status === 404 || missing.includes(response.status)) throw new NoSuchImvuUser();
if (response.status === 404 || missing.includes(response.status)) throw new NoSuchImvuUser(response.status);
if (!response.ok) throw new ImvuUnavailable(`IMVU answered ${response.status}`);
return response.json();
}
@@ -152,6 +201,21 @@ export function imvuImage(v: unknown): string | null {
return url.href;
}
/** A shop listing's own entry: its product IDs (in order), IMVU's count and the next page's URL. */
export function parseShop(answer: unknown): { items: number[]; total: number; next?: string } | null {
const a = answer as { id?: unknown; denormalized?: Record<string, { data?: Record<string, unknown>; relations?: Record<string, unknown> }> };
const entry = typeof a?.id === "string" ? a.denormalized?.[a.id] : undefined;
const items = entry?.data?.items;
if (!entry || !Array.isArray(items)) return null;
const ids = items.flatMap((i) => {
const n = typeof i === "string" ? Number(i.match(/\/product\/product-(\d+)$/)?.[1]) : NaN;
return Number.isSafeInteger(n) && n > 0 ? [n] : [];
});
const total = Number(entry.data?.total_count);
const next = entry.relations && !Array.isArray(entry.relations) ? entry.relations.next : undefined;
return { items: ids, total: Number.isSafeInteger(total) && total > 0 ? total : ids.length, next: typeof next === "string" ? next : undefined };
}
export function parseProduct(answer: unknown, id: number): ImvuProduct | null {
const den = (answer as { denormalized?: Record<string, { data?: Record<string, unknown> }> })?.denormalized ?? {};
const entry = Object.entries(den).find(([key]) => key.endsWith(`/product/product-${id}`));
@@ -165,7 +229,18 @@ export function parseProduct(answer: unknown, id: number): ImvuProduct | null {
return [{ id: n, name: name.trim().slice(0, 100) }];
});
const gender = d.gender === "female" || d.gender === "male" ? d.gender : "";
return { image: imvuImage(d.product_image), categories, gender };
const creatorId = Number(d.creator_cid);
const text = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
return {
image: imvuImage(d.product_image),
categories,
gender,
name: text(d.product_name, 200),
creatorId: Number.isSafeInteger(creatorId) && creatorId > 0 ? creatorId : 0,
creatorName: text(d.creator_name, 64),
adult: d.rating === "AP" || d.is_ap === true,
purchasable: d.is_purchasable !== false,
};
}
// IMVU's "denormalized" answers: the user is the one /user/user-<id> entry.
+100 -4
View File
@@ -4,9 +4,26 @@
// API_URL the API's address as the website and proxies reach it (default http://localhost:4101)
// WEB_URL the website's address (default http://localhost:4100)
// PORT default 4101
// REGISTRATION open or closed (new accounts wait for a moderator's approval), until an admin sets it in the console
// DISCORD_CLIENT_ID, DISCORD_CLIENT_SECRET
// Discord sign-in (basic accounts, docs/music.md); its redirect URL is
// API_URL/api/auth/callback/discord. Off unless both are set.
// MUSIC_CLIENT_SECRET, MUSIC_REDIRECT_URIS
// T5DE Music (docs/music.md) as an OpenID Connect client of the hub, client ID t5de-music: its
// secret (at least 32 characters) and redirect URIs, comma-separated (e.g.
// https://music.t5de.dev/api/auth/callback). The issuer is API_URL/api/auth.
// AGE_PROVIDERS ways to verify age, comma-separated (default imvu): imvu, didit
// DIDIT_API_KEY, DIDIT_WORKFLOW_ID, DIDIT_WEBHOOK_SECRET
// Didit's ID document check (docs/design.md, "Age"); its webhook is API_URL/api/v1/age/webhook/didit
// DIDIT_MONTHLY_LIMIT checks started a month at most (default 30: Didit's free plan has $10 of credit a month, and a
// check with ID document, liveness and face match costs $0.30)
import { openDatabase } from "@t5de/db";
import { AgeService, type Provider } from "./age";
import { diditAgeProvider } from "./age/didit";
import { imvuAgeProvider } from "./age/imvu";
import { createApp } from "./app";
import { createAuth } from "./auth";
import { createAuth, seedClients, type FirstPartyClient } from "./auth";
import { Settings } from "./settings";
import { ImvuClient } from "./imvu";
const env = process.env;
@@ -21,17 +38,96 @@ const apiURL = env.API_URL ?? `http://localhost:${port}`;
const webURL = env.WEB_URL ?? "http://localhost:4100";
const { db } = await openDatabase(env.DATABASE_URL ?? "./data/db");
const auth = createAuth(db, { apiURL, webURL, secret });
const { app, age, rooms, products } = createApp({ db, auth, imvu: new ImvuClient(), apiURL });
const settings = new Settings(db, { registration: env.REGISTRATION });
const discord =
env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET
? { clientId: env.DISCORD_CLIENT_ID, clientSecret: env.DISCORD_CLIENT_SECRET }
: undefined;
const clients: FirstPartyClient[] = [];
if (env.MUSIC_CLIENT_SECRET)
clients.push({
clientId: "t5de-music",
name: "T5DE Music",
secret: env.MUSIC_CLIENT_SECRET,
redirectUris: (env.MUSIC_REDIRECT_URIS ?? "").split(",").map((u) => u.trim()).filter(Boolean),
});
// In development, Music runs on http://localhost too.
const auth = createAuth(db, { apiURL, webURL, secret, settings, discord, clients, localRedirects: dev });
try {
await seedClients(db, apiURL, clients);
} catch (e) {
console.error("OAuth clients:", (e as Error).message);
process.exit(1);
}
const imvu = new ImvuClient();
function required(name: string): string {
const v = env[name];
if (!v) {
console.error(`${name} must be set`);
process.exit(1);
}
return v;
}
const ageProviders: Record<string, () => Provider> = {
imvu: () => imvuAgeProvider(imvu),
didit: () =>
diditAgeProvider({
apiKey: required("DIDIT_API_KEY"),
workflowId: required("DIDIT_WORKFLOW_ID"),
webhookSecret: required("DIDIT_WEBHOOK_SECRET"),
monthlyLimit: Number(env.DIDIT_MONTHLY_LIMIT ?? 30),
}),
};
const providers = (env.AGE_PROVIDERS ?? "imvu").split(",").map((id) => id.trim()).filter(Boolean);
if (!providers.includes("imvu")) providers.unshift("imvu"); // linking records IMVU's answer
for (const id of providers) {
if (!ageProviders[id]) {
console.error(`AGE_PROVIDERS: no provider ${id}`);
process.exit(1);
}
}
const ageService = new AgeService(db, providers.map((id) => ageProviders[id]!()));
const { app, age, rooms, products, imports, importers } = createApp({ db, auth, imvu, age: ageService, apiURL, webURL, settings });
app.listen({ port, hostname: env.HOST ?? "0.0.0.0" });
// Age answers that can change (IMVU's) are checked again when they expire, a few at a time; revisions missing their
// parent's info (IMVU was unavailable, or they predate it) get it, starting now.
// parent's info (IMVU was unavailable, or they predate it) get it, starting now; drafts never published go after 30
// days.
const parentInfo = () => products.fillParentInfo(20).catch((e) => console.error("parent info:", e));
const purgeDrafts = () =>
products
.purgeDrafts()
.then((n) => n > 0 && console.log(`deleted ${n} drafts never published`))
.catch((e) => console.error("drafts:", e));
parentInfo();
purgeDrafts();
setInterval(() => {
age.recheckDue(50).catch((e) => console.error("age re-checks:", e));
rooms.recheckDue(20).catch((e) => console.error("room re-checks:", e));
parentInfo();
purgeDrafts();
}, 10 * 60 * 1000);
// Imported products are checked with IMVU again daily (gone or another creator's: withdrawn; new revisions: a recheck
// job for the catalog's importer), a batch each hour.
const importRecheck = () =>
imports
.recheck(200)
.then((r) => (r.queued || r.withdrawn.length) && console.log(`imports: ${r.queued} rechecks queued, ${r.withdrawn.length} withdrawn`))
.catch((e) => console.error("import rechecks:", e));
// Whole-shop grants: their products listed on IMVU daily (new ones queued), a few shops each hour.
const shopListing = () =>
imports
.listShops(5)
.then((r) => r.queued && console.log(`imports: ${r.shops} shops listed, ${r.queued} products queued`))
.catch((e) => console.error("shop listings:", e));
setInterval(() => {
importRecheck();
shopListing();
importers
.expireSealed()
.then((n) => n && console.log(`imports: ${n} sealed importer passwords expired`))
.catch((e) => console.error("importer passwords:", e));
}, 60 * 60 * 1000);
console.log(`t5de-hub API on ${apiURL} (website ${webURL})`);
+67
View File
@@ -0,0 +1,67 @@
// Notifications (docs/console.md): something for a person to know, shown on the website and sent to their proxies
// over the realtime connection ({"type": "notification"}), so a client can show them later.
import { and, count, desc, eq, inArray, isNull, lt, schema, type AuditTags, type Database } from "@t5de/db";
const { notification } = schema;
/**
* The kinds of notification, and what their data holds:
* - product_edited: someone other than its creator changed a product's info `{product, name, kind, fields, reason, by}`
* - case_decided: a case they opened was decided `{case, kind, status, resolution}`
* - case_note: someone replied on a case they opened or are assigned `{case, kind, by}`
* - product_removed: moderation removed their product `{product, name, reason}`
* - product_restored: moderation restored it `{product, name, reason}`
* - membership_decided: a catalog decided their membership `{catalog, name, status}` (member, declined, banned)
*/
export type NotificationType =
| "product_edited"
| "product_removed"
| "product_restored"
| "case_decided"
| "case_note"
| "membership_decided"
| "import_grant_decided"
| "import_grant_ended";
export class Notifications {
constructor(
private readonly db: Database,
private readonly push: (userId: string, message: object) => void = () => {},
) {}
/** Tells a person something (never the one who did it: pass `actorId` to leave them out). */
async add(userId: string | null | undefined, type: NotificationType, data: Record<string, unknown>, tags: AuditTags = {}, actorId?: string) {
if (!userId || userId === actorId) return;
await this.db.insert(notification).values({ userId, type, data, tags });
this.push(userId, { type: "notification" });
}
/** A person's notifications, newest first; `before` an ID for the next page. */
async list(userId: string, before?: number, limit = 50) {
const rows = await this.db
.select()
.from(notification)
.where(and(eq(notification.userId, userId), before ? lt(notification.id, before) : undefined))
.orderBy(desc(notification.id))
.limit(Math.max(1, Math.min(limit, 100)));
return rows;
}
async unread(userId: string): Promise<number> {
const [row] = await this.db
.select({ n: count() })
.from(notification)
.where(and(eq(notification.userId, userId), isNull(notification.readAt)));
return row?.n ?? 0;
}
/** Marks some (or all) of a person's notifications read. */
async markRead(userId: string, ids?: number[]) {
await this.db
.update(notification)
.set({ readAt: new Date() })
.where(
and(eq(notification.userId, userId), isNull(notification.readAt), ids ? inArray(notification.id, ids) : undefined),
);
}
}
+289
View File
@@ -0,0 +1,289 @@
// Permissions (docs/console.md): code checks `resource:action` permissions, never roles. A role is a bundle of
// permissions given at a scope; hub-wide roles are user.role, owners are derived (a catalog's owner, a product's
// creator), and other roles are role_assignment rows.
import { and, eq, schema, type Database, type TokenGrant } from "@t5de/db";
const { catalog, product, roleAssignment, user } = schema;
export const permissions = [
"product:edit",
"product:edit-locked",
"product:lock",
"product:rate-lower",
"product:publish",
"product:delete",
"product:restore",
"product:remove",
"product:unremove",
"product:transfer",
"revision:upload",
"revision:retract",
"catalog:approve",
"catalog:edit",
"catalog:rotate-key",
"catalog:suspend",
"catalog:delete-request",
"catalog:delete-review",
"catalog:transfer",
"team:manage",
"member:approve",
"member:invite",
"member:remove",
"member:ban",
"hosting:choose",
"hosting:delist",
"import:grant",
"import:grant-on-behalf",
"import:accept",
"import:run",
"import:pause",
"import:withdraw",
"case:read",
"case:resolve",
"case:assign",
"audit:read",
"audit:read-sensitive",
"stats:read",
"person:approve",
"person:ban",
"person:link-cap",
"person:notes",
"person:role",
"person:view-as",
"room:edit",
"room:close",
"room:kick",
"room:ban",
"room:mute",
"settings:edit",
] as const;
export type Permission = (typeof permissions)[number];
/** Permissions that need two-factor sign-in on: without it, using them answers 403 `two_factor_required`. */
export const sensitive: readonly Permission[] = [
"product:remove",
"person:ban",
"person:role",
"audit:read-sensitive",
"catalog:transfer",
"catalog:suspend",
"import:grant-on-behalf",
"settings:edit",
];
/** Where a permission applies. The hub covers everything. */
export type Scope = { type: "hub" } | { type: "catalog"; id: string } | { type: "product"; id: string };
export const hubScope: Scope = { type: "hub" };
const all = (prefix: string) => permissions.filter((p) => p.startsWith(prefix + ":"));
const without = (list: readonly Permission[], ...drop: Permission[]) => list.filter((p) => !drop.includes(p));
const catalogOwner: Permission[] = [
"catalog:edit",
"catalog:rotate-key",
"catalog:delete-request",
"catalog:transfer",
"team:manage",
...all("member"),
"hosting:delist",
"import:grant",
"import:accept",
"import:run",
"import:pause",
"import:withdraw",
"case:read",
"case:resolve",
"audit:read",
"stats:read",
];
/** The built-in roles: name, the scope they're given at, and their permissions. */
export const roles = {
admin: { name: "Admin", scope: "hub", permissions: [...permissions] as Permission[] },
moderator: {
name: "Moderator",
scope: "hub",
permissions: [
...without(all("product"), "product:transfer"),
"revision:retract",
"catalog:approve",
"catalog:suspend",
"catalog:delete-review",
"hosting:delist",
"import:grant-on-behalf",
"import:withdraw",
"import:pause",
...all("case"),
"person:approve",
"person:ban",
"person:link-cap",
"person:notes",
"audit:read",
"stats:read",
...all("room"),
] as Permission[],
},
"catalog-owner": { name: "Owner", scope: "catalog", permissions: catalogOwner },
"catalog-operator": {
name: "Operator",
scope: "catalog",
permissions: without(catalogOwner, "catalog:delete-request", "catalog:transfer", "team:manage"),
},
creator: {
name: "Creator",
scope: "product",
permissions: [
"product:edit",
"product:publish",
"product:delete",
"product:restore",
"product:transfer",
"revision:upload",
"revision:retract",
"hosting:choose",
"case:read",
"audit:read",
"stats:read",
] as Permission[],
},
} as const satisfies Record<string, { name: string; scope: string; permissions: Permission[] }>;
export type RoleId = keyof typeof roles;
/** Roles that can be given at a catalog (the owner is derived, never given). */
export const assignableCatalogRoles = ["catalog-operator"] as const;
/** A person, as the check needs them. Signed in with an API token, only what it grants too (the intersection). */
export type Who = { id: string; role: string; twoFactorEnabled?: boolean; token?: { id: string; name: string; grants: TokenGrant[] } };
/** Whether a token (if any) grants a permission at a scope: granted there, or hub-wide. */
export function granted(who: Who | undefined, permission: Permission, scope: Scope): boolean {
if (!who?.token) return true;
return who.token.grants.some(
(g) =>
g.permission === permission &&
(g.scope.type === "hub" || (scope.type !== "hub" && g.scope.type === scope.type && g.scope.id === scope.id)),
);
}
/** Thrown when a sensitive permission is held but two-factor sign-in is off. */
export class TwoFactorRequired extends Error {
constructor(readonly permission: Permission) {
super("Turn on two-factor sign-in on your account page first.");
}
}
/** Thrown when a permission is missing; the API answers 403 with what was missing. */
export class Forbidden extends Error {
constructor(
readonly permission: Permission,
readonly scope: Scope,
) {
super("You don't have permission to do that.");
}
}
export class Permissions {
constructor(private readonly db: Database) {}
/** A person's hub-wide permissions (their user.role). */
hub(who: Who | undefined): Set<Permission> {
const held = who?.role === "admin" ? roles.admin.permissions : who?.role === "moderator" ? roles.moderator.permissions : [];
return new Set(held.filter((p) => granted(who, p, hubScope)));
}
/** The roles a person holds at a scope, broader scopes' included ("admin", "catalog-owner", ...). */
async rolesAt(who: Who | undefined, scope: Scope): Promise<RoleId[]> {
if (!who) return [];
const out: RoleId[] = [];
if (who.role === "admin") out.push("admin");
else if (who.role === "moderator") out.push("moderator");
if (scope.type === "catalog") {
const [c] = await this.db.select({ ownerId: catalog.ownerId }).from(catalog).where(eq(catalog.id, scope.id));
if (c?.ownerId === who.id) out.push("catalog-owner");
const given = await this.db
.select({ role: roleAssignment.role })
.from(roleAssignment)
.where(
and(eq(roleAssignment.userId, who.id), eq(roleAssignment.scopeType, "catalog"), eq(roleAssignment.scopeId, scope.id)),
);
for (const g of given) if (g.role in roles) out.push(g.role as RoleId);
} else if (scope.type === "product") {
const [p] = await this.db.select({ creatorId: product.creatorId }).from(product).where(eq(product.id, scope.id));
if (p?.creatorId === who.id) out.push("creator");
}
return out;
}
/** Every permission a person holds at a scope. */
async at(who: Who | undefined, scope: Scope): Promise<Set<Permission>> {
const out = new Set<Permission>();
for (const r of await this.rolesAt(who, scope)) for (const p of roles[r].permissions) if (granted(who, p, scope)) out.add(p);
return out;
}
async can(who: Who | undefined, permission: Permission, scope: Scope): Promise<boolean> {
if (this.hub(who).has(permission)) return true;
if (scope.type === "hub") return false;
return (await this.at(who, scope)).has(permission);
}
/** Throws Forbidden unless the person holds the permission at the scope, and TwoFactorRequired if it's sensitive
* and they haven't turned two-factor sign-in on. */
async require(who: Who | undefined, permission: Permission, scope: Scope): Promise<void> {
if (!(await this.can(who, permission, scope))) throw new Forbidden(permission, scope);
if (sensitive.includes(permission) && !who?.twoFactorEnabled) throw new TwoFactorRequired(permission);
}
/** May `who` give (or take away) `role` at `scope`? Only if they hold every permission in it there. */
async mayGive(who: Who | undefined, role: RoleId, scope: Scope): Promise<boolean> {
const held = await this.at(who, scope);
return roles[role].permissions.every((p) => held.has(p));
}
/** The catalogs a person is on the team of (owner or a role there). */
async teamCatalogs(personId: string): Promise<string[]> {
const owned = await this.db.select({ id: catalog.id }).from(catalog).where(eq(catalog.ownerId, personId));
const given = await this.db
.select({ id: roleAssignment.scopeId })
.from(roleAssignment)
.where(and(eq(roleAssignment.userId, personId), eq(roleAssignment.scopeType, "catalog")));
return [...new Set([...owned.map((c) => c.id), ...given.map((g) => g.id)])];
}
/** The products a person created. */
async ownProducts(personId: string): Promise<string[]> {
return (await this.db.select({ id: product.id }).from(product).where(eq(product.creatorId, personId))).map((p) => p.id);
}
/** A catalog's team: the owner and everyone given a role there, with their names. */
async team(catalogId: string) {
const [c] = await this.db
.select({ ownerId: catalog.ownerId, name: user.displayUsername, username: user.username })
.from(catalog)
.innerJoin(user, eq(user.id, catalog.ownerId))
.where(eq(catalog.id, catalogId));
const given = await this.db
.select({
personId: roleAssignment.userId,
role: roleAssignment.role,
name: user.displayUsername,
username: user.username,
since: roleAssignment.createdAt,
})
.from(roleAssignment)
.innerJoin(user, eq(user.id, roleAssignment.userId))
.where(and(eq(roleAssignment.scopeType, "catalog"), eq(roleAssignment.scopeId, catalogId)));
return {
owner: c ? { personId: c.ownerId, username: c.name ?? c.username ?? "" } : undefined,
roles: given.map((g) => ({
personId: g.personId,
role: g.role,
username: g.name ?? g.username ?? "",
since: g.since.toISOString(),
})),
};
}
}
+432 -29
View File
@@ -20,12 +20,38 @@ import { cleanHTML, maxDescription } from "./html";
import type { ImvuClient } from "./imvu";
import type { Signer } from "./keys";
const { catalog, product, productRevision, hosting, library, user } = schema;
const { catalog, catalogChange, catalogMember, fileBlock, product, productInfoChange, productRevision, hosting, library, roleAssignment, user } =
schema;
export type Catalog = typeof catalog.$inferSelect;
export type Product = typeof product.$inferSelect;
export type Revision = typeof productRevision.$inferSelect;
/** Info fields people edit (and moderators lock). */
export const infoFields = ["name", "description", "rating", "tags", "listed", "category"] as const;
export type InfoField = (typeof infoFields)[number];
/** `category`: an IMVU category ID from categoryChoices, or null for its parent's. */
export type InfoInput = {
name?: string;
description?: string;
rating?: string;
tags?: string[];
listed?: boolean;
category?: number | null;
};
/** An IMVU category path, outermost first. */
export type CategoryPath = { id: number; name: string }[];
/** What the person editing may do beyond product:edit (from the permission check). */
export type EditRights = { creator: boolean; editLocked: boolean; rateLower: boolean };
/** Who's looking: drafts are only for their creator and moderators. */
export type ProductViewer = { id: string; moderator: boolean };
/** Drafts never published are deleted after this long. */
export const draftDays = 30;
/** An error for the person; the routes turn it into a Problem. */
export class ProductError extends Error {
constructor(
@@ -37,6 +63,17 @@ export class ProductError extends Error {
}
}
/** An upload with a blocked file (docs/products.md): refused, and the route audits who tried. */
export class BlockedUpload extends ProductError {
constructor(
readonly personId: string,
readonly catalogId: string,
readonly files: FileEntry[],
) {
super(409, "blocked", "This upload has a file T5DE blocks.");
}
}
const base32 = "abcdefghijklmnopqrstuvwxyz234567";
export const newProductID = () =>
[...crypto.getRandomValues(new Uint8Array(10))].map((b) => base32[b & 31]).join("");
@@ -50,6 +87,19 @@ const nameRule = (s: unknown, max: number) => {
return v;
};
/** Tags as people type them: lowercase words (letters, digits, spaces, dashes), at most 10, each up to 24. */
export function checkTags(tags: unknown): string[] | undefined {
if (!Array.isArray(tags) || tags.length > 10) return undefined;
const out: string[] = [];
for (const t of tags) {
const v = typeof t === "string" ? t.trim().toLowerCase().replace(/\s+/g, " ") : "";
if (!v) continue;
if (v.length > 24 || !/^[\p{L}\p{N}][\p{L}\p{N} -]*$/u.test(v)) return undefined;
if (!out.includes(v)) out.push(v);
}
return out;
}
/** A file list as catalogs send it: checked and sorted by name. */
export function checkFiles(files: unknown): FileEntry[] | undefined {
if (!Array.isArray(files) || files.length === 0 || files.length > 512) return undefined;
@@ -74,6 +124,21 @@ const sameFiles = (a: FileEntry[], b: FileEntry[]) =>
// A parent's info another revision looked up lately is reused rather than asking IMVU again.
const parentInfoFresh = 7 * 24 * 60 * 60 * 1000;
/**
* Whether a product is available to a person (docs/products.md, "Member"): it's published, and they made it, or a
* catalog hosting it is approved, hasn't banned them, and is open or has them as a member or on its team.
*/
export const availableTo = (personId: string) => sql`(${product.status} = 'published' and (
${product.creatorId} = ${personId} or exists (
select 1 from ${hosting} h
join ${catalog} c on c.id = h.catalog_id
left join ${catalogMember} m on m.catalog_id = c.id and m.user_id = ${personId}
where h.product_id = ${product.id} and c.status = 'approved' and coalesce(m.status, '') <> 'banned'
and (c.membership = 'open' or m.status = 'member' or c.owner_id = ${personId}
or exists (select 1 from ${roleAssignment} r
where r.user_id = ${personId} and r.scope_type = 'catalog' and r.scope_id = c.id))
)))`;
/** Each product's latest revision (joined on product.latest, for lists). */
const latestJoin = and(eq(productRevision.productId, product.id), eq(productRevision.number, product.latest));
@@ -123,12 +188,13 @@ export class Products {
return { catalog: c!, key };
}
/** The catalog an `Authorization: Catalog <id>:<key>` header names, if it's approved and the key is right. */
async catalogFor(header: string | null): Promise<Catalog | undefined> {
/** The catalog an `Authorization: Catalog <id>:<key>` header names, if it's approved (or suspended, when asked)
* and the key is right. */
async catalogFor(header: string | null, suspendedToo = false): Promise<Catalog | undefined> {
const m = header?.match(/^Catalog ([a-z2-7]{10}):(\S+)$/);
if (!m) return undefined;
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, m[1]!));
if (!c || c.status !== "approved") return undefined;
if (!c || !(c.status === "approved" || (suspendedToo && c.status === "suspended"))) return undefined;
return timingSafeEqual(Buffer.from(sha256(m[2]!)), Buffer.from(c.keyHash)) ? c : undefined;
}
@@ -163,6 +229,23 @@ export class Products {
const [c] = await this.db.select().from(catalog).where(eq(catalog.id, catalogId));
if (!c || c.status !== "approved") throw new ProductError(404, "not_found", "No such catalog.");
if (productId) await this.own(personId, productId);
if (c.uploads !== "anyone" && c.ownerId !== personId) {
const [team] = await this.db
.select({ role: roleAssignment.role })
.from(roleAssignment)
.where(and(eq(roleAssignment.userId, personId), eq(roleAssignment.scopeType, "catalog"), eq(roleAssignment.scopeId, c.id)));
const [m] = await this.db
.select({ status: catalogMember.status })
.from(catalogMember)
.where(and(eq(catalogMember.catalogId, c.id), eq(catalogMember.userId, personId)));
const ok = team !== undefined || (c.uploads === "members" && m?.status === "member");
if (!ok)
throw new ProductError(
403,
"forbidden",
c.uploads === "members" ? "Only this catalog's members can upload to it." : "Only this catalog's team can upload to it.",
);
}
const token = await this.signer.sign(
"t5de-upload",
{ sub: personId, catalog: c.id, ...(productId ? { product: productId } : {}) },
@@ -183,9 +266,20 @@ export class Products {
if (!files) throw new ProductError(400, "invalid", "The file list isn't valid.");
if (body.rating !== "general" && body.rating !== "adult")
throw new ProductError(400, "invalid", "The rating must be general or adult.");
if (body.rating === "adult" && c.maxRating === "general")
throw new ProductError(400, "rating_ceiling", "This catalog hosts general-audience products only.");
const parent = Number.isSafeInteger(body.parent) && body.parent > 0 ? body.parent : 0;
const notes = (typeof body.notes === "string" ? body.notes.trim() : "").slice(0, 2000);
const personId = claims.sub;
const blocked = new Set(
(
await this.db
.select({ sha256: fileBlock.sha256 })
.from(fileBlock)
.where(inArray(fileBlock.sha256, [...new Set(files.map((f) => f.sha256))]))
).map((b) => b.sha256),
);
if (blocked.size) throw new BlockedUpload(personId, c.id, files.filter((f) => blocked.has(f.sha256)));
const made = await this.db.transaction(async (tx) => {
let p: Product;
@@ -204,7 +298,7 @@ export class Products {
const name = nameRule(body.name, 64) ?? "Untitled";
const [made] = await tx
.insert(product)
.values({ id: newProductID(), creatorId: personId, name, rating: body.rating })
.values({ id: newProductID(), creatorId: personId, name, rating: body.rating, status: "draft" })
.returning();
p = made!;
}
@@ -230,7 +324,7 @@ export class Products {
const rating = p.rating === "adult" || body.rating === "adult" ? "adult" : "general";
await tx.update(product).set({ latest: number, rating }).where(eq(product.id, p.id));
await tx.insert(hosting).values({ catalogId: c.id, productId: p.id, number });
return { product: p.id, revision: number };
return { product: p.id, revision: number, draft: p.status === "draft" };
});
// The parent's image and categories: best effort, without holding up the upload (fillParentInfo retries).
if (parent > 0) this.lookUpParent(made.product, made.revision, parent).catch(() => {});
@@ -318,17 +412,51 @@ export class Products {
return p;
}
/** Undoes a moderation removal (an upheld appeal, a mistake): its page, files and library entries are back, since
* removing only hides them. */
async unremove(id: string) {
const [p] = await this.db
.update(product)
.set({ removedAt: null, removedReason: null })
.where(and(eq(product.id, id), sql`${product.removedAt} is not null`))
.returning();
if (!p) throw new ProductError(404, "not_found", "No such removed product.");
return p;
}
/**
* Products, newest first; adult ones only if adult. `category`: only those whose latest revision's parent is in
* that IMVU category (anywhere in its path). Each comes with its latest revision's parent and parent info.
* Published products, newest first; adult ones only if adult; unlisted ones only for their creator. `category`:
* only those whose latest revision's parent is in that IMVU category (anywhere in its path); `tag`: those with
* the tag; `catalog`: those the catalog hosts. Each comes with its latest revision's parent and parent info.
*/
async list(opts: { q?: string; creator?: string; category?: number; adult: boolean; limit?: number }) {
const conds = [ne(product.latest, 0), isNull(product.deletedAt), isNull(product.removedAt)];
async list(opts: {
q?: string;
creator?: string;
category?: number;
tag?: string;
catalog?: string;
adult: boolean;
viewerId?: string;
limit?: number;
}) {
const conds = [
ne(product.latest, 0),
eq(product.status, "published"),
isNull(product.deletedAt),
isNull(product.removedAt),
opts.viewerId ? or(eq(product.listed, true), eq(product.creatorId, opts.viewerId))! : eq(product.listed, true),
];
if (!opts.adult) conds.push(eq(product.rating, "general"));
if (opts.q) conds.push(ilike(product.name, `%${opts.q.replace(/[%_\\]/g, (c) => "\\" + c)}%`));
if (opts.creator) conds.push(eq(user.username, opts.creator.toLowerCase()));
if (opts.category !== undefined)
conds.push(sql`${productRevision.parentInfo}->'categories' @> ${JSON.stringify([{ id: opts.category }])}::jsonb`);
conds.push(
sql`coalesce(${product.category}, ${productRevision.parentInfo}->'categories') @> ${JSON.stringify([{ id: opts.category }])}::jsonb`,
);
const tag = opts.tag !== undefined ? checkTags([opts.tag])?.[0] : undefined;
if (opts.tag !== undefined) conds.push(tag ? sql`${product.tags} @> ${JSON.stringify([tag])}::jsonb` : sql`false`);
if (opts.catalog)
conds.push(sql`exists (select 1 from ${hosting} h where h.product_id = ${product.id} and h.catalog_id = ${opts.catalog})`);
const limit = Math.max(1, Math.min(Math.trunc(opts.limit ?? 60) || 60, 200));
return this.db
.select({
@@ -355,7 +483,7 @@ export class Products {
return r;
}
async get(id: string, adult: boolean) {
async get(id: string, adult: boolean, viewer?: ProductViewer) {
const [row] = await this.db
.select({ product, creator: user.displayUsername, creatorUsername: user.username })
.from(product)
@@ -363,7 +491,10 @@ export class Products {
.where(eq(product.id, id));
if (!row || row.product.latest === 0) throw new ProductError(404, "not_found", "No such product.");
if (row.product.removedAt) throw new ProductError(410, "removed", "This product was removed by moderation.");
if (row.product.rating === "adult" && !adult) throw new ProductError(404, "not_found", "No such product.");
// Its creator and moderators always see it: drafts, and adult products without an adult account.
const responsible = viewer?.moderator || viewer?.id === row.product.creatorId;
if (row.product.status === "draft" && !responsible) throw new ProductError(404, "not_found", "No such product.");
if (row.product.rating === "adult" && !adult && !responsible) throw new ProductError(404, "not_found", "No such product.");
const revisions = await this.db
.select()
.from(productRevision)
@@ -377,27 +508,276 @@ export class Products {
return { ...row, revisions, hosts };
}
async update(personId: string, id: string, input: { name?: string; description?: string; rating?: string }) {
const p = await this.own(personId, id);
const set: Partial<Product> = {};
// ---- product info: edits, history, locks, publishing ----
/** A product for changing its info: not removed; deleted ones only by others than the creator (moderators). */
private async editable(id: string, rights: EditRights) {
const [p] = await this.db.select().from(product).where(eq(product.id, id));
if (!p || p.latest === 0) throw new ProductError(404, "not_found", "No such product.");
if (p.removedAt) throw new ProductError(410, "removed", "This product was removed by moderation.");
if (p.deletedAt && rights.creator) throw new ProductError(410, "deleted", "You deleted this product.");
return p;
}
/**
* Changes a product's info (the route checked product:edit). Only fields that change are kept in its history.
* Someone other than the creator must give a reason; locked fields need editLocked; lowering the rating needs
* rateLower (and files rated general). Returns the product, and the history entry if anything changed.
*/
async updateInfo(
byId: string,
id: string,
input: InfoInput,
reason: string,
rights: EditRights,
revertOf?: number,
): Promise<{ product: Product; entry?: number; fields: InfoField[] }> {
const p = await this.editable(id, rights);
reason = reason.trim().slice(0, 500);
if (!rights.creator && !reason)
throw new ProductError(400, "reason_needed", "Say why: the creator sees the reason with the change.");
const next: Partial<Pick<Product, InfoField>> = {};
if (input.name !== undefined) {
const name = nameRule(input.name, 64);
if (!name) throw new ProductError(400, "invalid", "Names are 1-64 characters.");
set.name = name;
next.name = name;
}
if (input.description !== undefined) {
if (input.description.length > maxDescription)
throw new ProductError(400, "invalid", "That description is too long.");
set.description = cleanHTML(input.description);
next.description = cleanHTML(input.description);
}
if (input.rating !== undefined) {
if (input.rating === "adult") set.rating = "adult";
else if (input.rating === "general" && p.rating === "adult")
// Lowering is reviewed by moderators first (design.md); until that exists, it's refused.
throw new ProductError(400, "review_needed", "Lowering a rating needs a moderator's review.");
if (input.rating !== "general" && input.rating !== "adult")
throw new ProductError(400, "invalid", "The rating must be general or adult.");
next.rating = input.rating;
}
const [updated] = await this.db.update(product).set(set).where(eq(product.id, id)).returning();
return updated!;
if (input.tags !== undefined) {
const tags = checkTags(input.tags);
if (!tags)
throw new ProductError(400, "invalid", "Up to 10 tags, each up to 24 letters, digits, spaces or dashes.");
next.tags = tags;
}
if (input.listed !== undefined) next.listed = input.listed;
if (input.category !== undefined) {
if (input.category === null) next.category = null;
else {
const path = (await this.categoryChoices(p)).find((c) => c.at(-1)!.id === input.category);
if (!path)
throw new ProductError(400, "invalid", "Choose one of the categories offered for this product.");
next.category = path;
}
}
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
const changes: Record<string, { from: unknown; to: unknown }> = {};
for (const f of infoFields)
if (next[f] !== undefined && !same(next[f], p[f])) changes[f] = { from: p[f], to: next[f] };
const fields = Object.keys(changes) as InfoField[];
if (fields.length === 0) return { product: p, fields };
const locked = fields.filter((f) => p.locked.includes(f));
if (locked.length && !rights.editLocked)
throw new ProductError(403, "locked", `A moderator locked this product's ${locked.join(", ")}.`);
if (changes.rating?.to === "general") {
if (!rights.rateLower)
throw new ProductError(400, "review_needed", "Lowering a rating needs a moderator's review.");
await this.checkFilesGeneral(id);
}
return this.db.transaction(async (tx) => {
const [updated] = await tx.update(product).set(next).where(eq(product.id, id)).returning();
const [entry] = await tx
.insert(productInfoChange)
.values({ productId: id, byId, kind: revertOf ? "revert" : "edit", changes, reason, revertOf })
.returning({ id: productInfoChange.id });
return { product: updated!, entry: entry!.id, fields };
});
}
/** Refuses (400 files_adult) if a revision of the product that isn't retracted is rated adult. */
async checkFilesGeneral(id: string) {
const [adultFiles] = await this.db
.select({ n: productRevision.number })
.from(productRevision)
.where(and(eq(productRevision.productId, id), eq(productRevision.rating, "adult"), eq(productRevision.retracted, false)))
.limit(1);
if (adultFiles)
throw new ProductError(400, "files_adult", `Revision ${adultFiles.n}'s files are rated adult; retract it first.`);
}
/** A draft becomes published: listed (unless unlisted), and people can get it. */
async publish(byId: string, id: string) {
const p = await this.editable(id, { creator: true, editLocked: false, rateLower: false });
if (p.status !== "draft") throw new ProductError(409, "published", "It's published already.");
if (!nameRule(p.name, 64)) throw new ProductError(400, "invalid", "Give it a name first.");
return this.db.transaction(async (tx) => {
const [updated] = await tx
.update(product)
.set({ status: "published", publishedAt: new Date() })
.where(eq(product.id, id))
.returning();
await tx
.insert(productInfoChange)
.values({ productId: id, byId, kind: "publish", changes: { status: { from: "draft", to: "published" } } });
return updated!;
});
}
/** Moderators lock info fields (the route checked product:lock); the reason is kept in the history. */
async setLocks(byId: string, id: string, fields: string[], reason: string) {
const p = await this.editable(id, { creator: false, editLocked: true, rateLower: true });
const want = infoFields.filter((f) => fields.includes(f));
if (want.length !== new Set(fields).size)
throw new ProductError(400, "invalid", `Only these can be locked: ${infoFields.join(", ")}.`);
reason = reason.trim().slice(0, 500);
if (!reason) throw new ProductError(400, "reason_needed", "Say why: the creator sees the reason.");
if (JSON.stringify(want) === JSON.stringify(infoFields.filter((f) => p.locked.includes(f)))) return p;
return this.db.transaction(async (tx) => {
const [updated] = await tx.update(product).set({ locked: want }).where(eq(product.id, id)).returning();
await tx
.insert(productInfoChange)
.values({ productId: id, byId, kind: "lock", changes: { locked: { from: p.locked, to: want } }, reason });
return updated!;
});
}
/**
* The categories a product may be filed under (docs/products.md): every IMVU category path the hub has seen on a
* revision's parent, and each step of those paths, under the same top-level category as its own parent's (any, if
* its parent's is unknown). Keeping the top level keeps it the same kind of product (clothing, furniture, rooms).
*/
async categoryChoices(p: Product): Promise<CategoryPath[]> {
const parent = (await this.latestParent(p))?.parentInfo?.categories ?? [];
const seen = await this.db
.selectDistinct({ path: sql<CategoryPath>`${productRevision.parentInfo}->'categories'` })
.from(productRevision)
.where(sql`jsonb_array_length(coalesce(${productRevision.parentInfo}->'categories', '[]'::jsonb)) > 0`);
const byId = new Map<number, CategoryPath>();
for (const path of [parent, ...seen.map((s) => s.path)])
for (let i = 0; i < path.length; i++)
if (!byId.has(path[i]!.id)) byId.set(path[i]!.id, path.slice(0, i + 1).map((c) => ({ id: c.id, name: c.name })));
const top = parent[0]?.id;
const label = (c: CategoryPath) => c.map((x) => x.name).join(" / ");
return [...byId.values()].filter((c) => top === undefined || c[0]!.id === top).sort((a, b) => label(a).localeCompare(label(b)));
}
/** A product's info history, newest first, with who made each change. */
async history(id: string) {
return this.db
.select({
id: productInfoChange.id,
at: productInfoChange.createdAt,
kind: productInfoChange.kind,
changes: productInfoChange.changes,
reason: productInfoChange.reason,
revertOf: productInfoChange.revertOf,
byId: productInfoChange.byId,
by: user.displayUsername,
})
.from(productInfoChange)
.leftJoin(user, eq(user.id, productInfoChange.byId))
.where(eq(productInfoChange.productId, id))
.orderBy(desc(productInfoChange.id));
}
/** Puts back what a history entry changed, as a new entry (the same rules as an edit). */
async revert(byId: string, id: string, entryId: number, reason: string, rights: EditRights) {
const [e] = await this.db
.select()
.from(productInfoChange)
.where(and(eq(productInfoChange.id, entryId), eq(productInfoChange.productId, id)));
if (!e || (e.kind !== "edit" && e.kind !== "revert")) throw new ProductError(404, "not_found", "No such change to undo.");
const input: Record<string, unknown> = {};
for (const f of infoFields) if (e.changes[f]) input[f] = e.changes[f].from;
// Categories are kept as paths; an edit takes the category's ID.
if (Array.isArray(input.category)) input.category = (input.category as CategoryPath).at(-1)?.id ?? null;
const done = await this.updateInfo(byId, id, input as InfoInput, reason, rights, e.id);
if (done.fields.length === 0) throw new ProductError(409, "unchanged", "Its info is already as it was before that change.");
return done;
}
/** Deletes drafts never published within draftDays; their catalogs are told to delete the files. */
async purgeDrafts(now = new Date()): Promise<number> {
const before = new Date(now.getTime() - draftDays * 24 * 60 * 60 * 1000);
const stale = await this.db
.select({ id: product.id })
.from(product)
.where(and(eq(product.status, "draft"), sql`${product.createdAt} < ${before.toISOString()}::timestamptz`));
for (const { id } of stale) {
await this.db.transaction(async (tx) => {
const hosted = await tx
.select({ catalogId: hosting.catalogId, number: hosting.number, files: productRevision.files })
.from(hosting)
.innerJoin(productRevision, and(eq(productRevision.productId, hosting.productId), eq(productRevision.number, hosting.number)))
.where(eq(hosting.productId, id));
for (const h of hosted)
await tx
.insert(catalogChange)
.values({ catalogId: h.catalogId, data: { type: "delete", product: id, revision: h.number, files: h.files } });
await tx.delete(hosting).where(eq(hosting.productId, id));
await tx.delete(product).where(eq(product.id, id));
});
}
return stale.length;
}
/**
* Products for the console: a person's own, or with `all` (moderators) everyone's; drafts, unlisted, deleted and
* removed ones included. `status`: draft, published, unlisted, deleted, removed or locked.
*/
async manage(opts: { creatorId?: string; q?: string; status?: string; limit?: number }) {
const conds = [ne(product.latest, 0)];
if (opts.creatorId) conds.push(eq(product.creatorId, opts.creatorId));
if (opts.q) {
const like = `%${opts.q.replace(/[%_\\]/g, (c) => "\\" + c)}%`;
conds.push(or(ilike(product.name, like), eq(product.id, opts.q), ilike(user.username, like))!);
}
const live = and(isNull(product.deletedAt), isNull(product.removedAt))!;
switch (opts.status) {
case "draft":
conds.push(eq(product.status, "draft"), live);
break;
case "published":
conds.push(eq(product.status, "published"), eq(product.listed, true), live);
break;
case "unlisted":
conds.push(eq(product.status, "published"), eq(product.listed, false), live);
break;
case "deleted":
conds.push(sql`${product.deletedAt} is not null`, isNull(product.removedAt));
break;
case "removed":
conds.push(sql`${product.removedAt} is not null`);
break;
case "locked":
conds.push(sql`jsonb_array_length(${product.locked}) > 0`);
break;
}
return this.db
.select({
product,
creator: user.displayUsername,
creatorUsername: user.username,
parent: productRevision.parent,
parentInfo: productRevision.parentInfo,
libraries: sql<number>`(select count(*) from ${library} l where l.product_id = ${product.id})::int`,
})
.from(product)
.innerJoin(user, eq(user.id, product.creatorId))
.leftJoin(productRevision, latestJoin)
.where(and(...conds))
.orderBy(desc(product.updatedAt))
.limit(Math.max(1, Math.min(opts.limit ?? 100, 200)));
}
/** How many drafts a person has (for the console's to-dos). */
async draftCount(creatorId: string) {
const [row] = await this.db
.select({ n: sql<number>`count(*)::int` })
.from(product)
.where(and(eq(product.creatorId, creatorId), eq(product.status, "draft"), isNull(product.deletedAt), ne(product.latest, 0)));
return row?.n ?? 0;
}
async retract(personId: string, id: string, number: number) {
@@ -427,7 +807,7 @@ export class Products {
.innerJoin(product, eq(product.id, library.productId))
.innerJoin(user, eq(user.id, product.creatorId))
.leftJoin(productRevision, latestJoin)
.where(and(eq(library.userId, personId), isNull(product.removedAt)))
.where(and(eq(library.userId, personId), isNull(product.removedAt), availableTo(personId)))
.orderBy(desc(library.addedAt));
}
@@ -439,13 +819,35 @@ export class Products {
return row;
}
async add(personId: string, productId: string, adult: boolean) {
const p = await this.get(productId, adult);
async add(personId: string, productId: string, adult: boolean, viewer?: ProductViewer) {
const p = await this.get(productId, adult, viewer);
// Seeing an adult product is open to its creator and moderators; getting it isn't.
if (p.product.rating === "adult" && !adult) throw new ProductError(404, "not_found", "No such product.");
if (p.product.status !== "published") throw new ProductError(409, "draft", "This product isn't published yet.");
if (p.product.deletedAt && !(await this.inLibrary(personId, productId)))
throw new ProductError(410, "deleted", "Its creator deleted this product.");
if (!(await this.available(personId, productId)))
throw new ProductError(403, "members_only", "Join a catalog hosting this product to get it.");
await this.db.insert(library).values({ userId: personId, productId }).onConflictDoNothing();
}
async available(personId: string, productId: string): Promise<boolean> {
const [row] = await this.db
.select({ id: product.id })
.from(product)
.where(and(eq(product.id, productId), availableTo(personId)));
return row !== undefined;
}
/** The approved catalogs hosting a product, with their membership rule (for "join to get it"). */
async hostingCatalogs(productId: string) {
return this.db
.selectDistinct({ id: catalog.id, name: catalog.name, membership: catalog.membership, visibility: catalog.visibility })
.from(hosting)
.innerJoin(catalog, eq(catalog.id, hosting.catalogId))
.where(and(eq(hosting.productId, productId), eq(catalog.status, "approved")));
}
async remove(personId: string, productId: string) {
await this.db.delete(library).where(and(eq(library.userId, personId), eq(library.productId, productId)));
}
@@ -470,8 +872,9 @@ export class Products {
* The revision a person uses of a product: the one they stay on, else the latest; a retracted one gives way to
* the nearest earlier one that isn't (or later, if none).
*/
async revisionFor(personId: string | undefined, productId: string, adult: boolean) {
const p = await this.get(productId, adult);
async revisionFor(personId: string | undefined, productId: string, adult: boolean, viewer?: ProductViewer) {
const p = await this.get(productId, adult, viewer);
if (p.product.rating === "adult" && !adult) throw new ProductError(404, "not_found", "No such product.");
const pin = personId ? (await this.inLibrary(personId, productId))?.stayOn : undefined;
const want = pin ?? p.product.latest;
const usable = p.revisions.filter((r) => !r.retracted);
+15 -1
View File
@@ -121,8 +121,15 @@ export type RealtimeDeps = {
hostedVisit?: (userId: string, n: number, imvuId: number) => void;
/** The IMVU username of a linked account, from its verified link ("" if unknown). */
accountName?: (imvuId: number) => Promise<string>;
/**
* Of these hub product IDs, the ones a person may wear (available to them: docs/products.md, "Member"). Outfit
* items with other hub IDs aren't relayed; items that aren't hub IDs (local packs) are.
*/
wearable?: (userId: string, productIds: string[]) => Promise<Set<string>>;
};
const hubProductID = /^[a-z2-7]{10}$/;
const maxChats = 16;
const chatPattern = /^[0-9]{1,20}$/;
const roomPattern = /^[0-9]{1,12}-[0-9]{1,12}$/;
@@ -179,6 +186,7 @@ export class Realtime {
hostedBoot: async () => {},
hostedVisit: () => {},
accountName: async () => "",
wearable: async (_, ids) => new Set(ids),
...d,
};
}
@@ -644,10 +652,16 @@ export class Realtime {
const items = m.items ?? [];
if (!Array.isArray(items)) return { type: "error", message: "items must be a list" };
if (items.length > 64) return { type: "error", message: "too many items" };
s.outfit = items
let outfit = items
.filter((it): it is Item => typeof it?.id === "string" && typeof it?.name === "string")
.filter((it) => it.id && it.id.length <= 128 && it.name.length <= 128)
.map((it) => ({ id: it.id, name: it.name, adult: it.adult === true }));
const hubIds = outfit.filter((it) => hubProductID.test(it.id)).map((it) => it.id);
if (hubIds.length > 0) {
const ok = await this.deps.wearable(s.userId, hubIds);
outfit = outfit.filter((it) => !hubProductID.test(it.id) || ok.has(it.id));
}
s.outfit = outfit;
this.changed(s.chats.keys());
return;
}
+29
View File
@@ -0,0 +1,29 @@
// The hub's settings that admins change from the console, kept in hub_setting. A setting never changed there has its
// default from the environment (so a new staging hub can start with registration closed).
import { eq, schema, type Database } from "@t5de/db";
const { hubSetting } = schema;
/** Open: new accounts can use the hub at once. Closed: they can sign in, and wait for a moderator's approval. */
export type Registration = "open" | "closed";
export const registrations: readonly Registration[] = ["open", "closed"];
export class Settings {
constructor(
private readonly db: Database,
private readonly defaults: { registration?: string } = {},
) {}
async registration(): Promise<Registration> {
const [row] = await this.db.select().from(hubSetting).where(eq(hubSetting.key, "registration"));
const value = row?.value ?? this.defaults.registration;
return value === "closed" ? "closed" : "open";
}
async setRegistration(value: Registration) {
await this.db
.insert(hubSetting)
.values({ key: "registration", value })
.onConflictDoUpdate({ target: hubSetting.key, set: { value, updatedAt: new Date() } });
}
}
+94
View File
@@ -0,0 +1,94 @@
// Personal API tokens (docs/console.md): for scripts. Each grants some of its owner's permissions at chosen scopes;
// what it may do is always the intersection with what the owner holds now. Only the hash is kept, and the token is
// shown once. Making, listing and revoking tokens takes a website session (a token can't make tokens).
import { createHash, randomBytes } from "node:crypto";
import { and, desc, eq, gt, isNull, schema, sql, type Database, type TokenGrant } from "@t5de/db";
import { ProductError } from "./products";
import { permissions, type Permission, type Permissions, type Scope } from "./permissions";
const { apiToken } = schema;
export const tokenPrefix = "t5de_pat_";
/** Active tokens a person may have at once. */
export const maxTokens = 20;
/** Grants a token may carry. */
export const maxGrants = 50;
/** The longest a token may last. */
export const maxTokenDays = 365;
const hashOf = (raw: string) => createHash("sha256").update(raw).digest("hex");
export type ApiToken = typeof apiToken.$inferSelect;
export class Tokens {
constructor(
private db: Database,
private perms: Permissions,
) {}
/** Makes a token for a person; every grant must be something they hold now. Returns the token (shown once). */
async create(who: { id: string; role: string }, name: string, days: number, grants: TokenGrant[]) {
const label = name.trim().replace(/\s+/g, " ");
if (!label || label.length > 64) throw new ProductError(400, "invalid", "Name it (at most 64 characters).");
if (!Number.isInteger(days) || days < 1 || days > maxTokenDays)
throw new ProductError(400, "invalid", `It may last 1 to ${maxTokenDays} days.`);
if (grants.length === 0 || grants.length > maxGrants)
throw new ProductError(400, "invalid", `Give it 1 to ${maxGrants} permissions.`);
const seen = new Set<string>();
const clean: TokenGrant[] = [];
for (const g of grants) {
if (!(permissions as readonly string[]).includes(g.permission))
throw new ProductError(400, "invalid", `No such permission: ${g.permission}.`);
const scope: Scope = g.scope.type === "hub" ? { type: "hub" } : { type: g.scope.type, id: g.scope.id };
if (!(await this.perms.can(who, g.permission as Permission, scope)))
throw new ProductError(400, "not_held", `You don't hold ${g.permission} there, so a token can't either.`);
const key = JSON.stringify([g.permission, scope]);
if (seen.has(key)) continue;
seen.add(key);
clean.push({ permission: g.permission, scope });
}
const [{ n } = { n: 0 }] = await this.db
.select({ n: sql<number>`count(*)::int` })
.from(apiToken)
.where(and(eq(apiToken.userId, who.id), isNull(apiToken.revokedAt), gt(apiToken.expiresAt, new Date())));
if (n >= maxTokens) throw new ProductError(409, "too_many", `You have ${maxTokens} tokens. Revoke one first.`);
const raw = tokenPrefix + randomBytes(32).toString("base64url");
const [made] = await this.db
.insert(apiToken)
.values({
id: randomBytes(8).toString("hex"),
userId: who.id,
name: label,
hash: hashOf(raw),
grants: clean,
expiresAt: new Date(Date.now() + days * 86_400_000),
})
.returning();
return { token: raw, row: made! };
}
/** A person's tokens, newest first (revoked and expired ones included, for the record). */
async list(personId: string) {
return this.db.select().from(apiToken).where(eq(apiToken.userId, personId)).orderBy(desc(apiToken.createdAt));
}
async revoke(personId: string, id: string) {
const [t] = await this.db
.update(apiToken)
.set({ revokedAt: new Date() })
.where(and(eq(apiToken.id, id), eq(apiToken.userId, personId), isNull(apiToken.revokedAt)))
.returning();
if (!t) throw new ProductError(404, "not_found", "No such token, or it's revoked already.");
return t;
}
/** The token a raw value names, if it's still good; notes its use (at most once a minute). */
async verify(raw: string): Promise<ApiToken | undefined> {
if (!raw.startsWith(tokenPrefix) || raw.length > 100) return undefined;
const [t] = await this.db.select().from(apiToken).where(eq(apiToken.hash, hashOf(raw)));
if (!t || t.revokedAt || t.expiresAt <= new Date()) return undefined;
if (!t.lastUsedAt || Date.now() - t.lastUsedAt.getTime() > 60_000)
await this.db.update(apiToken).set({ lastUsedAt: new Date() }).where(eq(apiToken.id, t.id));
return t;
}
}
+146 -7
View File
@@ -1,8 +1,10 @@
// Age verification: the one rule, providers that check a person (here a fake document-check vendor with signed
// webhooks), and IMVU's answers changing.
// Age verification: the one rule, providers that check a person (a fake document-check vendor with signed webhooks,
// and Didit's adapter against a fake Didit), limits on checks, and IMVU's answers changing.
import { createHmac } from "node:crypto";
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, schema, type Database } from "@t5de/db";
import { AgeService, type Provider } from "../src/age";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { AgeService, attemptsPerPerson, type Provider } from "../src/age";
import { ageOn, diditAgeProvider } from "../src/age/didit";
import { imvuAgeProvider } from "../src/age/imvu";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
@@ -27,6 +29,7 @@ const webhookSecret = "vendor-secret";
const fakeVendor: Provider = {
id: "vendor",
label: "ID document",
vendor: "Vendor",
scope: "person",
start: async () => {
const ref = `session-${crypto.randomUUID()}`;
@@ -39,6 +42,45 @@ const fakeVendor: Provider = {
},
};
// Didit: sessions per person (an unfinished one is given again), and each session's decision.
const diditSecret = "didit-secret";
const diditSessions = new Map<string, { id: string; vendor: string; finished: boolean; decision?: unknown }>();
const fakeDidit: typeof fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(String(input));
if (new Headers(init?.headers).get("x-api-key") !== "didit-key") return new Response("no key", { status: 401 });
if (init?.method === "POST" && url.pathname === "/v3/session/") {
const body = JSON.parse(String(init.body));
expect(body.workflow_id).toBe("workflow");
let s = [...diditSessions.values()].find((s) => s.vendor === body.vendor_data && !s.finished);
if (!s) {
s = { id: crypto.randomUUID(), vendor: body.vendor_data, finished: false };
diditSessions.set(s.id, s);
}
return Response.json({ session_id: s.id, url: `https://verify.didit.test/session/${s.id}`, status: "Not Started" }, { status: 201 });
}
const m = /^\/v3\/session\/([^/]+)\/decision\/$/.exec(url.pathname);
if (m && diditSessions.get(m[1]!)) return Response.json(diditSessions.get(m[1]!)!.decision ?? {});
return new Response("not found", { status: 404 });
}) as typeof fetch;
const didit = diditAgeProvider({ apiKey: "didit-key", workflowId: "workflow", webhookSecret: diditSecret, baseURL: "https://didit.test", fetch: fakeDidit });
/** A Didit webhook request, signed as Didit signs it (the raw body, or V2), or forged. */
function diditHook(body: Record<string, unknown>, sign: "raw" | "v2" | "forged" = "raw", timestamp = Math.floor(Date.now() / 1000)) {
const raw = JSON.stringify(body);
const hmac = (s: string, key = diditSecret) => createHmac("sha256", key).update(s).digest("hex");
const sortKeys = (v: unknown): unknown =>
Array.isArray(v)
? v.map(sortKeys)
: v && typeof v === "object"
? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys((v as Record<string, unknown>)[k])]))
: v;
const headers: Record<string, string> = { "X-Timestamp": String(timestamp), "Content-Type": "application/json" };
if (sign === "raw") headers["X-Signature"] = hmac(raw);
if (sign === "v2") headers["X-Signature-V2"] = hmac(JSON.stringify(sortKeys(body)));
if (sign === "forged") headers["X-Signature"] = hmac(raw, "wrong");
return fetch(`${base}/api/v1/age/webhook/didit`, { method: "POST", headers, body: raw });
}
let db: Database;
let close: () => Promise<void>;
let base: string;
@@ -49,8 +91,8 @@ beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL: "http://api.test", webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const imvu = new ImvuClient("http://imvu.test", fakeIMVU);
age = new AgeService(db, [imvuAgeProvider(imvu), fakeVendor]);
const hub = createApp({ db, auth, imvu, age });
age = new AgeService(db, [imvuAgeProvider(imvu), fakeVendor, didit]);
const hub = createApp({ db, auth, imvu, age, webURL });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
@@ -86,6 +128,13 @@ async function personWithAccounts(name: string, ids: { id: number; ageVerified?:
return cookie;
}
const userOf = async (name: string) => (await db.select().from(schema.user)).find((u) => u.username === name)!.id;
const startedThisMonth = async () => {
const now = new Date();
const month = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
return (await db.select().from(schema.ageCheck).where(eq(schema.ageCheck.provider, "didit"))).filter((r) => r.createdAt >= month).length;
};
const adultOf = async (cookie: { v: string }) =>
Object.fromEntries(((await call(cookie, "GET", "/api/v1/account")).json.links as any[]).map((l) => [l.imvuId, l.adult]));
@@ -102,7 +151,7 @@ test("IMVU's answer is per account, and re-checked when it expires", async () =>
test("a person's check covers all their accounts; webhooks must be signed", async () => {
const b = await personWithAccounts("ben", [{ id: 10 }, { id: 11 }]);
expect((await call(b, "GET", "/api/v1/age")).json.providers.map((p: any) => p.id)).toEqual(["imvu", "vendor"]);
expect((await call(b, "GET", "/api/v1/age")).json.providers.map((p: any) => p.id)).toEqual(["imvu", "vendor", "didit"]);
// IMVU checks accounts, not people: it can't be started this way.
expect((await call(b, "POST", "/api/v1/age/imvu/start", { returnURL: `${webURL}/account` })).status).toBe(400);
@@ -118,6 +167,96 @@ test("a person's check covers all their accounts; webhooks must be signed", asyn
expect(await adultOf(b)).toEqual({ 10: true, 11: true });
// A repeated webhook is harmless.
expect((await hook(webhookSecret, true)).status).toBe(204);
// Verified already: no more checks, with this provider or another.
const again = await call(b, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` });
expect(again).toMatchObject({ status: 409, json: { error: "refused" } });
});
test("people are sent back only to the hub's website", async () => {
const e = await personWithAccounts("eve", []);
expect((await call(e, "POST", "/api/v1/age/didit/start", { returnURL: "https://evil.test/account" })).status).toBe(400);
expect((await call(e, "POST", "/api/v1/age/didit/start", { returnURL: "//evil.test/account" })).status).toBe(400);
// A path is on the website.
expect((await call(e, "POST", "/api/v1/age/didit/start", { returnURL: "/account?age=back" })).json.kind).toBe("redirect");
});
test("Didit: signed webhooks, the age on the document, and answers changed later", async () => {
const f = await personWithAccounts("fay", [{ id: 30 }]);
const started = (await call(f, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account?age=didit` })).json;
expect(started).toMatchObject({ kind: "redirect", url: `https://verify.didit.test/session/${started.ref}` });
// Going back to an unfinished check gives the same session, and doesn't count as another.
const resumed = (await call(f, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` })).json;
expect(resumed.ref).toBe(started.ref);
expect((await call(f, "GET", "/api/v1/age")).json.checks).toHaveLength(1);
const event = (status: string, decision?: unknown) => ({
event_id: crypto.randomUUID(),
webhook_type: "status.updated",
session_id: started.ref,
status,
timestamp: Math.floor(Date.now() / 1000),
...(decision ? { decision } : {}),
});
const approved = event("Approved", { id_verifications: [{ status: "Approved", age: 31, date_of_birth: "1995-01-01" }] });
expect((await diditHook(approved, "forged")).status).toBe(401);
expect((await diditHook(approved, "raw", Math.floor(Date.now() / 1000) - 3600)).status).toBe(401); // stale
// In review: no answer yet.
expect((await diditHook(event("In Review"))).status).toBe(204);
expect((await call(f, "GET", "/api/v1/age")).json.checks[0].status).toBe("pending");
expect(await adultOf(f)).toEqual({ 30: false });
expect((await diditHook(approved, "v2")).status).toBe(204);
expect(await adultOf(f)).toEqual({ 30: true });
const [row] = await db.select().from(schema.ageCheck).where(eq(schema.ageCheck.providerRef, started.ref));
expect(row).toMatchObject({ provider: "didit", method: "id_document", status: "complete", overEighteen: true, imvuId: null });
// A reviewer at Didit declines it afterwards: the answer is taken back.
expect((await diditHook(event("Declined"))).status).toBe(204);
expect(await adultOf(f)).toEqual({ 30: false });
expect((await call(f, "GET", "/api/v1/age")).json.checks[0].status).toBe("revoked");
});
test("Didit: under 18, and a decision fetched when the webhook has none", async () => {
const g = await personWithAccounts("gus", [{ id: 40 }]);
const started = (await call(g, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` })).json;
const session = diditSessions.get(started.ref)!;
session.finished = true;
session.decision = { id_verifications: [{ date_of_birth: `${new Date().getUTCFullYear() - 17}-12-31` }] };
const body = { webhook_type: "status.updated", session_id: started.ref, status: "Approved", timestamp: 0 };
expect((await diditHook(body)).status).toBe(204);
expect(await adultOf(g)).toEqual({ 40: false });
expect((await call(g, "GET", "/api/v1/age")).json.checks[0]).toMatchObject({ status: "complete", overEighteen: false });
});
test("checks are limited per person and by a provider's monthly allowance", async () => {
const h = await personWithAccounts("hal", []);
// Each abandoned check is a new one.
for (let i = 0; i < attemptsPerPerson; i++) {
const s = (await call(h, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` })).json;
diditSessions.get(s.ref)!.finished = true;
const body = { webhook_type: "status.updated", session_id: s.ref, status: "Abandoned", timestamp: 0 };
expect((await diditHook(body)).status).toBe(204);
}
const limited = await call(h, "POST", "/api/v1/age/didit/start", { returnURL: `${webURL}/account` });
expect(limited).toMatchObject({ status: 409, json: { error: "refused" } });
expect(limited.json.message).toContain("30 days");
// The month's allowance is everyone's (here a service with room for one more).
const capped = new AgeService(db, [{ ...didit, monthlyLimit: (await startedThisMonth()) + 1 }]);
await personWithAccounts("ivy", []);
await personWithAccounts("joe", []);
const ivy = await capped.start({ userId: await userOf("ivy") }, "didit", `${webURL}/account`);
await expect(capped.start({ userId: await userOf("joe") }, "didit", `${webURL}/account`)).rejects.toThrow("used up");
// Ivy can still go back to hers.
expect(await capped.start({ userId: await userOf("ivy") }, "didit", `${webURL}/account`)).toEqual(ivy);
});
test("birth dates to ages", () => {
const day = new Date("2026-11-03T12:00:00Z");
expect(ageOn("2008-11-03", day)).toBe(18);
expect(ageOn("2008-11-04", day)).toBe(17);
expect(ageOn("2008-12-01", day)).toBe(17);
expect(ageOn("nonsense", day)).toBeUndefined();
});
test("a moved account takes nobody's age with it", async () => {
+205
View File
@@ -0,0 +1,205 @@
// File blocks (docs/products.md): moderation blocks a file network-wide; products using it are removed, catalogs told
// to delete it, and uploads with it refused.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const fakeIMVU: typeof fetch = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname.startsWith("/product/")) return Response.json({ status: "failure" }, { status: 404 });
const u = [...accounts.values()].find(
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
);
return Response.json({
denormalized: u
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
: {},
});
}) as typeof fetch;
// Catalog addresses that answer /health (for address changes).
const healthy = new Set<string>(["https://moved.example.test"]);
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({
db,
auth,
imvu: new ImvuClient("http://imvu.test", fakeIMVU),
apiURL,
webURL,
catalogHealthy: async (url) => healthy.has(url),
});
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Person = { cookie: string; name: string };
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const res = await fetch(base + path, {
method,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(p ? { Cookie: p.cookie } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json: any;
try {
json = JSON.parse(text);
} catch {
json = text;
}
return { status: res.status, json };
}
async function person(name: string): Promise<Person> {
const res = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
const file = (name: string, n: number) => ({ name, sha256: n.toString(16).padStart(64, "0"), size: 100 * n });
/** A person's catalog, registered and approved; its key's Authorization header. */
async function catalogOf(owner: Person, admin: Person, name: string, membership = "open") {
const reg = await call(owner, "POST", "/api/v1/catalogs", {
name,
url: `https://${name.toLowerCase().replace(/\W/g, "")}.example.test`,
contact: "[email protected]",
visibility: "public",
membership,
});
expect(reg.status).toBe(201);
const id = reg.json.catalog.id as string;
expect((await call(admin, "POST", `/api/v1/console/catalogs/${id}/approve`)).status).toBe(200);
return { id, auth: { Authorization: `Catalog ${id}:${reg.json.key}` } };
}
/** A product uploaded by a person to a catalog; its ID. */
async function upload(maker: Person, c: { id: string; auth: Record<string, string> }, name: string, n: number, rating = "general") {
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
expect(tok.status).toBe(200);
const r = await call(
undefined,
"POST",
"/api/v1/catalog/revisions",
{ uploadToken: tok.json.token, files: [file("index.xml", n)], rating, parent: 0, name, notes: "" },
c.auth,
);
expect(r.status).toBe(201);
expect((await call(maker, "POST", `/api/v1/products/${r.json.product}/publish`)).status).toBe(200);
return r.json.product as string;
}
/** A revision with these files, by a person, to a catalog: the answer. */
async function uploadFiles(maker: Person, c: { id: string; auth: Record<string, string> }, name: string, files: unknown[]) {
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
return call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: tok.json.token, files, rating: "general", parent: 0, name, notes: "" }, c.auth);
}
let admin: Person;
let mod: Person;
test("the first account is the admin; a moderator", async () => {
admin = await person("admin1");
mod = await person("warden");
const id = (await call(mod, "GET", "/api/v1/me")).json.person.id;
expect((await call(admin, "POST", `/api/v1/console/people/${id}/role`, { role: "moderator" })).status).toBe(200);
});
test("blocking a file removes the products using it, tells their catalogs, and refuses it in uploads", async () => {
const owner = await person("shelfowner");
const maker = await person("maker");
const copier = await person("copier");
const c = await catalogOf(owner, admin, "Block Shelf");
const other = await catalogOf(copier, admin, "Copy Shelf");
const logo = file("logo.png", 2).sha256;
const tee = await upload(maker, c, "Logo Tee", 1);
const second = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id, product: tee });
expect(
(await call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: second.json.token, files: [file("index.xml", 1), file("logo.png", 2)], rating: "general", parent: 0, name: "", notes: "Added the logo" }, c.auth)).status,
).toBe(201);
const copy = (await uploadFiles(copier, other, "Copy Tee", [file("index.xml", 5), file("logo.png", 2)])).json.product as string;
const plain = await upload(maker, c, "Plain Tee", 3);
// Only those who can remove products hub-wide.
for (const p of [owner, maker]) {
expect((await call(p, "GET", "/api/v1/blocks")).status).toBe(403);
expect((await call(p, "GET", `/api/v1/blocks/${logo}`)).status).toBe(403);
expect((await call(p, "PUT", `/api/v1/blocks/${logo}`, { reason: "x" })).status).toBe(403);
}
expect((await call(owner, "GET", "/api/v1/console")).json.sections).not.toContain("blocks");
expect((await call(mod, "GET", "/api/v1/console")).json.sections).toContain("blocks");
expect((await call(mod, "GET", "/api/v1/blocks/not-a-hash")).status).toBe(400);
// What blocking it would remove.
const preview = (await call(mod, "GET", `/api/v1/blocks/${logo}`)).json;
expect(preview.block).toBeNull();
expect(preview.products.map((p: any) => [p.name, p.creatorUsername, p.revisions, p.removed]).sort()).toEqual([
["Copy Tee", "copier", [1], false],
["Logo Tee", "maker", [2], false],
]);
const blocked = await call(mod, "PUT", `/api/v1/blocks/${logo}`, { reason: "Trademarked logo" });
expect(blocked.status).toBe(200);
expect(blocked.json.removed.map((p: any) => p.id).sort()).toEqual([copy, tee].sort());
expect((await call(mod, "PUT", `/api/v1/blocks/${logo}`, { reason: "Again" })).json.error).toBe("blocked");
expect((await call(undefined, "GET", `/api/v1/products/${tee}`)).status).toBe(410);
expect((await call(undefined, "GET", `/api/v1/products/${copy}`)).status).toBe(410);
expect((await call(undefined, "GET", `/api/v1/products/${plain}`)).status).toBe(200);
expect((await call(mod, "GET", `/api/v1/blocks/${logo}`)).json.block).toMatchObject({ sha256: logo, reason: "Trademarked logo", by: "warden" });
expect((await call(mod, "GET", "/api/v1/blocks")).json.blocks.map((b: any) => b.sha256)).toEqual([logo]);
// Each catalog that hosts it is told to delete it.
for (const k of [c, other]) {
const feed = (await call(undefined, "GET", "/api/v1/catalog/changes", undefined, k.auth)).json.changes;
expect(feed.filter((x: any) => x.type === "block")).toEqual([{ type: "block", sha256: logo }]);
}
// Creators are told, and may appeal the removal.
const told = (await call(maker, "GET", "/api/v1/notifications")).json.notifications[0];
expect(told).toMatchObject({ type: "product_removed", data: { product: tee, reason: "Trademarked logo" } });
const removal = (await call(maker, "GET", `/api/v1/console/audit?action=product.remove`)).json.entries[0];
expect(removal).toMatchObject({ target: tee, appealable: true, detail: { file: logo } });
// Uploads with it are refused, and moderators see who tried.
const again = await uploadFiles(copier, other, "Copy Tee 2", [file("index.xml", 6), file("logo2.png", 2)]);
expect(again.status).toBe(409);
expect(again.json.error).toBe("blocked");
const tried = (await call(mod, "GET", "/api/v1/console/audit?action=file.blocked_upload")).json.entries[0];
expect(tried).toMatchObject({ actor: "copier", tags: { catalog: other.id }, detail: { files: [{ name: "logo2.png", sha256: logo }] } });
// Unblocking lets it in again; the products it removed stay removed until restored.
expect((await call(owner, "DELETE", `/api/v1/blocks/${logo}`)).status).toBe(403);
expect((await call(mod, "DELETE", `/api/v1/blocks/${logo}`, { reason: "Licensed after all" })).status).toBe(204);
expect((await call(mod, "DELETE", `/api/v1/blocks/${logo}`)).status).toBe(404);
expect((await uploadFiles(copier, other, "Copy Tee 2", [file("index.xml", 6), file("logo2.png", 2)])).status).toBe(201);
expect((await call(undefined, "GET", `/api/v1/products/${tee}`)).status).toBe(410);
expect((await call(mod, "POST", `/api/v1/products/${tee}/unremove`, { reason: "Licensed" })).status).toBe(200);
expect((await call(undefined, "GET", `/api/v1/products/${tee}`)).status).toBe(200);
expect((await call(mod, "GET", "/api/v1/console/audit?action=file.unblock")).json.entries[0]).toMatchObject({ target: logo, detail: { reason: "Licensed after all" } });
});
+308
View File
@@ -0,0 +1,308 @@
// Cases (docs/console.md): reports, rating reviews, deletion and removal requests, appeals; their threads, who sees
// and decides them, what deciding does; and notifications.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const fakeIMVU: typeof fetch = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname.startsWith("/product/")) return Response.json({ status: "failure" }, { status: 404 });
const u = [...accounts.values()].find(
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
);
return Response.json({
denormalized: u
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
: {},
});
}) as typeof fetch;
// Catalog addresses that answer /health (for address changes).
const healthy = new Set<string>(["https://moved.example.test"]);
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({
db,
auth,
imvu: new ImvuClient("http://imvu.test", fakeIMVU),
apiURL,
webURL,
catalogHealthy: async (url) => healthy.has(url),
});
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Person = { cookie: string; name: string };
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const res = await fetch(base + path, {
method,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(p ? { Cookie: p.cookie } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json: any;
try {
json = JSON.parse(text);
} catch {
json = text;
}
return { status: res.status, json };
}
async function person(name: string): Promise<Person> {
const res = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
const file = (name: string, n: number) => ({ name, sha256: n.toString(16).padStart(64, "0"), size: 100 * n });
/** A person's catalog, registered and approved; its key's Authorization header. */
async function catalogOf(owner: Person, admin: Person, name: string, membership = "open") {
const reg = await call(owner, "POST", "/api/v1/catalogs", {
name,
url: `https://${name.toLowerCase().replace(/\W/g, "")}.example.test`,
contact: "[email protected]",
visibility: "public",
membership,
});
expect(reg.status).toBe(201);
const id = reg.json.catalog.id as string;
expect((await call(admin, "POST", `/api/v1/console/catalogs/${id}/approve`)).status).toBe(200);
return { id, auth: { Authorization: `Catalog ${id}:${reg.json.key}` } };
}
/** A product uploaded by a person to a catalog; its ID. */
async function upload(maker: Person, c: { id: string; auth: Record<string, string> }, name: string, n: number, rating = "general") {
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
expect(tok.status).toBe(200);
const r = await call(
undefined,
"POST",
"/api/v1/catalog/revisions",
{ uploadToken: tok.json.token, files: [file("index.xml", n)], rating, parent: 0, name, notes: "" },
c.auth,
);
expect(r.status).toBe(201);
expect((await call(maker, "POST", `/api/v1/products/${r.json.product}/publish`)).status).toBe(200);
return r.json.product as string;
}
let admin: Person;
let mod: Person;
const notes = async (p: Person) => (await call(p, "GET", "/api/v1/notifications")).json;
test("the first account is the admin; a moderator", async () => {
admin = await person("admin1");
mod = await person("warden");
const id = (await call(mod, "GET", "/api/v1/me")).json.person.id;
expect((await call(admin, "POST", `/api/v1/console/people/${id}/role`, { role: "moderator" })).status).toBe(200);
});
test("reports: anyone signed in reports; the hosting catalog's team and moderators decide; who reported stays private", async () => {
const owner = await person("shelfowner");
const maker = await person("maker");
const reporter = await person("reporter");
const outsider = await person("outsider");
const c = await catalogOf(owner, admin, "Report Shelf");
const hat = await upload(maker, c, "Odd Hat", 1);
expect((await call(undefined, "POST", "/api/v1/cases", { kind: "report", about: { product: hat }, reason: "x" })).status).toBe(401);
expect((await call(reporter, "POST", "/api/v1/cases", { kind: "report", about: { product: hat }, reason: " " })).json.error).toBe("reason_needed");
const made = await call(reporter, "POST", "/api/v1/cases", { kind: "report", about: { product: hat }, reason: "Copied from another creator" });
expect(made.status).toBe(201);
const id = made.json.case.id;
expect(made.json.case).toMatchObject({ kind: "report", status: "open", tags: { product: hat }, tagNames: { [hat]: "Odd Hat" } });
expect((await call(reporter, "POST", "/api/v1/cases", { kind: "report", about: { product: hat }, reason: "Again" })).json.error).toBe("already_reported");
expect((await call(reporter, "POST", "/api/v1/cases", { kind: "report", about: { person: "reporter" }, reason: "Me" })).status).toBe(400);
// Who sees it: the reporter, the hosting catalog's team, moderators. Not its creator, not others.
const ids = async (p: Person) => (await call(p, "GET", "/api/v1/cases")).json.cases.map((x: any) => x.id);
expect(await ids(reporter)).toEqual([id]);
expect(await ids(owner)).toContain(id);
expect(await ids(mod)).toContain(id);
expect(await ids(maker)).not.toContain(id);
expect((await call(maker, "GET", `/api/v1/cases/${id}`)).status).toBe(404);
expect((await call(outsider, "GET", `/api/v1/cases/${id}`)).status).toBe(404);
expect((await call(owner, "GET", `/api/v1/cases/${id}`)).json).toMatchObject({ canDecide: true, canAssign: false });
expect((await call(reporter, "GET", `/api/v1/cases/${id}`)).json).toMatchObject({ canDecide: false, case: { openedBy: "reporter" } });
// The catalog's team decides it without knowing who reported; moderators know.
expect((await call(owner, "GET", `/api/v1/cases/${id}`)).json.case.openedBy).toBe("");
expect((await call(mod, "GET", `/api/v1/cases/${id}`)).json.case.openedBy).toBe("reporter");
expect((await call(owner, "GET", "/api/v1/console")).json.todo.cases).toBe(1);
expect((await call(owner, "GET", "/api/v1/console")).json.sections).toContain("cases");
// A thread: replies reach the reporter; internal notes stay with those deciding.
expect((await call(owner, "POST", `/api/v1/cases/${id}/notes`, { body: "Looking into it" })).status).toBe(200);
expect((await call(owner, "POST", `/api/v1/cases/${id}/notes`, { body: "Probably fine", internal: true })).status).toBe(200);
expect((await call(reporter, "GET", `/api/v1/cases/${id}`)).json.notes.map((n: any) => n.body)).toEqual(["Looking into it"]);
expect((await call(owner, "GET", `/api/v1/cases/${id}`)).json.notes.map((n: any) => [n.body, n.internal])).toEqual([
["Looking into it", false],
["Probably fine", true],
]);
expect((await notes(reporter)).notifications[0]).toMatchObject({ type: "case_note", data: { case: id, by: "shelfowner" } });
// Assigning is for moderators, to moderators.
expect((await call(owner, "POST", `/api/v1/cases/${id}/assign`, { to: "shelfowner" })).status).toBe(403);
expect((await call(admin, "POST", `/api/v1/cases/${id}/assign`, { to: "outsider" })).json.error).toBe("invalid");
expect((await call(admin, "POST", `/api/v1/cases/${id}/assign`, { to: "warden" })).json.case.assignee).toBe("warden");
// Deciding: the catalog's owner declines it; the reporter is told; it's done.
expect((await call(outsider, "POST", `/api/v1/cases/${id}/decide`, { decision: "resolve", resolution: "" })).status).toBe(404);
const decided = await call(owner, "POST", `/api/v1/cases/${id}/decide`, { decision: "decline", resolution: "It's an original." });
expect(decided.json.case).toMatchObject({ status: "declined", resolution: "It's an original.", decidedBy: "shelfowner" });
expect((await call(owner, "POST", `/api/v1/cases/${id}/decide`, { decision: "resolve", resolution: "" })).json.error).toBe("decided");
expect((await notes(reporter)).notifications[0]).toMatchObject({ type: "case_decided", data: { case: id, status: "declined" } });
expect((await call(reporter, "GET", "/api/v1/me")).json.person.unread).toBe(2);
expect((await call(reporter, "POST", "/api/v1/notifications/read", {})).json.unread).toBe(0);
// The audit log keeps who reported out of what the product's creator can read.
const audit = (await call(maker, "GET", `/api/v1/console/audit?product=${hat}`)).json.entries.map((e: any) => e.action);
expect(audit).not.toContain("case.open");
// Reports are limited: ten an hour.
for (let i = 0; i < 9; i++) {
const p = await person(`spam${i}`);
expect((await call(reporter, "POST", "/api/v1/cases", { kind: "report", about: { person: p.name }, reason: "Spam" })).status).toBe(201);
}
expect((await call(reporter, "POST", "/api/v1/cases", { kind: "report", about: { catalog: c.id }, reason: "One more" })).status).toBe(429);
});
test("rating reviews: a creator lowering a rating asks moderators; resolving lowers it", async () => {
const owner = await person("reviewshelf");
const maker = await person("rater");
const c = await catalogOf(owner, admin, "Review Shelf");
const top = await upload(maker, c, "Plain Top", 2);
expect((await call(maker, "PATCH", `/api/v1/products/${top}`, { rating: "adult" })).json.review).toBeNull();
// Lowering it opens a case (one at a time); other fields in the same edit still change.
const asked = await call(maker, "PATCH", `/api/v1/products/${top}`, { rating: "general", name: "Plain Tee", reason: "Nothing adult about it" });
expect(asked.status).toBe(200);
expect(asked.json.product).toMatchObject({ rating: "adult", name: "Plain Tee" });
const review = asked.json.review as number;
expect(review).toBeGreaterThan(0);
expect((await call(maker, "PATCH", `/api/v1/products/${top}`, { rating: "general" })).json.review).toBe(review);
const kase = (await call(maker, "GET", `/api/v1/cases/${review}`)).json;
expect(kase.case).toMatchObject({ kind: "rating-review", reason: "Nothing adult about it", openedBy: "rater" });
expect(kase.canDecide).toBe(false);
// Its catalog's team doesn't see or decide ratings; moderators do.
expect((await call(owner, "POST", `/api/v1/cases/${review}/decide`, { decision: "resolve", resolution: "" })).status).toBe(404);
expect((await call(mod, "POST", `/api/v1/cases/${review}/decide`, { decision: "resolve", resolution: "Agreed" })).json.case.status).toBe("resolved");
const history = (await call(maker, "GET", `/api/v1/products/${top}/history`)).json.entries;
expect(history[0]).toMatchObject({ by: "warden", reason: "Agreed", changes: { rating: { from: "adult", to: "general" } } });
const types = (await notes(maker)).notifications.map((n: any) => n.type);
expect(types).toContain("case_decided");
expect(types).toContain("product_edited");
// Files rated adult can't be lowered by anyone: the creator is told at once.
const lace = await upload(maker, c, "Lace", 3, "adult");
expect((await call(maker, "PATCH", `/api/v1/products/${lace}`, { rating: "general" })).json.error).toBe("files_adult");
});
test("a catalog's deletion goes to moderators; resolving it deletes the catalog", async () => {
const owner = await person("leaver");
const operator = await person("leaverop");
const c = await catalogOf(owner, admin, "Leaving Shelf");
expect((await call(owner, "PUT", `/api/v1/catalogs/${c.id}/team/leaverop?role=catalog-operator`, { role: "catalog-operator" })).status).toBe(200);
expect((await call(operator, "POST", `/api/v1/catalogs/${c.id}/delete`, { reason: "Done" })).json.missing.permission).toBe("catalog:delete-request");
const first = (await call(owner, "POST", `/api/v1/catalogs/${c.id}/delete`, { reason: "Closing shop" })).json.case;
expect((await call(owner, "POST", `/api/v1/catalogs/${c.id}/delete`, { reason: "Again" })).json).toMatchObject({ error: "requested", case: first });
// Its team sees the case; a decline leaves the catalog as it was.
expect((await call(operator, "GET", `/api/v1/cases/${first}`)).json.case.kind).toBe("catalog-deletion");
expect((await call(mod, "POST", `/api/v1/cases/${first}/decide`, { decision: "decline", resolution: "Move your products first" })).status).toBe(200);
expect((await call(owner, "GET", `/api/v1/catalogs/${c.id}`)).json.catalog.status).toBe("approved");
const second = (await call(owner, "POST", `/api/v1/catalogs/${c.id}/delete`, { reason: "Moved them" })).json.case;
expect((await call(mod, "POST", `/api/v1/cases/${second}/decide`, { decision: "resolve", resolution: "" })).status).toBe(200);
expect((await call(owner, "GET", `/api/v1/catalogs/${c.id}`)).json.catalog.status).toBe("deleted");
expect((await call(undefined, "GET", "/api/v1/catalog/changes", undefined, c.auth)).status).toBe(401);
});
test("removal requests: a catalog's team asks; moderators remove the product everywhere", async () => {
const owner = await person("cautious");
const maker = await person("copier");
const c = await catalogOf(owner, admin, "Careful Shelf");
const shoes = await upload(maker, c, "Copied Shoes", 4);
expect((await call(maker, "POST", "/api/v1/cases", { kind: "removal-request", about: { product: shoes }, catalog: c.id, reason: "x" })).status).toBe(403);
const asked = await call(owner, "POST", "/api/v1/cases", { kind: "removal-request", about: { product: shoes }, catalog: c.id, reason: "Stolen work" });
expect(asked.status).toBe(201);
expect((await call(owner, "POST", `/api/v1/cases/${asked.json.case.id}/decide`, { decision: "resolve", resolution: "" })).status).toBe(403);
expect((await call(mod, "POST", `/api/v1/cases/${asked.json.case.id}/decide`, { decision: "resolve", resolution: "Confirmed" })).status).toBe(200);
expect((await call(undefined, "GET", `/api/v1/products/${shoes}`)).status).toBe(410);
expect((await notes(maker)).notifications[0]).toMatchObject({ type: "product_removed", data: { product: shoes, reason: "Confirmed" } });
});
test("appeals: the person affected appeals an action once; another moderator decides", async () => {
const owner = await person("appealshelf");
const maker = await person("appealer");
const c = await catalogOf(owner, admin, "Appeal Shelf");
const coat = await upload(maker, c, "Fine Coat", 5);
expect((await call(mod, "POST", `/api/v1/products/${coat}/remove`, { reason: "Looks stolen" })).status).toBe(200);
expect((await notes(maker)).notifications[0]).toMatchObject({ type: "product_removed", data: { name: "Fine Coat", reason: "Looks stolen" } });
// The creator's audit log offers the removal for appeal; others can't appeal it.
const entry = (await call(maker, "GET", `/api/v1/console/audit?product=${coat}`)).json.entries.find((e: any) => e.action === "product.remove");
expect(entry.appealable).toBe(true);
expect((await call(owner, "POST", "/api/v1/cases", { kind: "appeal", audit: entry.id, reason: "x" })).status).toBe(404);
const appeal = await call(maker, "POST", "/api/v1/cases", { kind: "appeal", audit: entry.id, reason: "I made it from scratch" });
expect(appeal.json.case).toMatchObject({ kind: "appeal", data: { action: "product.remove" } });
expect((await call(maker, "POST", "/api/v1/cases", { kind: "appeal", audit: entry.id, reason: "Again" })).json.error).toBe("appealed");
// The moderator who removed it doesn't decide the appeal; an admin may (flagged in the audit log when it was theirs).
const id = appeal.json.case.id;
expect((await call(mod, "GET", `/api/v1/cases/${id}`)).json.canDecide).toBe(false);
expect((await call(mod, "POST", `/api/v1/cases/${id}/decide`, { decision: "decline", resolution: "" })).json.message).toContain("Another moderator");
expect((await call(admin, "POST", `/api/v1/cases/${id}/decide`, { decision: "resolve", resolution: "Restoring it" })).json.case.status).toBe("resolved");
// Upholding it records the decision; the moderator restores the product (only moderators can).
expect((await call(maker, "POST", `/api/v1/products/${coat}/unremove`, {})).status).toBe(403);
expect((await call(admin, "POST", `/api/v1/products/${coat}/unremove`, { reason: "Appeal upheld" })).status).toBe(200);
expect((await call(undefined, "GET", `/api/v1/products/${coat}`)).status).toBe(200);
expect((await call(admin, "POST", `/api/v1/products/${coat}/unremove`, {})).status).toBe(404);
expect((await notes(maker)).notifications[0]).toMatchObject({ type: "product_restored", data: { reason: "Appeal upheld" } });
});
test("membership decisions and moderators' edits reach people as notifications", async () => {
const owner = await person("gatekeeper");
const joiner = await person("joiner");
const c = await catalogOf(owner, admin, "Gated Shelf", "approval");
expect((await call(joiner, "POST", `/api/v1/catalogs/${c.id}/join`, {})).json.membership).toBe("requested");
expect((await call(owner, "PUT", `/api/v1/catalogs/${c.id}/members/joiner`, { status: "member" })).status).toBe(200);
expect((await notes(joiner)).notifications[0]).toMatchObject({ type: "membership_decided", data: { catalog: c.id, status: "member" } });
const maker = await person("edited");
const p = await upload(maker, c, "Wrong Name", 6);
expect((await call(mod, "PATCH", `/api/v1/products/${p}`, { name: "Right Name", reason: "Typo" })).status).toBe(200);
expect((await notes(maker)).notifications[0]).toMatchObject({
type: "product_edited",
data: { product: p, name: "Right Name", fields: ["name"], reason: "Typo", by: "warden" },
});
// Their own edits don't notify them.
const before = (await notes(maker)).notifications.length;
await call(maker, "PATCH", `/api/v1/products/${p}`, { tags: ["mine"] });
expect((await notes(maker)).notifications.length).toBe(before);
});
+341
View File
@@ -0,0 +1,341 @@
// Managing catalogs (docs/products.md) with permissions (docs/console.md): settings, keys, teams, membership and
// what it gates, invites, delisting, suspension, the changes feed, and the console's scoped audit log.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const fakeIMVU: typeof fetch = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname.startsWith("/product/")) return Response.json({ status: "failure" }, { status: 404 });
const u = [...accounts.values()].find(
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
);
return Response.json({
denormalized: u
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
: {},
});
}) as typeof fetch;
// Catalog addresses that answer /health (for address changes).
const healthy = new Set<string>(["https://moved.example.test"]);
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({
db,
auth,
imvu: new ImvuClient("http://imvu.test", fakeIMVU),
apiURL,
webURL,
catalogHealthy: async (url) => healthy.has(url),
});
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Person = { cookie: string; name: string };
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const res = await fetch(base + path, {
method,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(p ? { Cookie: p.cookie } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json: any;
try {
json = JSON.parse(text);
} catch {
json = text;
}
return { status: res.status, json };
}
async function person(name: string): Promise<Person> {
const res = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
const file = (name: string, n: number) => ({ name, sha256: n.toString(16).padStart(64, "0"), size: 100 * n });
/** A person's catalog, registered and approved; its key's Authorization header. */
async function catalogOf(owner: Person, admin: Person, name: string, membership = "open") {
const reg = await call(owner, "POST", "/api/v1/catalogs", {
name,
url: `https://${name.toLowerCase().replace(/\W/g, "")}.example.test`,
contact: "[email protected]",
visibility: "public",
membership,
});
expect(reg.status).toBe(201);
const id = reg.json.catalog.id as string;
expect((await call(admin, "POST", `/api/v1/console/catalogs/${id}/approve`)).status).toBe(200);
return { id, auth: { Authorization: `Catalog ${id}:${reg.json.key}` } };
}
/** A product uploaded by a person to a catalog; its ID. */
async function upload(maker: Person, c: { id: string; auth: Record<string, string> }, name: string, n: number, rating = "general") {
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
expect(tok.status).toBe(200);
const r = await call(
undefined,
"POST",
"/api/v1/catalog/revisions",
{ uploadToken: tok.json.token, files: [file("index.xml", n)], rating, parent: 0, name, notes: "" },
c.auth,
);
expect(r.status).toBe(201);
expect((await call(maker, "POST", `/api/v1/products/${r.json.product}/publish`)).status).toBe(200);
return r.json.product as string;
}
let admin: Person;
test("the first account is the admin", async () => {
admin = await person("admin1");
expect((await call(admin, "GET", "/api/v1/me")).json.person.role).toBe("admin");
});
test("a catalog's owner changes its settings and key; others can't, and are told which permission they lack", async () => {
const owner = await person("owner1");
const stranger = await person("stranger1");
const c = await catalogOf(owner, admin, "Owner Shelf");
// Anyone can see an approved catalog; the owner sees their permissions there.
const seen = await call(owner, "GET", `/api/v1/catalogs/${c.id}`);
expect(seen.status).toBe(200);
expect(seen.json.roles).toContain("catalog-owner");
expect(seen.json.permissions).toContain("catalog:edit");
expect((await call(stranger, "GET", `/api/v1/catalogs/${c.id}`)).json.permissions).toEqual([]);
// A stranger is refused, naming what's missing.
const refused = await call(stranger, "PATCH", `/api/v1/catalogs/${c.id}`, { name: "Mine now" });
expect(refused.status).toBe(403);
expect(refused.json).toMatchObject({ error: "forbidden", missing: { permission: "catalog:edit", scope: { catalog: c.id } } });
// The owner changes settings; an address must answer /health.
const edited = await call(owner, "PATCH", `/api/v1/catalogs/${c.id}`, { name: "Owner's Shelf", maxRating: "general", uploads: "members" });
expect(edited.status).toBe(200);
expect(edited.json.catalog).toMatchObject({ name: "Owner's Shelf", maxRating: "general", uploads: "members" });
expect((await call(owner, "PATCH", `/api/v1/catalogs/${c.id}`, { url: "https://nowhere.example.test" })).json.error).toBe("unreachable");
expect((await call(owner, "PATCH", `/api/v1/catalogs/${c.id}`, { url: "https://moved.example.test/" })).json.catalog.url).toBe(
"https://moved.example.test",
);
// A new key: the old one stops working at once.
const rotated = await call(owner, "POST", `/api/v1/catalogs/${c.id}/key`);
expect(rotated.status).toBe(200);
expect((await call(undefined, "GET", "/api/v1/catalog/changes", undefined, c.auth)).status).toBe(401);
expect(
(await call(undefined, "GET", "/api/v1/catalog/changes", undefined, { Authorization: `Catalog ${c.id}:${rotated.json.key}` })).status,
).toBe(200);
});
test("teams: the owner gives the operator role; operators manage members but not the team", async () => {
const owner = await person("owner2");
const op = await person("op2");
const other = await person("other2");
const c = await catalogOf(owner, admin, "Team Shelf", "approval");
expect((await call(op, "PUT", `/api/v1/catalogs/${c.id}/team/other2`, { role: "catalog-operator" })).status).toBe(403);
const added = await call(owner, "PUT", `/api/v1/catalogs/${c.id}/team/op2`, { role: "catalog-operator" });
expect(added.status).toBe(200);
expect(added.json.team.roles).toMatchObject([{ username: "op2", role: "catalog-operator" }]);
// The operator holds member:approve, not team:manage.
const perms = (await call(op, "GET", `/api/v1/console/permissions?catalog=${c.id}`)).json;
expect(perms.roles).toEqual(["catalog-operator"]);
expect(perms.permissions).toContain("member:approve");
expect(perms.permissions).not.toContain("team:manage");
expect((await call(op, "PUT", `/api/v1/catalogs/${c.id}/team/other2`, { role: "catalog-operator" })).json.missing.permission).toBe(
"team:manage",
);
// An approval catalog: other asks, the operator approves.
expect((await call(other, "POST", `/api/v1/catalogs/${c.id}/join`, {})).json.membership).toBe("requested");
const requests = await call(op, "GET", `/api/v1/catalogs/${c.id}/members?status=requested`);
expect(requests.json.members).toMatchObject([{ username: "other2", status: "requested" }]);
expect((await call(op, "PUT", `/api/v1/catalogs/${c.id}/members/other2`, { status: "member" })).status).toBe(200);
expect((await call(other, "GET", `/api/v1/catalogs/${c.id}`)).json.membership).toBe("member");
// Operators leave on their own; the console lists the catalog for them while they're on the team.
expect((await call(op, "GET", "/api/v1/console/catalogs")).json.catalogs.map((x: any) => x.id)).toEqual([c.id]);
expect((await call(op, "DELETE", `/api/v1/catalogs/${c.id}/team/op2?role=catalog-operator`)).status).toBe(200);
expect((await call(op, "GET", "/api/v1/console/catalogs")).status).toBe(403);
});
test("membership gates getting and wearing products; seeing them doesn't need it", async () => {
const owner = await person("owner3");
const maker = await person("maker3");
const fan = await person("fan3");
const c = await catalogOf(owner, admin, "Invite Shelf", "invite");
// Uploads to an invite catalog: anyone may upload by default.
const pid = await upload(maker, c, "Hat", 31);
// Seeing works; getting doesn't, and says which catalogs host it.
const page = await call(fan, "GET", `/api/v1/products/${pid}`);
expect(page.json).toMatchObject({ available: false, catalogs: [{ id: c.id, membership: "invite", joined: null }] });
expect((await call(fan, "GET", `/api/v1/products/${pid}/files`)).status).toBe(200);
const refused = await call(fan, "PUT", `/api/v1/library/${pid}`);
expect(refused.status).toBe(403);
expect(refused.json).toMatchObject({ error: "members_only", catalogs: [{ id: c.id }] });
// Invite only: joining without an invite is refused; with one, they're in.
expect((await call(fan, "POST", `/api/v1/catalogs/${c.id}/join`, {})).json.error).toBe("invite_only");
const inv = await call(owner, "POST", `/api/v1/catalogs/${c.id}/invites`, { maxUses: 1 });
expect(inv.status).toBe(201);
expect(inv.json.invite.url).toBe(`${webURL}/catalogs/${c.id}?invite=${inv.json.invite.code}`);
expect((await call(fan, "POST", `/api/v1/catalogs/${c.id}/join`, { invite: inv.json.invite.code })).json.membership).toBe("member");
const late = await person("late3");
expect((await call(late, "POST", `/api/v1/catalogs/${c.id}/join`, { invite: inv.json.invite.code })).json.error).toBe("invite_invalid");
expect((await call(fan, "PUT", `/api/v1/library/${pid}`)).status).toBe(200);
expect((await call(fan, "GET", "/api/v1/library")).json.library.map((l: any) => l.product.id)).toEqual([pid]);
// Banned: the product stays in the table but isn't listed (or wearable) until they're back.
expect((await call(owner, "PUT", `/api/v1/catalogs/${c.id}/members/fan3`, { status: "banned" })).status).toBe(200);
expect((await call(fan, "GET", "/api/v1/library")).json.library).toEqual([]);
expect((await call(fan, "POST", `/api/v1/catalogs/${c.id}/join`, {})).json.error).toBe("banned");
expect((await call(owner, "DELETE", `/api/v1/catalogs/${c.id}/members/fan3`)).status).toBe(204);
expect((await call(owner, "PUT", `/api/v1/catalogs/${c.id}/members/fan3`, { status: "member" })).status).toBe(200);
expect((await call(fan, "GET", "/api/v1/library")).json.library.map((l: any) => l.product.id)).toEqual([pid]);
// Its creator always has their own product.
expect((await call(maker, "PUT", `/api/v1/library/${pid}`)).status).toBe(200);
});
test("a catalog's upload policy and rating ceiling apply to uploads", async () => {
const owner = await person("owner4");
const maker = await person("maker4");
const c = await catalogOf(owner, admin, "Strict Shelf");
expect((await call(owner, "PATCH", `/api/v1/catalogs/${c.id}`, { uploads: "members", maxRating: "general" })).status).toBe(200);
const refused = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
expect(refused).toMatchObject({ status: 403, json: { error: "forbidden" } });
expect((await call(maker, "POST", `/api/v1/catalogs/${c.id}/join`, {})).json.membership).toBe("member");
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
expect(tok.status).toBe(200);
const adult = await call(
undefined,
"POST",
"/api/v1/catalog/revisions",
{ uploadToken: tok.json.token, files: [file("index.xml", 41)], rating: "adult", parent: 0, name: "Spicy", notes: "" },
c.auth,
);
expect(adult).toMatchObject({ status: 400, json: { error: "rating_ceiling" } });
// Team only: members can't either.
expect((await call(owner, "PATCH", `/api/v1/catalogs/${c.id}`, { uploads: "team" })).status).toBe(200);
expect((await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id })).status).toBe(403);
expect((await call(owner, "POST", "/api/v1/products/upload", { catalog: c.id })).status).toBe(200);
});
test("delisting and suspension reach the catalog through its changes feed", async () => {
const owner = await person("owner5");
const maker = await person("maker5");
const c = await catalogOf(owner, admin, "Feed Shelf");
const pid = await upload(maker, c, "Scarf", 51);
expect((await call(owner, "GET", `/api/v1/catalogs/${c.id}/products`)).json.products).toMatchObject([{ id: pid, revisions: [1] }]);
expect((await call(maker, "DELETE", `/api/v1/catalogs/${c.id}/products/${pid}?reason=no`)).status).toBe(403);
const delisted = await call(owner, "DELETE", `/api/v1/catalogs/${c.id}/products/${pid}?reason=${encodeURIComponent("off-topic")}`);
expect(delisted.json.revisions).toEqual([1]);
expect((await call(owner, "GET", `/api/v1/catalogs/${c.id}/products`)).json.products).toEqual([]);
const feed = await call(undefined, "GET", "/api/v1/catalog/changes", undefined, c.auth);
expect(feed.json.changes).toEqual([{ type: "delete", product: pid, revision: 1, files: [file("index.xml", 51)] }]);
const cursor = feed.json.cursor;
expect((await call(undefined, "GET", `/api/v1/catalog/changes?after=${cursor}`, undefined, c.auth)).json.changes).toEqual([]);
// Owners can't suspend their own catalog; moderators can. A suspended catalog can't register revisions, still
// reads its feed, and is told.
expect((await call(owner, "POST", `/api/v1/catalogs/${c.id}/suspend`, { reason: "x" })).status).toBe(403);
expect((await call(admin, "POST", `/api/v1/catalogs/${c.id}/suspend`, { reason: "spam" })).json.catalog).toMatchObject({
status: "suspended",
statusReason: "spam",
});
expect((await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id })).status).toBe(404);
const told = await call(undefined, "GET", `/api/v1/catalog/changes?after=${cursor}`, undefined, c.auth);
expect(told.json.changes).toEqual([{ type: "status", status: "suspended" }]);
expect((await call(admin, "POST", `/api/v1/catalogs/${c.id}/reinstate`)).json.catalog.status).toBe("approved");
});
test("the console is for everyone who controls something; its audit log shows only what they may see", async () => {
const owner = await person("owner6");
const maker = await person("maker6");
const nobody = await person("nobody6");
const c = await catalogOf(owner, admin, "Audit Shelf");
const other = await catalogOf(await person("owner6b"), admin, "Other Shelf");
const pid = await upload(maker, c, "Gloves", 61);
expect((await call(owner, "PATCH", `/api/v1/catalogs/${c.id}`, { contact: "[email protected]" })).status).toBe(200);
expect((await call(maker, "PATCH", `/api/v1/products/${pid}`, { name: "Warm Gloves" })).status).toBe(200);
expect((await call(admin, "PATCH", `/api/v1/catalogs/${other.id}`, { name: "Other Shelf 2" })).status).toBe(200);
// Sections by what they control.
expect((await call(nobody, "GET", "/api/v1/console")).status).toBe(403);
expect((await call(nobody, "GET", "/api/v1/console/audit")).status).toBe(403);
const ownerConsole = (await call(owner, "GET", "/api/v1/console")).json;
expect(ownerConsole.sections).toEqual(["overview", "catalogs", "cases", "audit"]);
expect(ownerConsole.moderation).toBeNull();
expect((await call(maker, "GET", "/api/v1/console")).json.sections).toEqual(["overview", "products", "cases", "audit"]);
expect((await call(admin, "GET", "/api/v1/console")).json.sections).toEqual(["overview", "products", "catalogs", "cases", "people", "imports", "blocks", "audit", "settings"]);
// The owner sees their catalog's entries, not the other catalog's; the maker sees their product's.
const ownerLog = (await call(owner, "GET", "/api/v1/console/audit")).json.entries;
expect(ownerLog.some((e: any) => e.action === "catalog.edit" && e.tags.catalog === c.id)).toBe(true);
expect(ownerLog.some((e: any) => e.tags.catalog === other.id)).toBe(false);
expect(ownerLog.find((e: any) => e.tags.catalog === c.id).tagNames[c.id]).toBe("Audit Shelf");
const makerLog = (await call(maker, "GET", "/api/v1/console/audit")).json.entries;
expect(makerLog.map((e: any) => e.action)).toContain("product.edit");
expect(makerLog.some((e: any) => e.tags.catalog === c.id && e.action === "catalog.edit")).toBe(false);
// Admins see everything, and filter.
const filtered = (await call(admin, "GET", `/api/v1/console/audit?catalog=${other.id}&action=catalog.edit`)).json.entries;
expect(filtered).toHaveLength(1);
expect(filtered[0]).toMatchObject({ actor: "admin1", action: "catalog.edit" });
expect((await call(admin, "GET", "/api/v1/console/audit?actor=maker6")).json.entries.every((e: any) => e.actor === "maker6")).toBe(true);
expect((await call(admin, "GET", "/api/v1/console/audit?q=legal@example")).json.entries).toHaveLength(1);
});
test("outfits relay only the hub products the wearer may wear; local packs pass", async () => {
const { Realtime } = await import("../src/realtime");
const rt = new Realtime({
owner: async () => "u1",
wearable: async (_, ids) => new Set(ids.filter((id) => id === "aaaaaaaaaa")),
});
rt.open("s1", "u1", () => {});
await rt.message("s1", { type: "session", imvu_id: 7 });
await rt.message("s1", {
type: "outfit",
items: [
{ id: "aaaaaaaaaa", name: "Mine", adult: false },
{ id: "bbbbbbbbbb", name: "Members only", adult: false },
{ id: "local-pack-1", name: "A pack", adult: false },
],
});
expect(rt.online()[0]!.outfit.map((i) => i.id)).toEqual(["aaaaaaaaaa", "local-pack-1"]);
});
+205
View File
@@ -0,0 +1,205 @@
// Discord sign-in (docs/music.md, Accounts): it makes a basic account (Discord only, none of the hub's features), from a
// verified email only, and never links by matching email; a basic account finishes setting up with a username and
// password; a member links Discord from their own session. Discord itself is stood in for below.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient } from "../src/imvu";
import { Settings } from "../src/settings";
const webURL = "http://web.test";
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
let settings: Settings;
/** The Discord account the next sign-in comes back as. */
let discordProfile: Record<string, unknown> = {};
const realFetch = globalThis.fetch;
beforeAll(async () => {
// Discord's token and profile endpoints, as Better Auth's Discord provider calls them.
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
if (url.startsWith("https://discord.com/api/oauth2/token"))
return Response.json({ access_token: "discord-at", token_type: "Bearer", expires_in: 3600, refresh_token: "discord-rt", scope: "identify email" });
if (/^https:\/\/discord\.com\/api\/users\/(@|%40)me/.test(url)) return Response.json(discordProfile);
return realFetch(input, init);
}) as typeof fetch;
({ db, close } = await openDatabase("memory"));
settings = new Settings(db, { registration: "open" });
const auth = createAuth(db, {
apiURL: "http://api.test",
webURL,
secret: "test-secret-test-secret-test-secret-1234",
rateLimit: false,
settings,
discord: { clientId: "discord-client", clientSecret: "discord-secret" },
});
const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch);
const hub = createApp({ db, auth, imvu, webURL, settings });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
globalThis.fetch = realFetch;
stop();
await close();
});
type Cookie = { v: string };
/** Keeps the cookies a response sets (Better Auth's state, then the session). */
function keep(cookie: Cookie, res: Response) {
const jar = new Map(cookie.v ? cookie.v.split("; ").map((c) => c.split("=", 2) as [string, string]) : []);
for (const c of res.headers.getSetCookie()) {
const [pair] = c.split(";");
const [k, v] = pair!.split("=", 2) as [string, string];
if (/max-age=0/i.test(c) || v === "") jar.delete(k);
else jar.set(k, v);
}
cookie.v = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
}
async function call(cookie: Cookie, method: string, path: string, body?: unknown) {
const res = await realFetch(base + path, {
method,
redirect: "manual",
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(cookie.v ? { Cookie: cookie.v } : {}) },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
keep(cookie, res);
const text = await res.text();
let json: any;
try {
json = text ? JSON.parse(text) : undefined;
} catch {
json = undefined;
}
return { status: res.status, json, location: res.headers.get("location") ?? "" };
}
/** Goes through Discord's sign-in (or linking, from a signed-in session) and returns where the browser ends up. */
async function viaDiscord(cookie: Cookie, profile: Record<string, unknown>, link = false) {
discordProfile = { discriminator: "0", avatar: null, global_name: profile.username, ...profile };
const start = link
? await call(cookie, "POST", "/api/auth/link-social", { provider: "discord", callbackURL: `${webURL}/account`, errorCallbackURL: `${webURL}/account` })
: await call(cookie, "POST", "/api/auth/sign-in/social", { provider: "discord", callbackURL: `${webURL}/`, errorCallbackURL: `${webURL}/signin` });
expect(start.status).toBe(200);
const state = new URL(start.json.url).searchParams.get("state");
expect(state).toBeTruthy();
const back = await call(cookie, "GET", `/api/auth/callback/discord?code=discord-code&state=${encodeURIComponent(state!)}`);
expect(back.status).toBe(302);
return new URL(back.location, webURL);
}
async function signUp(name: string, email = `${name}@example.test`) {
const cookie = { v: "" };
expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email, password: "a long password", name, username: name })).status).toBe(200);
return cookie;
}
test("a basic account from Discord can't use the hub until it finishes setting up; the first member still runs the hub", async () => {
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "open", discord: true });
const disco: Cookie = { v: "" };
const landed = await viaDiscord(disco, { id: "1001", username: "disco", email: "[email protected]", verified: true });
expect(landed.pathname).toBe("/");
expect(landed.searchParams.get("error")).toBeNull();
const me = (await call(disco, "GET", "/api/v1/me")).json.person;
expect(me).toMatchObject({ kind: "basic", role: "user", username: "disco", email: "[email protected]" });
expect(await call(disco, "GET", "/api/v1/account")).toMatchObject({ status: 403, json: { error: "finish_setup" } });
expect((await call(disco, "POST", "/api/v1/account/links", { username: "someone" })).json.error).toBe("finish_setup");
// Basic accounts don't count: the first member is still the admin.
const ada = await signUp("ada");
expect((await call(ada, "GET", "/api/v1/me")).json.person).toMatchObject({ kind: "member", role: "admin" });
// Signing in with the same Discord account again is the same person.
const again: Cookie = { v: "" };
await viaDiscord(again, { id: "1001", username: "disco", email: "[email protected]", verified: true });
expect((await call(again, "GET", "/api/v1/me")).json.person.id).toBe(me.id);
});
test("Discord sign-in needs a verified email, and never links to an account by its email", async () => {
const unverified = await viaDiscord({ v: "" }, { id: "1002", username: "nover", email: "[email protected]", verified: false });
expect(unverified.pathname).toBe("/signin");
expect(unverified.searchParams.get("error")).toBe("email_not_verified");
const noEmail = await viaDiscord({ v: "" }, { id: "1003", username: "phone", email: null, verified: false });
expect(noEmail.searchParams.get("error")).toBe("email_not_found");
// bea is a member; someone puts her address on their Discord account.
await signUp("bea");
const thief: Cookie = { v: "" };
const taken = await viaDiscord(thief, { id: "1004", username: "thief", email: "[email protected]", verified: true });
expect(taken.pathname).toBe("/signin");
expect(taken.searchParams.get("error")).toBe("account_not_linked");
expect((await call(thief, "GET", "/api/v1/me")).status).toBe(401);
});
test("finishing setup: a username and password make a member, still signing in with Discord too", async () => {
const cass: Cookie = { v: "" };
await viaDiscord(cass, { id: "1005", username: "cass", email: "[email protected]", verified: true });
const id = (await call(cass, "GET", "/api/v1/me")).json.person.id;
const finish = (username: string, password = "a long password") => call(cass, "POST", "/api/v1/account/finish", { username, password });
expect((await finish("no spaces")).json.error).toBe("invalid_username");
expect((await finish("imvu_123")).json.error).toBe("invalid_username");
expect((await finish("Ada")).json.error).toBe("username_taken");
expect((await finish("cass_", "short")).json.error).toBe("invalid_password");
const done = await finish("Cass_");
expect(done.status).toBe(200);
expect(done.json.person).toMatchObject({ id, kind: "member", username: "Cass_", approved: true });
expect((await call(cass, "GET", "/api/v1/account")).json).toMatchObject({ discord: { available: true, linked: true } });
expect((await finish("again")).json.error).toBe("already_member");
// The password works, and so does Discord.
const byPassword: Cookie = { v: "" };
expect((await call(byPassword, "POST", "/api/auth/sign-in/username", { username: "cass_", password: "a long password" })).status).toBe(200);
expect((await call(byPassword, "GET", "/api/v1/me")).json.person.id).toBe(id);
const byDiscord: Cookie = { v: "" };
await viaDiscord(byDiscord, { id: "1005", username: "cass", email: "[email protected]", verified: true });
expect((await call(byDiscord, "GET", "/api/v1/me")).json.person).toMatchObject({ id, kind: "member" });
});
test("with registration closed, a finished account waits for approval", async () => {
await settings.setRegistration("closed");
try {
const dee: Cookie = { v: "" };
await viaDiscord(dee, { id: "1006", username: "dee", email: "[email protected]", verified: true });
expect((await call(dee, "POST", "/api/v1/account/finish", { username: "dee", password: "a long password" })).json.person).toMatchObject({
kind: "member",
approved: false,
});
expect((await call(dee, "GET", "/api/v1/account")).json.error).toBe("awaiting_approval");
} finally {
await settings.setRegistration("open");
}
});
test("a member links Discord from their own session; a Discord account already in use can't be linked again", async () => {
const eve = await signUp("eve");
expect((await call(eve, "GET", "/api/v1/account")).json.discord).toEqual({ available: true, linked: false });
// Another address than eve's own: allowed, it's her session that links it.
const linked = await viaDiscord(eve, { id: "1007", username: "eve_discord", email: "[email protected]", verified: true }, true);
expect(linked.pathname).toBe("/account");
expect(linked.searchParams.get("error")).toBeNull();
expect((await call(eve, "GET", "/api/v1/account")).json.discord).toEqual({ available: true, linked: true });
// And unlinks it again (she keeps her password).
expect((await call(eve, "DELETE", "/api/v1/account/discord")).status).toBe(204);
expect((await call(eve, "GET", "/api/v1/account")).json.discord.linked).toBe(false);
expect((await call(eve, "DELETE", "/api/v1/account/discord")).status).toBe(404);
// disco's Discord account (a basic account) can't be added to fay's: merging comes later.
const fay = await signUp("fay");
const refused = await viaDiscord(fay, { id: "1001", username: "disco", email: "[email protected]", verified: true }, true);
expect(refused.searchParams.get("error")).toBe("account_already_linked_to_different_user");
expect((await call(fay, "GET", "/api/v1/account")).json.discord.linked).toBe(false);
});
+4 -2
View File
@@ -4,6 +4,7 @@ import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth, proxyClientID } from "../src/auth";
import { ImvuClient, type ImvuUser } from "../src/imvu";
import { twoFactorOn } from "./two-factor";
const webURL = "http://web.test";
const accounts = new Map<number, ImvuUser>();
@@ -229,8 +230,8 @@ describe("T5DE's proxy", () => {
const admin = new Browser();
await admin.call("POST", "/api/auth/sign-in/username", { username: "alice", password: "a long password" });
const consoleView = (await admin.call("GET", "/api/v1/console")).json;
expect(consoleView.online[0]).toMatchObject({ username: "ErinAv", hidden: true });
expect(consoleView.counts.computers).toBe(1);
expect(consoleView.moderation.online[0]).toMatchObject({ username: "ErinAv", hidden: true });
expect(consoleView.moderation.counts.computers).toBe(1);
await erin.call("PATCH", "/api/v1/account/links/77", { showPresence: true, showBadge: true });
const online = (await visitor.call("GET", "/api/v1/online")).json.online;
expect(online).toEqual([
@@ -239,6 +240,7 @@ describe("T5DE's proxy", () => {
// A ban closes the connection and ends the proxy's session.
const erinId = (await erin.call("GET", "/api/v1/me")).json.person.id;
await twoFactorOn(db, "alice");
const closed = new Promise((r) => (ws.onclose = r));
expect((await admin.call("POST", `/api/v1/console/people/${erinId}/ban`, { reason: "testing" })).status).toBe(200);
await closed;
+586
View File
@@ -0,0 +1,586 @@
// Imports (docs/imports.md): a creator grants a catalog leave to import their IMVU products; the catalog's team
// accepts; requests queue jobs; the importer claims them, gets a token, uploads, and the catalog registers the
// revision; narrowing or withdrawing a grant withdraws products.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient, type ImvuUser } from "../src/imvu";
import type { Imports } from "../src/imports";
import { twoFactorOn } from "./two-factor";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const imvuProducts = new Map<number, Record<string, unknown>>();
const hiddenProducts = new Set<number>(); // answered 401, as IMVU does for Access Pass products
const shops = new Map<string, number[]>(); // IMVU username (lowercase) → the products IMVU lists for it
const fakeIMVU = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname === "/product" && url.searchParams.has("creator")) {
// Pages of 2 that overlap by one, as IMVU's small pages do: the client follows `next` and drops repeats.
const creator = url.searchParams.get("creator")!;
const ids = shops.get(creator.toLowerCase()) ?? [];
const offset = Number(url.searchParams.get("offset") ?? 0);
const page = ids.slice(offset, offset + 2);
const self = `http://imvu.test/product?creator=${creator}&offset=${offset}`;
const next = offset + 2 < ids.length ? { next: `http://imvu.test/product?creator=${creator}&offset=${offset + 1}` } : [];
const den: Record<string, unknown> = {
[self]: { data: { items: page.map((id) => `https://api.imvu.com/product/product-${id}`), total_count: ids.length }, relations: next },
};
for (const id of page) den[`https://api.imvu.com/product/product-${id}`] = { data: { product_id: id, ...imvuProducts.get(id) } };
return Response.json({ status: "success", id: self, denormalized: den });
}
const pm = url.pathname.match(/^\/product\/product-(\d+)$/);
if (pm) {
const p = imvuProducts.get(Number(pm[1]));
if (hiddenProducts.has(Number(pm[1]))) return Response.json({ status: "failure", error: "AUTHENTICATION-005" }, { status: 401 });
if (!p) return Response.json({ status: "failure" }, { status: 404 });
return Response.json({ denormalized: { [`https://api.imvu.com/product/product-${pm[1]}`]: { data: p } } });
}
const u = [...accounts.values()].find(
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
);
return Response.json({
denormalized: u
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
: {},
});
}) as unknown as typeof fetch;
let imports: Imports;
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({ db, auth, imvu: new ImvuClient("http://imvu.test", fakeIMVU), apiURL, webURL, catalogHealthy: async () => true });
imports = hub.imports;
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Person = { cookie: string; name: string };
let rootAdmin: Person; // the first person: an admin
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const res = await fetch(base + path, {
method,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(p ? { Cookie: p.cookie } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json: any;
try {
json = JSON.parse(text);
} catch {
json = text;
}
return { status: res.status, json };
}
/** A person (with two-factor sign-in on), optionally with a linked IMVU account. */
async function person(name: string, imvu?: number): Promise<Person> {
const res = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
const p = { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
if (imvu) {
accounts.set(imvu, { id: imvu, username: `${name}Av`, tagline: "", ageVerified: false, accessPass: false, picture: null });
const started = await call(p, "POST", "/api/v1/account/links", { username: `${name}Av` });
accounts.get(imvu)!.tagline = started.json.challenge.code;
expect((await call(p, "POST", `/api/v1/account/links/${imvu}/check`)).status).toBe(200);
}
return p;
}
const file = (name: string, n: number) => ({ name, sha256: n.toString(16).padStart(64, "0"), size: 100 * n });
const imvuProduct = (name: string, creator: number, rating = "GA") => ({ product_name: name, creator_cid: creator, creator_name: "x", rating, is_purchasable: true });
test("grants, requests, the importer's jobs, and withdrawal", async () => {
const admin = await person("root");
rootAdmin = admin;
const owner = await person("shelf");
const maker = await person("maker", 501);
const fan = await person("fan");
imvuProducts.set(9001, imvuProduct("Silk Dress", 501));
imvuProducts.set(9002, imvuProduct("Silk Hat", 501));
imvuProducts.set(9003, imvuProduct("Silk Shoes", 501));
imvuProducts.set(9100, imvuProduct("Someone Else's", 777));
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Imports Shelf", url: "https://imports.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(admin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
// Imports on: an importer key, and the catalog takes grants.
expect((await call(undefined, "GET", "/api/v1/imports/catalogs")).json.catalogs).toEqual([]);
expect((await call(fan, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true })).status).toBe(403);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
expect(on.json.catalog.importer).toBe("on");
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const listed = (await call(undefined, "GET", "/api/v1/imports/catalogs")).json;
expect(listed.catalogs.map((c: any) => c.id)).toEqual([catalogID]);
const version = listed.consent.version;
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, { Authorization: `Importer ${catalogID}:wrong` })).status).toBe(401);
// Before any grant, requests are counted.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9001 })).json).toEqual({ status: "counted" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuCreator: 501 })).json).toEqual({ status: "counted" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 4242 })).status).toBe(404);
// A grant: only for one's own linked account, with the current consent.
const grantBody = { catalog: catalogID, imvuId: 501, scope: "shop", exclude: [9003], consentVersion: version };
expect((await call(fan, "POST", "/api/v1/imports/grants", grantBody)).json.error).toBe("not_linked");
expect((await call(maker, "POST", "/api/v1/imports/grants", { ...grantBody, consentVersion: version + 1 })).json.error).toBe("consent_changed");
const made = await call(maker, "POST", "/api/v1/imports/grants", grantBody);
expect(made.status).toBe(201);
expect(made.json.grant).toMatchObject({ status: "pending", scope: "shop", exclude: [9003], consentKind: "verified" });
const grantID = made.json.grant.id as string;
expect((await call(maker, "POST", "/api/v1/imports/grants", grantBody)).json.error).toBe("exists");
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs).toEqual([]);
// The catalog's team accepts: what people asked for is queued; the creator hears.
expect((await call(maker, "POST", `/api/v1/imports/grants/${grantID}/accept`)).status).toBe(403);
const accepted = await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`);
expect(accepted.json).toMatchObject({ grant: { status: "active" }, queued: 1 });
await imports.listingsDone(); // the shop's listing (IMVU lists nothing for it here)
expect((await call(maker, "GET", "/api/v1/notifications")).json.notifications[0]).toMatchObject({ type: "import_grant_decided" });
// Paused: no jobs handed out.
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { paused: true })).json.catalog.importer).toBe("paused");
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs).toEqual([]);
await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { paused: false });
// The importer claims the job, gets a token for the revision it found, and uploads; the catalog registers it.
const claimed = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 5 }, importer)).json.jobs;
expect(claimed).toEqual([{ id: expect.any(String), kind: "import", imvuProduct: 9001, lastRevision: 0, rating: "general" }]);
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${claimed[0].id}/token`, { imvuRevision: 3 }, importer);
expect(tok.json.url).toBe("https://imports.example.test/api/v1/uploads");
const files = [file("index.xml", 11), file("dress.xmf", 12)];
const regd = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating: "general", parent: 1234, name: "ignored" }, catalogAuth);
expect(regd.status).toBe(201);
const productID = regd.json.product as string;
const page = (await call(fan, "GET", `/api/v1/products/${productID}`)).json;
expect(page.product).toMatchObject({ name: "Silk Dress", creatorUsername: "maker", status: "published", imvuProduct: 9001 });
// The fan who asked has it.
expect((await call(fan, "GET", "/api/v1/library")).json.library.map((l: any) => l.product.id)).toEqual([productID]);
// The same token again: the job is done.
expect((await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating: "general", parent: 1234, name: "x" }, catalogAuth)).status).toBe(409);
// Asking for an imported product adds it at once; a covered one is queued; excluded or others' are counted.
const other = await person("other");
expect((await call(other, "POST", "/api/v1/imports/requests", { imvuProduct: 9001 })).json).toEqual({ status: "added", product: productID });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9002 })).json).toEqual({ status: "queued" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9003 })).json).toEqual({ status: "counted" });
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9100 })).json).toEqual({ status: "counted" });
// A failure goes back to the queue with backoff, the reason shown to the team.
const second = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs;
expect(second.map((j: any) => j.imvuProduct)).toEqual([9002]);
const failed = await call(undefined, "POST", `/api/v1/importer/jobs/${second[0].id}`, { status: "failed", reason: "CDN said 503" }, importer);
expect(failed.json.job).toMatchObject({ status: "queued", attempts: 1, reason: "CDN said 503" });
expect((await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs).toEqual([]);
const view = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
expect(view).toMatchObject({ importer: "on", counts: { queued: 1, done: 1 }, permissions: { run: true, accept: true } });
expect(view.grants.map((g: any) => g.imvuName)).toEqual(["makerAv"]);
expect((await call(fan, "GET", `/api/v1/catalogs/${catalogID}/importer`)).status).toBe(403);
// The creator sees what people asked for.
const asked = (await call(maker, "GET", "/api/v1/imports/requests?imvuCreator=501")).json.requests;
expect(asked.map((r: any) => [r.imvuProduct, r.requests])).toEqual([[9001, 2], [0, 1], [9002, 1], [9003, 1]]);
expect((await call(fan, "GET", "/api/v1/imports/requests?imvuCreator=501")).status).toBe(403);
// Narrowing the grant withdraws what it no longer covers: gone, and the catalog deletes its files.
const narrowed = await call(maker, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [9001, 9003] });
expect(narrowed.json.withdrawn).toEqual([productID]);
expect((await call(fan, "GET", `/api/v1/products/${productID}`)).status).toBe(410);
const changes = (await call(undefined, "GET", "/api/v1/catalog/changes", undefined, catalogAuth)).json.changes;
expect(changes).toContainEqual({ type: "delete", product: productID, revision: 1, files: expect.any(Array) });
// Withdrawn: its open jobs fail; the catalog's audit has it all.
const gone = await call(maker, "DELETE", `/api/v1/imports/grants/${grantID}`);
expect(gone.json.grant.status).toBe("withdrawn");
expect((await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer?status=failed`)).json.jobs.map((j: any) => j.imvuProduct)).toEqual([9002]);
const actions = (await call(owner, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["catalog.importer", "import.grant", "import.grant_accept", "import.revision", "import.grant_withdraw"]));
// Unlinking the IMVU account suspends its grants.
const again = await call(maker, "POST", "/api/v1/imports/grants", { ...grantBody, scope: "products", products: [9002] });
expect(again.status).toBe(201);
expect((await call(maker, "DELETE", "/api/v1/account/links/501")).status).toBe(204);
expect((await call(maker, "GET", "/api/v1/imports/grants")).json.grants[0]).toMatchObject({ id: again.json.grant.id, status: "suspended" });
});
test("IMVU's 401 keeps what was last seen; 404 is gone", async () => {
imvuProducts.set(9500, imvuProduct("Turned AP", 501));
expect(await imports.info(9500, true)).toMatchObject({ found: true, creatorId: 501 });
hiddenProducts.add(9500);
expect(await imports.info(9500, true)).toMatchObject({ found: true, creatorId: 501, name: "Turned AP" });
hiddenProducts.add(9501); // never seen: nothing to keep
expect(await imports.info(9501, true)).toBeUndefined();
hiddenProducts.delete(9500);
imvuProducts.delete(9500);
expect(await imports.info(9500, true)).toBeUndefined();
});
test("the importer's key, IMVU accounts with sealed passwords, and settings", async () => {
const admin = rootAdmin;
const owner = await person("keeper");
const outsider = await person("outsider");
accounts.set(601, { id: 601, username: "ImportBot", tagline: "", ageVerified: true, accessPass: true, picture: null });
accounts.set(602, { id: 602, username: "SpareBot", tagline: "", ageVerified: false, accessPass: false, picture: null });
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Keeper Shelf", url: "https://keeper.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
expect((await call(admin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const page = async () => (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
// Before the importer has said hello there's no key to seal for.
expect((await page()).program).toMatchObject({ version: "", seenAt: null, fingerprint: null, publicKey: null });
const keys = async () => {
const pair = (await crypto.subtle.generateKey(
{ name: "RSA-OAEP", modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
true,
["encrypt", "decrypt"],
)) as CryptoKeyPair;
return { pair, spki: Buffer.from(await crypto.subtle.exportKey("spki", pair.publicKey)).toString("base64") };
};
// As the console's browser does: the account's ID and password, sealed for the importer's key.
const seal = async (spki: string, imvuId: number, password: string) => {
const key = await crypto.subtle.importKey("spki", Buffer.from(spki, "base64"), { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
const data = new TextEncoder().encode(JSON.stringify({ imvuId, password }));
return Buffer.from(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, key, data)).toString("base64");
};
const unseal = async (pair: CryptoKeyPair, sealed: string) =>
JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: "RSA-OAEP" }, pair.privateKey, Buffer.from(sealed, "base64"))));
const k1 = await keys();
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts`, { imvuId: 601, sealed: await seal(k1.spki, 601, "x"), fingerprint: "00" })).json.error).toBe("no_importer");
expect((await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.0", publicKey: "not a key" }, importer)).status).toBe(400);
const hello = await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.0", publicKey: k1.spki }, importer);
expect(hello.status).toBe(200);
expect(hello.json).toMatchObject({ paused: false, settings: { rate: 2, concurrency: 2 }, accounts: [] });
const shown = (await page()).program;
expect(shown).toMatchObject({ version: "0.1.0", publicKey: k1.spki });
expect(shown.fingerprint).toBe(hello.json.fingerprint);
expect(shown.seenAt).not.toBeNull();
// The console looks the account up, then adds it with the password sealed for that key.
expect((await call(outsider, "GET", `/api/v1/catalogs/${catalogID}/importer/imvu-account?username=ImportBot`)).status).toBe(403);
const found = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer/imvu-account?username=ImportBot`)).json;
expect(found).toMatchObject({ imvuId: 601, username: "ImportBot", accessPass: true, ageVerified: true });
const add = (imvuId: number, sealed: string, fingerprint = shown.fingerprint) =>
call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts`, { imvuId, sealed, fingerprint });
expect((await add(601, "bm90IHNlYWxlZA==")).json.error).toBe("invalid");
expect((await add(601, await seal(k1.spki, 601, "pw1"), "ff".repeat(32))).json.error).toBe("importer_key_changed");
const added = await add(601, await seal(k1.spki, 601, "pw1"));
expect(added.status).toBe(201);
expect(added.json.account).toMatchObject({ username: "ImportBot", state: "waiting", accessPass: true });
expect((await add(601, await seal(k1.spki, 601, "pw1"))).json.error).toBe("exists");
expect((await add(602, await seal(k1.spki, 602, "pw2"))).status).toBe(201);
// The importer gets the sealed passwords, in order, and can read them; the hub drops each once it has it.
const config = (await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json;
expect(config.accounts.map((a: any) => a.username)).toEqual(["ImportBot", "SpareBot"]);
expect(await unseal(k1.pair, config.accounts[0].sealed)).toEqual({ imvuId: 601, password: "pw1" });
const first = config.accounts[0].id as string;
expect((await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { received: true }, importer)).json.account.state).toBe("received");
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts[0].sealed).toBeNull();
await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { state: "ok", accessPass: true }, importer);
expect((await call(undefined, "POST", `/api/v1/importer/accounts/${first}`, { state: "ok" }, { Authorization: `Importer ${catalogID}:wrong` })).status).toBe(401);
// The order can change; settings are bounded.
await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/accounts/${first}/move`, { direction: "down" });
expect((await page()).accounts.map((a: any) => [a.username, a.state])).toEqual([["SpareBot", "waiting"], ["ImportBot", "ok"]]);
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/settings`, { rate: 50, concurrency: 2 })).status).toBe(400);
expect((await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer/settings`, { rate: 0.5, concurrency: 4 })).json.settings).toEqual({ rate: 0.5, concurrency: 4 });
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.settings).toEqual({ rate: 0.5, concurrency: 4 });
// A new install (a new key) can't read the old seals: every account needs its password again.
const k2 = await keys();
expect((await call(undefined, "POST", "/api/v1/importer/hello", { version: "0.1.1", publicKey: k2.spki }, importer)).json.accounts.every((a: any) => a.sealed === null)).toBe(true);
const after = await page();
expect(after.accounts.map((a: any) => a.state)).toEqual(["needs_password", "needs_password"]);
const spare = after.accounts[0].id as string;
const again = await call(owner, "PUT", `/api/v1/catalogs/${catalogID}/importer/accounts/${spare}/password`, { sealed: await seal(k2.spki, 602, "pw3"), fingerprint: after.program.fingerprint });
expect(again.json.account.state).toBe("waiting");
const sealed = (await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts[0].sealed;
expect(await unseal(k2.pair, sealed)).toEqual({ imvuId: 602, password: "pw3" });
// Removed accounts leave the importer's config; it's all audited.
expect((await call(owner, "DELETE", `/api/v1/catalogs/${catalogID}/importer/accounts/${spare}`)).status).toBe(204);
expect((await call(undefined, "GET", "/api/v1/importer/config", undefined, importer)).json.accounts.map((a: any) => a.username)).toEqual(["ImportBot"]);
const actions = (await call(owner, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["catalog.importer_hello", "catalog.importer_account", "catalog.importer_settings"]));
// Passwords never show on the console.
expect(JSON.stringify(await page())).not.toContain(sealed);
});
test("recorded grants, unclaimed creators, proof, and claiming", async () => {
const admin = rootAdmin;
const owner = await person("shelver");
const fan = await person("fanatic");
accounts.set(701, { id: 701, username: "QuietMaker", tagline: "", ageVerified: false, accessPass: false, picture: null });
imvuProducts.set(9201, imvuProduct("Quiet Coat", 701));
imvuProducts.set(9202, imvuProduct("Quiet Hat", 701));
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Recorded Shelf", url: "https://recorded.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(admin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
// Only those who may grant on behalf record; evidence is required; creators on T5DE grant themselves.
const body = { catalog: catalogID, imvu: "QuietMaker", scope: "shop", exclude: [9202], evidence: "Discord DM, 2026-11-07" };
expect((await call(owner, "POST", "/api/v1/console/imports/grants", body)).status).toBe(403);
expect((await call(owner, "GET", "/api/v1/console/imports")).status).toBe(403);
expect((await call(admin, "POST", "/api/v1/console/imports/grants", { ...body, evidence: " " })).json.error).toBe("invalid");
await person("onhub", 801); // a creator on T5DE, with their IMVU account linked
expect((await call(admin, "POST", "/api/v1/console/imports/grants", { ...body, imvu: "801" })).json.error).toBe("linked");
const recorded = await call(admin, "POST", "/api/v1/console/imports/grants", body);
expect(recorded.status).toBe(201);
expect(recorded.json.grant).toMatchObject({ status: "pending", consentKind: "recorded", consentProven: false, imvuName: "QuietMaker" });
const grantID = recorded.json.grant.id as string;
expect((await call(admin, "POST", "/api/v1/console/imports/grants", body)).json.error).toBe("exists");
// The console lists it; the catalog's team sees it named, and accepts as for any grant.
const consoleView = (await call(admin, "GET", "/api/v1/console/imports")).json;
expect(consoleView.grants).toEqual([expect.objectContaining({ id: grantID, evidence: "Discord DM, 2026-11-07", recordedBy: "root", claimed: false, proofCode: null })]);
expect((await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json.grants[0]).toMatchObject({ imvuName: "QuietMaker", consentKind: "recorded" });
expect((await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`)).json.grant.status).toBe("active");
// Proof without an account: a code in the creator's IMVU tagline.
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof/check`)).json.error).toBe("no_code");
const code = (await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof`)).json.code as string;
expect(code).toMatch(/^t5de-/);
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof`)).json.code).toBe(code);
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof/check`)).json.error).toBe("not_found");
accounts.get(701)!.tagline = `hi ${code}`;
expect((await call(admin, "POST", `/api/v1/console/imports/grants/${grantID}/proof/check`)).json.grant.consentProven).toBe(true);
// Imported products belong to the unclaimed creator.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9201 })).json).toEqual({ status: "queued" });
const [job] = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", {}, importer)).json.jobs;
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${job.id}/token`, { imvuRevision: 1 }, importer);
const regd = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files: [file("index.xml", 31)], rating: "general", parent: 0, name: "x" }, catalogAuth);
expect(regd.status).toBe(201);
const productID = regd.json.product as string;
expect((await call(fan, "GET", `/api/v1/products/${productID}`)).json.product).toMatchObject({ name: "Quiet Coat", creatorUsername: "imvu_701" });
// Admins change it for them; others can't.
expect((await call(fan, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [] })).status).toBe(403);
expect((await call(admin, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [] })).json.grant.exclude).toEqual([]);
// Nobody signs up as an unclaimed creator.
const squat = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: "[email protected]", password: "a long password", name: "squat", username: "imvu_702" }),
});
expect(squat.status).toBe(400);
// The creator joins and links the account: the grant stands, and they're offered the claim.
const quiet = await person("quiet", 701);
expect((await call(quiet, "GET", "/api/v1/imports/grants")).json.grants).toEqual([]);
expect((await call(admin, "GET", "/api/v1/console/imports")).json.grants[0]).toMatchObject({ status: "active", claimed: false });
expect((await call(quiet, "GET", "/api/v1/account")).json.claims).toEqual([{ imvuId: 701, username: "QuietMaker", products: 1, grants: 1 }]);
expect((await call(fan, "POST", "/api/v1/account/claims/701")).json.error).toBe("not_linked");
expect((await call(quiet, "POST", "/api/v1/account/claims/701")).json).toEqual({ products: 1, grants: 1 });
// Now it's theirs: their product and grant; the placeholder is gone; admins no longer change it.
expect((await call(fan, "GET", `/api/v1/products/${productID}`)).json.product.creatorUsername).toBe("quiet");
expect((await call(quiet, "GET", "/api/v1/imports/grants")).json.grants.map((g: any) => g.id)).toEqual([grantID]);
expect((await call(quiet, "GET", "/api/v1/account")).json.claims).toEqual([]);
expect((await call(admin, "GET", "/api/v1/console/imports")).json.grants[0].claimed).toBe(true);
expect((await call(admin, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [9202] })).status).toBe(403);
expect((await call(quiet, "PATCH", `/api/v1/imports/grants/${grantID}`, { exclude: [9202] })).status).toBe(200);
expect((await call(quiet, "POST", "/api/v1/account/claims/701")).status).toBe(404);
const actions = (await call(admin, "GET", "/api/v1/console/audit")).json.entries.map((e: any) => e.action);
expect(actions).toEqual(expect.arrayContaining(["import.grant_record", "import.grant_proof", "import.claim"]));
});
test("whole shops listed on IMVU, and what's available", async () => {
const owner = await person("stall");
const keeper = await person("shopkeep", 901);
const fan = await person("browser");
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "Shop Shelf", url: "https://shops.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(rootAdmin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const version = (await call(undefined, "GET", "/api/v1/imports/catalogs")).json.consent.version;
for (const [id, name] of [[9301, "Keeper Coat"], [9302, "Keeper Boots"], [9303, "Keeper Scarf"]] as const)
imvuProducts.set(id, { ...imvuProduct(name, 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9100]); // 9100 is another creator's: left out
// Nothing yet.
const none = await call(undefined, "GET", "/api/v1/imports/available?products=9301,9999&creators=901");
expect(none.json).toEqual({
products: [
{ imvuProduct: 9301, status: "none", product: null },
{ imvuProduct: 9999, status: "none", product: null },
],
shops: [{ imvuCreator: 901, shop: false, products: 0 }],
});
expect((await call(undefined, "GET", "/api/v1/imports/available?products=9301,abc")).status).toBe(400);
// Accepting a whole-shop grant lists the shop on IMVU: its products are queued, less those left out.
const made = await call(keeper, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 901, scope: "shop", exclude: [9303], consentVersion: version });
expect(made.json.grant).toMatchObject({ shopListedAt: null, shopListed: 0 });
const grantID = made.json.grant.id as string;
expect((await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`)).json.queued).toBe(0);
await imports.listingsDone();
const view = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json;
expect(view.grants[0]).toMatchObject({ shopListed: 3, shopListedAt: expect.any(String) });
expect(view.jobs.map((j: any) => j.imvuProduct).sort()).toEqual([9301, 9302]);
expect(await imports.info(9302)).toMatchObject({ found: true, name: "Keeper Boots", creatorId: 901 });
// Queued, covered, left out; the fan's own request shows.
expect((await call(fan, "POST", "/api/v1/imports/requests", { imvuProduct: 9302 })).json).toEqual({ status: "queued" });
const queued = await call(fan, "GET", "/api/v1/imports/available?products=9301,9302,9303&creators=901");
expect(queued.json.products).toEqual([
{ imvuProduct: 9301, status: "queued", product: null, requested: false },
{ imvuProduct: 9302, status: "queued", product: null, requested: true },
{ imvuProduct: 9303, status: "none", product: null, requested: false },
]);
expect(queued.json.shops).toEqual([{ imvuCreator: 901, shop: true, products: 0 }]);
// Imported: the hub product; an adult one only for adult accounts.
const jobs = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 5 }, importer)).json.jobs;
const imported: Record<number, string> = {};
for (const j of jobs) {
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${j.id}/token`, { imvuRevision: 1 }, importer);
const rating = j.imvuProduct === 9302 ? "adult" : "general";
const files = [file("index.xml", j.imvuProduct)];
const r = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files, rating, parent: 0, name: "x" }, catalogAuth);
expect(r.status).toBe(201);
imported[j.imvuProduct] = r.json.product;
}
const done = await call(undefined, "GET", "/api/v1/imports/available?products=9301,9302&creators=901");
expect(done.json).toEqual({
products: [
{ imvuProduct: 9301, status: "imported", product: imported[9301] },
{ imvuProduct: 9302, status: "adult", product: null },
],
shops: [{ imvuCreator: 901, shop: true, products: 2 }],
});
// A new product on IMVU: listed again (by the team, or daily), it's queued.
imvuProducts.set(9304, { ...imvuProduct("Keeper Gloves", 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9304]);
expect((await call(fan, "POST", `/api/v1/imports/grants/${grantID}/list`)).status).toBe(403);
const again = await call(owner, "POST", `/api/v1/imports/grants/${grantID}/list`);
expect(again.json).toMatchObject({ listed: 4, queued: 1, grant: { shopListed: 4 } });
imvuProducts.set(9305, { ...imvuProduct("Keeper Belt", 901), creator_name: "shopkeepAv" });
shops.set("shopkeepav", [9301, 9302, 9303, 9304, 9305]);
expect(await imports.listShops()).toEqual({ shops: 0, queued: 0 }); // listed within a day
await db.update(schema.importGrant).set({ shopListedAt: new Date(Date.now() - 2 * 86_400_000) }).where(eq(schema.importGrant.id, grantID));
expect(await imports.listShops()).toEqual({ shops: 1, queued: 1 });
// Grants of chosen products aren't listed.
const chooser = await person("chooser", 902);
const g2 = await call(chooser, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 902, scope: "products", products: [9401], consentVersion: version });
await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/accept`);
expect((await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/list`)).json.error).toBe("not_shop");
});
test("Access Pass products, through the importer's signed-in account", async () => {
const owner = await person("apstall");
const keeper = await person("apkeeper", 903);
const chooser = await person("apchooser", 904);
const reg = await call(owner, "POST", "/api/v1/catalogs", { name: "AP Shelf", url: "https://ap.example.test", contact: "[email protected]", visibility: "public", membership: "open" });
const catalogID = reg.json.catalog.id as string;
const catalogAuth = { Authorization: `Catalog ${catalogID}:${reg.json.key}` };
expect((await call(rootAdmin, "POST", `/api/v1/console/catalogs/${catalogID}/approve`)).status).toBe(200);
const on = await call(owner, "POST", `/api/v1/catalogs/${catalogID}/importer`, { enabled: true });
const importer = { Authorization: `Importer ${catalogID}:${on.json.key}` };
const version = (await call(undefined, "GET", "/api/v1/imports/catalogs")).json.consent.version;
imvuProducts.set(9501, { ...imvuProduct("AP Keeper Coat", 903), creator_name: "apkeeperAv" });
shops.set("apkeeperav", [9501]); // what IMVU lists signed out: the general-rated one
for (const id of [9502, 9503, 9504, 9505]) hiddenProducts.add(id); // Access Pass (or gone): 401 to the hub
// Without an Access Pass account, the hub lists the shop itself; no signed-in listing.
const made = await call(keeper, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 903, scope: "shop", consentVersion: version });
const grantID = made.json.grant.id as string;
await call(owner, "POST", `/api/v1/imports/grants/${grantID}/accept`);
await imports.listingsDone();
let claimed = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 10 }, importer)).json.jobs;
expect(claimed).toEqual([{ id: expect.any(String), kind: "import", imvuProduct: 9501, lastRevision: 0, rating: "general" }]);
await call(undefined, "POST", `/api/v1/importer/jobs/${claimed[0].id}`, { status: "failed", reason: "later" }, importer);
// The importer signs in with an account that has Access Pass: the catalog's whole shops are listed with it.
const [acct] = await db
.insert(schema.importerAccount)
.values({ id: "apacct0001", catalogId: catalogID, imvuId: 777, username: "ImporterAP", position: 0, state: "received" })
.returning();
const signedIn = await call(undefined, "POST", `/api/v1/importer/accounts/${acct!.id}`, { state: "ok", accessPass: true }, importer);
expect(signedIn.json.account).toMatchObject({ state: "ok", accessPass: true });
claimed = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 10 }, importer)).json.jobs;
expect(claimed).toEqual([{ id: expect.any(String), kind: "list", imvuProduct: 0, imvuCreator: 903, lastRevision: 0, rating: null }]);
const list = claimed[0].id as string;
expect((await call(undefined, "POST", `/api/v1/importer/jobs/${list}/token`, { imvuRevision: 1 }, importer)).json.error).toBe("not_product");
const seen = (id: number, name: string, rating: string, creatorId = 903) => ({ id, name, rating, creatorId, creatorName: "apkeeperAv", purchasable: true });
const listed = await call(
undefined,
"POST",
`/api/v1/importer/jobs/${list}/listing`,
{ products: [seen(9501, "AP Keeper Coat", "general"), seen(9502, "AP Keeper Robe", "adult"), seen(9503, "Someone Else's", "adult", 999)] },
importer,
);
expect(listed.json).toEqual({ listed: 2, queued: 1 }); // another creator's product isn't taken from it
expect(await imports.info(9502)).toMatchObject({ found: true, name: "AP Keeper Robe", rating: "adult", creatorId: 903 });
expect(await imports.info(9503)).toBeUndefined();
const grant = (await call(owner, "GET", `/api/v1/catalogs/${catalogID}/importer`)).json.grants[0];
expect(grant).toMatchObject({ shopListed: 2, shopListedSignedIn: true });
expect((await call(undefined, "POST", `/api/v1/importer/jobs/${list}/listing`, { products: [] }, importer)).json.error).toBe("not_claimed");
// The Access Pass product imports as adult; the hub's daily recheck keeps it though IMVU hides it from the hub.
claimed = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 10 }, importer)).json.jobs;
const robe = claimed.find((j: any) => j.imvuProduct === 9502);
expect(robe).toMatchObject({ kind: "import", rating: "adult" });
const tok = await call(undefined, "POST", `/api/v1/importer/jobs/${robe.id}/token`, { imvuRevision: 2 }, importer);
const r = await call(undefined, "POST", "/api/v1/catalog/revisions", { importToken: tok.json.token, files: [file("index.xml", 9502)], rating: "adult", parent: 0, name: "x" }, catalogAuth);
expect(r.status).toBe(201);
await db.update(schema.importJob).set({ updatedAt: new Date(Date.now() - 2 * 86_400_000) }).where(eq(schema.importJob.imvuProduct, 9502));
const rechecked = await imports.recheck();
expect(rechecked.withdrawn).not.toContain(r.json.product);
// Products chosen by ID that IMVU hides from the hub: the importer says what its account sees, then imports.
const g2 = await call(chooser, "POST", "/api/v1/imports/grants", { catalog: catalogID, imvuId: 904, scope: "products", products: [9504, 9505], consentVersion: version });
await call(owner, "POST", `/api/v1/imports/grants/${g2.json.grant.id}/accept`);
claimed = (await call(undefined, "POST", "/api/v1/importer/jobs/claim", { limit: 10 }, importer)).json.jobs;
const hidden = claimed.filter((j: any) => j.imvuProduct === 9504 || j.imvuProduct === 9505);
expect(hidden.map((j: any) => j.rating)).toEqual([null, null]);
const j4 = hidden.find((j: any) => j.imvuProduct === 9504);
const j5 = hidden.find((j: any) => j.imvuProduct === 9505);
expect((await call(undefined, "POST", `/api/v1/importer/jobs/${j4.id}/token`, { imvuRevision: 1 }, importer)).json.error).toBe("not_covered");
const info = await call(undefined, "POST", `/api/v1/importer/jobs/${j4.id}/info`, { found: true, name: "Chosen Veil", rating: "adult", creatorId: 904, creatorName: "chooserAv", purchasable: true }, importer);
expect(info.json).toEqual({ rating: "adult", covered: true });
expect((await call(undefined, "POST", `/api/v1/importer/jobs/${j4.id}/token`, { imvuRevision: 1 }, importer)).status).toBe(200);
// Another creator's, as the account sees it: not covered.
const other = await call(undefined, "POST", `/api/v1/importer/jobs/${j5.id}/info`, { found: true, name: "Not Theirs", rating: "general", creatorId: 999, creatorName: "x", purchasable: true }, importer);
expect(other.json).toEqual({ rating: "general", covered: false });
// What IMVU shows the hub publicly wins over the importer's word.
hiddenProducts.delete(9505);
imvuProducts.set(9505, { ...imvuProduct("Public Now", 904), creator_name: "chooserAv" });
const pub = await call(undefined, "POST", `/api/v1/importer/jobs/${j5.id}/info`, { found: false }, importer);
expect(pub.json).toEqual({ rating: "general", covered: true });
expect(await imports.info(9505)).toMatchObject({ name: "Public Now", creatorId: 904 });
});
+187
View File
@@ -0,0 +1,187 @@
// The hub as an OpenID Connect provider (docs/music.md): T5DE Music signs people in with the authorization code flow
// (PKCE), gets their linked IMVU accounts from the `imvu` scope, and links IMVU accounts through the hub's API with an
// access token for it (`imvu:link`).
import { afterAll, beforeAll, expect, test } from "bun:test";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth, hubResource, seedClients } from "../src/auth";
import { ImvuClient } from "../src/imvu";
import { Settings } from "../src/settings";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const music = {
clientId: "t5de-music",
name: "T5DE Music",
secret: "music-secret-music-secret-music-secret-1234",
redirectUris: ["https://music.test/api/auth/callback"],
};
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const settings = new Settings(db, { registration: "open" });
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false, settings, clients: [music] });
await seedClients(db, apiURL, [music]);
const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch);
const hub = createApp({ db, auth, imvu, webURL, apiURL, settings });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Cookie = { v: string };
async function call(cookie: Cookie, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const form = body instanceof URLSearchParams;
const res = await fetch(base + path, {
method,
redirect: "manual",
headers: {
Origin: webURL,
...(body !== undefined ? { "Content-Type": form ? "application/x-www-form-urlencoded" : "application/json" } : {}),
...(cookie.v ? { Cookie: cookie.v } : {}),
...headers,
},
body: body === undefined ? undefined : form ? body.toString() : JSON.stringify(body),
});
const set = res.headers.getSetCookie();
if (set.length) cookie.v = set.map((c) => c.split(";")[0]).join("; ");
const text = await res.text();
let json: any;
try {
json = text ? JSON.parse(text) : undefined;
} catch {}
return { status: res.status, json, location: res.headers.get("location") ?? "" };
}
async function signUp(name: string) {
const cookie = { v: "" };
expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email: `${name}@example.test`, password: "a long password", name, username: name })).status).toBe(200);
return cookie;
}
const b64url = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url");
/** Music's side: the authorize request, with PKCE and the hub's API as the token's resource. */
async function authorizeURL(scope: string, extra: Record<string, string> = {}) {
const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
const challenge = b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
const q = new URLSearchParams({
response_type: "code",
client_id: music.clientId,
redirect_uri: music.redirectUris[0]!,
scope,
state: "st-" + verifier.slice(0, 6),
code_challenge: challenge,
code_challenge_method: "S256",
resource: hubResource(apiURL),
...extra,
});
return { path: `/api/auth/oauth2/authorize?${q}`, verifier, state: q.get("state")! };
}
/** Music signs `cookie`'s person in: authorize (signed in already), then the code for tokens. */
async function musicSignIn(cookie: Cookie, scope = "openid profile email offline_access imvu imvu:link") {
const a = await authorizeURL(scope);
const r = await call(cookie, "GET", a.path);
expect(r.status).toBe(302);
const back = new URL(r.location);
expect(back.origin + back.pathname).toBe(music.redirectUris[0]!);
expect(back.searchParams.get("state")).toBe(a.state);
const code = back.searchParams.get("code")!;
const token = await call(
{ v: "" },
"POST",
"/api/auth/oauth2/token",
new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: music.redirectUris[0]!, code_verifier: a.verifier, resource: hubResource(apiURL) }),
{ Authorization: "Basic " + Buffer.from(`${music.clientId}:${music.secret}`).toString("base64") },
);
expect(token.status).toBe(200);
return token.json as { access_token: string; id_token: string; refresh_token?: string; scope: string };
}
const bearer = (t: string) => ({ Authorization: `Bearer ${t}` });
test("discovery: the issuer is the API's /api/auth", async () => {
const d = (await call({ v: "" }, "GET", "/api/auth/.well-known/openid-configuration")).json;
expect(d.issuer).toBe(`${apiURL}/api/auth`);
expect(d.scopes_supported).toEqual(expect.arrayContaining(["openid", "imvu", "imvu:link"]));
expect(d.jwks_uri).toBe(`${apiURL}/api/auth/jwks`);
});
test("the sign-in page can name the site asking", async () => {
expect((await call({ v: "" }, "GET", `/api/v1/oauth/clients/${music.clientId}`)).json).toEqual({ client: { name: "T5DE Music", firstParty: true } });
expect((await call({ v: "" }, "GET", "/api/v1/oauth/clients/nobody")).status).toBe(404);
});
test("signed out, authorize sends people to the website's sign-in page with the request", async () => {
const a = await authorizeURL("openid profile imvu", { t5de_provider: "discord" });
const r = await call({ v: "" }, "GET", a.path);
expect(r.status).toBe(302);
const to = new URL(r.location);
expect(to.origin + to.pathname).toBe(`${webURL}/signin`);
expect(to.searchParams.get("client_id")).toBe(music.clientId);
expect(to.searchParams.get("sig")).toBeTruthy();
// The hint for the sign-in page comes along.
expect(to.searchParams.get("t5de_provider")).toBe("discord");
});
test("Music signs a member in without a consent screen, and gets their IMVU accounts", async () => {
const ada = await signUp("ada");
const me = (await call(ada, "GET", "/api/v1/me")).json.person;
await db.insert(schema.imvuLink).values({ imvuId: 4242, userId: me.id, pairwiseId: "pw-4242", username: "AdaInIMVU" });
const t = await musicSignIn(ada);
expect(t.scope.split(" ")).toEqual(expect.arrayContaining(["openid", "imvu", "imvu:link"]));
expect(t.refresh_token).toBeTruthy();
// The ID token carries the IMVU accounts.
const idClaims = JSON.parse(Buffer.from(t.id_token.split(".")[1]!, "base64url").toString());
expect(idClaims).toMatchObject({ iss: `${apiURL}/api/auth`, aud: music.clientId, sub: me.id, imvu: [{ id: 4242, username: "AdaInIMVU" }] });
const info = (await call({ v: "" }, "GET", "/api/auth/oauth2/userinfo", undefined, bearer(t.access_token))).json;
expect(info).toMatchObject({ sub: me.id, preferred_username: "ada", email: "[email protected]", imvu: [{ id: 4242, username: "AdaInIMVU" }] });
// The access token works on the routes for T5DE's sites, and only those.
const imvu = await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token));
expect(imvu.status).toBe(200);
expect(imvu.json.links).toEqual([expect.objectContaining({ imvuId: 4242, username: "AdaInIMVU" })]);
expect((await call({ v: "" }, "GET", "/api/v1/account", undefined, bearer(t.access_token))).json.error).toBe("token_not_allowed");
expect((await call({ v: "" }, "GET", "/api/v1/me", undefined, bearer(t.access_token))).json.error).toBe("token_not_allowed");
// A token that isn't the hub's.
expect((await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer("aaa.bbb.ccc"))).status).toBe(401);
});
test("without imvu and imvu:link, Music gets no IMVU accounts and can't link", async () => {
const bo = await signUp("bo_");
const t = await musicSignIn(bo, "openid profile");
const info = (await call({ v: "" }, "GET", "/api/auth/oauth2/userinfo", undefined, bearer(t.access_token))).json;
expect(info.imvu).toBeUndefined();
expect((await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token))).json.error).toBe("insufficient_scope");
});
test("a basic account links IMVU accounts through Music; the website still says finish setting up", async () => {
// A basic account, as Discord sign-in makes them (discord.test.ts covers that part).
const cy = await signUp("cyd");
const id = (await call(cy, "GET", "/api/v1/me")).json.person.id;
await db.update(schema.user).set({ kind: "basic", username: null, displayUsername: null }).where(eq(schema.user.id, id));
const t = await musicSignIn(cy);
const imvu = await call({ v: "" }, "GET", "/api/v1/account/imvu", undefined, bearer(t.access_token));
expect(imvu).toMatchObject({ status: 200, json: { links: [], canLink: true } });
expect((await call(cy, "GET", "/api/v1/account/imvu")).json.error).toBe("finish_setup");
});
test("a website session still links as before", async () => {
const dee = await signUp("dee");
expect((await call(dee, "GET", "/api/v1/account/imvu")).status).toBe(200);
});
+159 -5
View File
@@ -4,6 +4,7 @@ import { createLocalJWKSet, jwtVerify } from "jose";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, imvuImage, parse, parseProduct, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
@@ -82,6 +83,7 @@ async function person(name: string, imvu?: { id: number; ageVerified: boolean })
accounts.get(imvu.id)!.tagline = started.json.challenge.code;
expect((await call(p, "POST", `/api/v1/account/links/${imvu.id}/check`)).status).toBe(200);
}
await twoFactorOn(db, name);
return p;
}
@@ -122,10 +124,22 @@ test("catalogs register uploads; products have revisions, info and libraries", a
expect((await call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: up.json.token, files, rating: "general", parent: 0, name: "x", notes: "" }, { Authorization: `Catalog ${catalogID}:wrong` })).status).toBe(401);
const made = await revision(up.json.token);
expect(made.status).toBe(201);
expect(made.json.revision).toBe(1);
expect(made.json).toMatchObject({ revision: 1, draft: true });
const id = made.json.product as string;
expect(id).toMatch(/^[a-z2-7]{10}$/);
// A new product is a draft: only its creator (and moderators) see it, and nobody can get it until it's published.
expect((await call(undefined, "GET", `/api/v1/products/${id}`)).status).toBe(404);
expect((await call(kid, "GET", `/api/v1/products/${id}`)).status).toBe(404);
expect((await call(kid, "GET", `/api/v1/products/${id}/files`)).status).toBe(404);
expect((await call(admin, "GET", `/api/v1/products/${id}`)).json.product.status).toBe("draft");
expect((await call(maker, "GET", `/api/v1/products/${id}`)).json.product).toMatchObject({ status: "draft", publishedAt: null });
expect((await call(maker, "PUT", `/api/v1/library/${id}`)).json.error).toBe("draft");
expect((await call(maker, "GET", "/api/v1/products?creator=maker")).json.products).toEqual([]);
expect((await call(kid, "POST", `/api/v1/products/${id}/publish`)).status).toBe(403);
expect((await call(maker, "POST", `/api/v1/products/${id}/publish`)).json.product.status).toBe("published");
expect((await call(maker, "POST", `/api/v1/products/${id}/publish`)).json.error).toBe("published");
// Its page: info, revisions (files sorted), hosting.
const page = (await call(undefined, "GET", `/api/v1/products/${id}`)).json;
expect(page.product).toMatchObject({ name: "Blue Coat", rating: "general", latest: 1, creator: "maker" });
@@ -147,7 +161,7 @@ test("catalogs register uploads; products have revisions, info and libraries", a
expect((await revision(up2)).status).toBe(400);
expect((await revision(up2, { notes: "same" })).status).toBe(409);
const r2 = await revision(up2, { notes: "Brighter", files: [file("index.xml", 1), file("tex.png", 3)] });
expect(r2.json).toEqual({ product: id, revision: 2 });
expect(r2.json).toEqual({ product: id, revision: 2, draft: false });
// Someone else's upload token can't add to it.
expect((await call(kid, "POST", "/api/v1/products/upload", { catalog: catalogID, product: id })).status).toBe(403);
@@ -174,14 +188,19 @@ test("catalogs register uploads; products have revisions, info and libraries", a
// Adult products are only for adults.
const up3 = (await call(maker, "POST", "/api/v1/products/upload", { catalog: catalogID })).json.token;
const adultID = (await revision(up3, { rating: "adult", name: "Lace" })).json.product;
await call(maker, "POST", `/api/v1/products/${adultID}/publish`);
expect((await call(maker, "GET", `/api/v1/products/${adultID}`)).status).toBe(200);
expect((await call(kid, "GET", `/api/v1/products/${adultID}`)).status).toBe(404);
// Its creator and moderators see it without an adult account; getting or wearing it still needs one.
expect((await call(admin, "GET", `/api/v1/products/${adultID}`)).status).toBe(200);
expect((await call(admin, "PUT", `/api/v1/library/${adultID}`)).status).toBe(404);
expect((await call(admin, "GET", `/api/v1/products/${adultID}/files`)).status).toBe(404);
expect((await call(kid, "PUT", `/api/v1/library/${adultID}`)).status).toBe(404);
expect((await call(undefined, "GET", "/api/v1/products")).json.products.map((p: any) => p.name)).toEqual(["Blue Coat"]);
expect((await call(maker, "GET", "/api/v1/products?q=lac")).json.products.map((p: any) => p.name)).toEqual(["Lace"]);
// Lowering a rating waits for review.
expect((await call(maker, "PATCH", `/api/v1/products/${adultID}`, { rating: "general" })).json.error).toBe("review_needed");
// Its files are rated adult, so it can't be lowered (a revision rated general can be reviewed: cases.test.ts).
expect((await call(maker, "PATCH", `/api/v1/products/${adultID}`, { rating: "general" })).json.error).toBe("files_adult");
expect((await call(kid, "DELETE", `/api/v1/library/${id}`)).status).toBe(204);
expect((await call(kid, "GET", "/api/v1/library")).json.library).toEqual([]);
@@ -195,7 +214,7 @@ test("IMVU product info: parsing and image addresses", () => {
const answer = {
denormalized: {
"https://api.imvu.com/product/product-9": {
data: { product_image: "https://x.imvu.com/i.png", gender: "female", category_path: [{ id: 106, name: "Clothing" }, { id: "x", name: "Bad" }, { id: 716, name: " Coats & Jackets " }] },
data: { product_image: "https://x.imvu.com/i.png", gender: "female", category_path: [{ id: 106, name: "Clothing" }, { id: "x", name: "Bad" }, { id: 716, name: " Coats & Jackets " }], product_name: " Coat ", creator_cid: 77, creator_name: "Maker", rating: "AP", is_purchasable: false },
},
},
};
@@ -203,6 +222,11 @@ test("IMVU product info: parsing and image addresses", () => {
image: "https://x.imvu.com/i.png",
categories: [{ id: 106, name: "Clothing" }, { id: 716, name: "Coats & Jackets" }],
gender: "female",
name: "Coat",
creatorId: 77,
creatorName: "Maker",
adult: true,
purchasable: false,
});
expect(parseProduct(answer, 10)).toBeNull();
});
@@ -230,6 +254,7 @@ test("derived products carry their IMVU parent's image and categories", async ()
const token = (await call(dresser, "POST", "/api/v1/products/upload", { catalog: catalogID })).json.token;
const r = await call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: token, files: [file("index.xml", parent || 9)], rating: "general", parent, name, notes: "" }, auth);
expect(r.status).toBe(201);
await call(dresser, "POST", `/api/v1/products/${r.json.product}/publish`);
return r.json.product as string;
};
const coatID = await upload("Dresser Coat", 7001);
@@ -266,6 +291,28 @@ test("derived products carry their IMVU parent's image and categories", async ()
expect(await page(missingID)).toMatchObject({ parent: 7999, image: null, categories: [] });
expect(await hub.products.fillParentInfo(50)).toBe(0);
// A product can be filed under another category the hub has seen, in its parent's top-level category: a jacket
// made from a plain top goes under Coats & Jackets, never under Hair or Body (another kind of product).
imvuProducts.set(7004, { ...coat, category_path: coat.category_path.slice(0, 3) });
const jacketID = await upload("Dresser Jacket", 7004);
for (let i = 0; i < 100 && (await page(jacketID)).categories.length === 0; i++) await Bun.sleep(20);
const { choices, parent } = (await call(dresser, "GET", `/api/v1/products/${jacketID}/categories`)).json;
expect(parent.map((c: any) => c.id)).toEqual([106, 40, 128]);
expect(choices.map((c: any) => c.at(-1).id).sort()).toEqual([106, 128, 40, 716]);
expect((await call(undefined, "GET", `/api/v1/products/${jacketID}/categories`)).status).toBe(401);
expect((await call(dresser, "PATCH", `/api/v1/products/${jacketID}`, { category: 75 })).json.error).toBe("invalid");
const filed = await call(dresser, "PATCH", `/api/v1/products/${jacketID}`, { category: 716 });
expect(filed.json.fields).toEqual(["category"]);
expect(filed.json.product.categories).toEqual(coat.category_path);
expect(filed.json.product.category).toEqual(coat.category_path);
expect(await names("&category=716")).toEqual(["Dresser Coat", "Dresser Jacket"]);
// Back to its parent's: the history keeps paths, and undoing puts the chosen one back.
expect((await call(dresser, "PATCH", `/api/v1/products/${jacketID}`, { category: null })).json.product.categories).toEqual(parent);
expect(await names("&category=716")).toEqual(["Dresser Coat"]);
const [cleared] = (await call(dresser, "GET", `/api/v1/products/${jacketID}/history`)).json.entries;
expect(cleared.changes.category).toEqual({ from: coat.category_path, to: null });
expect((await call(dresser, "POST", `/api/v1/products/${jacketID}/history/${cleared.id}/revert`, {})).json.product.categories).toEqual(coat.category_path);
// The library shows them too.
expect((await call(dresser, "PUT", `/api/v1/library/${coatID}`)).status).toBe(200);
expect((await call(dresser, "GET", "/api/v1/library")).json.library[0].product).toMatchObject({ image: coat.product_image });
@@ -287,6 +334,7 @@ test("creators delete products (those who have them keep them); moderation remov
const make = async (name: string) => {
const token = (await call(maker, "POST", "/api/v1/products/upload", { catalog: catalogID })).json.token;
const r = await call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: token, files: [file(`${name}.xml`, 1)], rating: "general", parent: 500, name, notes: "" }, auth);
await call(maker, "POST", `/api/v1/products/${r.json.product}/publish`);
return r.json.product as string;
};
const listed = async () => (await call(undefined, "GET", "/api/v1/products?q=gone")).json.products.map((p: any) => p.name);
@@ -313,3 +361,109 @@ test("creators delete products (those who have them keep them); moderation remov
expect((await call(owner, "GET", `/api/v1/products/${bad}/files`)).status).toBe(410);
expect((await call(owner, "GET", "/api/v1/library")).json.library.map((l: any) => l.product.id)).toEqual([id]);
});
test("product info: moderators edit with reasons and lock fields; history and reverts; unlisted and tags", async () => {
const { admin, catalogID, auth } = shared;
const maker = await person("tailor", { id: 521, ageVerified: true });
const other = await person("browser", { id: 522, ageVerified: true });
const mod = await person("warden", { id: 523, ageVerified: true });
const modID = (await call(mod, "GET", "/api/v1/me")).json.person.id;
expect((await call(admin, "POST", `/api/v1/console/people/${modID}/role`, { role: "moderator" })).status).toBe(200);
const token = (await call(maker, "POST", "/api/v1/products/upload", { catalog: catalogID })).json.token;
const id = (await call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: token, files: [file("vest.xml", 7)], rating: "general", parent: 0, name: "Vest", notes: "" }, auth)).json.product as string;
// The creator sets it up while it's a draft: tags (cleaned), unlisted; then publishes.
const set = await call(maker, "PATCH", `/api/v1/products/${id}`, { tags: [" Formal ", "formal", "Wool Blend"], listed: false });
expect(set.json.fields).toEqual(["tags", "listed"]);
expect(set.json.product).toMatchObject({ tags: ["formal", "wool blend"], listed: false });
expect((await call(maker, "PATCH", `/api/v1/products/${id}`, { tags: ["<b>"] })).json.error).toBe("invalid");
expect((await call(maker, "PATCH", `/api/v1/products/${id}`, { listed: false })).json.fields).toEqual([]);
await call(maker, "POST", `/api/v1/products/${id}/publish`);
// Unlisted: not in lists or search for others (its creator still sees it); its link works, and people can get it.
const names = async (p: Person | undefined, qs: string) => (await call(p, "GET", `/api/v1/products?${qs}`)).json.products.map((x: any) => x.name);
expect(await names(other, "creator=tailor")).toEqual([]);
expect(await names(maker, "creator=tailor")).toEqual(["Vest"]);
expect((await call(other, "GET", `/api/v1/products/${id}`)).status).toBe(200);
expect((await call(other, "PUT", `/api/v1/library/${id}`)).status).toBe(200);
await call(maker, "PATCH", `/api/v1/products/${id}`, { listed: true });
expect(await names(other, "tag=formal")).toEqual(["Vest"]);
expect(await names(other, "tag=Wool%20Blend")).toEqual(["Vest"]);
expect(await names(other, "tag=denim")).toEqual([]);
expect(await names(other, `creator=tailor&catalog=${catalogID}`)).toEqual(["Vest"]);
// Others can't edit; a moderator can, with a reason the creator sees.
expect((await call(other, "PATCH", `/api/v1/products/${id}`, { name: "Mine" })).json).toMatchObject({
error: "forbidden",
missing: { permission: "product:edit" },
});
expect((await call(mod, "PATCH", `/api/v1/products/${id}`, { name: "Wool Vest" })).json.error).toBe("reason_needed");
expect((await call(mod, "PATCH", `/api/v1/products/${id}`, { name: "Wool Vest", reason: "Misleading name" })).status).toBe(200);
// Locks: the creator can't change a locked field; moderators can. The page lists what the person may do.
expect((await call(maker, "PUT", `/api/v1/products/${id}/locks`, { fields: ["name"], reason: "x" })).status).toBe(403);
expect((await call(mod, "PUT", `/api/v1/products/${id}/locks`, { fields: ["name"], reason: "" })).json.error).toBe("reason_needed");
expect((await call(mod, "PUT", `/api/v1/products/${id}/locks`, { fields: ["name"], reason: "Keeps renaming it" })).json.product.locked).toEqual(["name"]);
expect((await call(maker, "PATCH", `/api/v1/products/${id}`, { name: "Vest!" })).json.error).toBe("locked");
expect((await call(maker, "PATCH", `/api/v1/products/${id}`, { description: "<p>Warm</p>" })).status).toBe(200);
const page = (await call(maker, "GET", `/api/v1/products/${id}`)).json;
expect(page.product.locked).toEqual(["name"]);
expect(page.permissions).toContain("product:edit");
expect(page.permissions).not.toContain("product:edit-locked");
expect((await call(mod, "GET", `/api/v1/products/${id}`)).json.permissions).toContain("product:edit-locked");
// Ratings: anyone with product:edit raises it; lowering is for moderators, and not below its files' rating.
expect((await call(maker, "PATCH", `/api/v1/products/${id}`, { rating: "adult" })).status).toBe(200);
expect((await call(maker, "PATCH", `/api/v1/products/${id}`, { rating: "general" })).json).toMatchObject({
product: { rating: "adult" },
review: expect.any(Number),
});
expect((await call(mod, "PATCH", `/api/v1/products/${id}`, { rating: "general", reason: "Not adult" })).status).toBe(200);
// The history: every change, newest first, with who and why. Only the creator and moderators read it.
expect((await call(other, "GET", `/api/v1/products/${id}/history`)).status).toBe(403);
const history = (await call(maker, "GET", `/api/v1/products/${id}/history`)).json.entries;
expect(history.map((e: any) => [e.kind, Object.keys(e.changes).join(), e.by, e.byCreator])).toEqual([
["edit", "rating", "warden", false],
["edit", "rating", "tailor", true],
["edit", "description", "tailor", true],
["lock", "locked", "warden", false],
["edit", "name", "warden", false],
["edit", "listed", "tailor", true],
["publish", "status", "tailor", true],
["edit", "tags,listed", "tailor", true],
]);
expect(history[4]).toMatchObject({ reason: "Misleading name", changes: { name: { from: "Vest", to: "Wool Vest" } } });
// Reverting puts back what an entry changed, by the same rules: the name is locked for the creator.
const rename = history[4].id;
expect((await call(maker, "POST", `/api/v1/products/${id}/history/${rename}/revert`, {})).json.error).toBe("locked");
const reverted = await call(mod, "POST", `/api/v1/products/${id}/history/${rename}/revert`, { reason: "My mistake" });
expect(reverted.json.product.name).toBe("Vest");
expect((await call(mod, "POST", `/api/v1/products/${id}/history/${rename}/revert`, { reason: "Again" })).json.error).toBe("unchanged");
const latest = (await call(maker, "GET", `/api/v1/products/${id}/history`)).json.entries[0];
expect(latest).toMatchObject({ kind: "revert", revertOf: rename, reason: "My mistake" });
// Moderators' edits are in the creator's audit log, tagged with the product.
const audit = (await call(maker, "GET", `/api/v1/console/audit?product=${id}`)).json.entries;
expect(audit.map((e: any) => e.action)).toContain("product.lock");
// The console's product list: the creator's own (drafts too); moderators everyone's, filtered.
const draftToken = (await call(maker, "POST", "/api/v1/products/upload", { catalog: catalogID })).json.token;
const draft = (await call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: draftToken, files: [file("cap.xml", 8)], rating: "general", parent: 0, name: "Cap", notes: "" }, auth)).json.product as string;
const mine = (await call(maker, "GET", "/api/v1/console/products")).json;
expect(mine.products.map((p: any) => [p.name, p.status, p.libraries])).toEqual([["Cap", "draft", 0], ["Vest", "published", 1]]);
expect((await call(maker, "GET", "/api/v1/console")).json.todo.drafts).toBe(1);
expect((await call(other, "GET", "/api/v1/console/products")).status).toBe(403);
expect((await call(mod, "GET", "/api/v1/console/products?all=1&status=locked")).json.products.map((p: any) => p.id)).toEqual([id]);
expect((await call(mod, "GET", "/api/v1/console/products?all=1&status=draft&q=tailor")).json.products.map((p: any) => p.id)).toEqual([draft]);
// Drafts never published go after 30 days, and their catalogs are told to delete the files.
expect(await hub.products.purgeDrafts(new Date(Date.now() + 29 * 24 * 60 * 60 * 1000))).toBe(0);
expect(await hub.products.purgeDrafts(new Date(Date.now() + 31 * 24 * 60 * 60 * 1000))).toBeGreaterThanOrEqual(1);
expect((await call(maker, "GET", `/api/v1/products/${draft}`)).status).toBe(404);
expect((await call(maker, "GET", `/api/v1/products/${id}`)).status).toBe(200);
const changes = (await call(undefined, "GET", "/api/v1/catalog/changes", undefined, auth)).json.changes;
expect(changes.find((c: any) => c.product === draft)).toMatchObject({ type: "delete", revision: 1, files: [file("cap.xml", 8)] });
});
+109
View File
@@ -0,0 +1,109 @@
// Registration: open (new accounts can use the hub at once) or closed (they sign in, and wait for a moderator's
// approval); admins switch it in the console, and the environment gives the default.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient } from "../src/imvu";
import { Settings } from "../src/settings";
import { twoFactorOn } from "./two-factor";
const webURL = "http://web.test";
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
// Closed by default (as on staging), until an admin changes it.
const settings = new Settings(db, { registration: "closed" });
const auth = createAuth(db, { apiURL: "http://api.test", webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false, settings });
const imvu = new ImvuClient("http://imvu.test", (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch);
const hub = createApp({ db, auth, imvu, webURL, settings });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
async function call(cookie: { v: string }, method: string, path: string, body?: unknown) {
const res = await fetch(base + path, {
method,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(cookie.v ? { Cookie: cookie.v } : {}) },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const set = res.headers.getSetCookie();
if (set.length) cookie.v = set.map((c) => c.split(";")[0]).join("; ");
const text = await res.text();
return { status: res.status, json: text ? JSON.parse(text) : undefined };
}
async function signUp(name: string) {
const cookie = { v: "" };
expect((await call(cookie, "POST", "/api/auth/sign-up/email", { email: `${name}@example.test`, password: "a long password", name, username: name })).status).toBe(200);
return cookie;
}
test("closed: new accounts wait for approval; the first one runs the hub", async () => {
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "closed", discord: false });
const admin = await signUp("ada");
expect((await call(admin, "GET", "/api/v1/me")).json.person).toMatchObject({ role: "admin", approved: true });
expect((await call(admin, "GET", "/api/v1/account")).status).toBe(200);
const bo = await signUp("bo_");
// Signed in, but nothing else.
expect((await call(bo, "GET", "/api/v1/me")).json.person).toMatchObject({ role: "user", approved: false });
expect(await call(bo, "GET", "/api/v1/account")).toMatchObject({ status: 403, json: { error: "awaiting_approval" } });
expect((await call(bo, "POST", "/api/v1/account/links", { username: "someone" })).status).toBe(403);
expect((await call(bo, "GET", "/api/v1/console")).status).toBe(403);
// Moderators see who's waiting, and approve them.
expect((await call(admin, "GET", "/api/v1/console")).json.moderation.counts.waiting).toBe(1);
const waiting = (await call(admin, "GET", "/api/v1/console/people?waiting=true")).json.people;
expect(waiting.map((p: any) => p.username)).toEqual(["bo_"]);
expect((await call(admin, "POST", `/api/v1/console/people/${waiting[0].id}/approve`)).json.person.approved).toBe(true);
expect((await call(bo, "GET", "/api/v1/account")).status).toBe(200);
expect((await call(admin, "GET", "/api/v1/console/people?waiting=true")).json.people).toEqual([]);
// An approved account can't be declined.
expect((await call(admin, "POST", `/api/v1/console/people/${waiting[0].id}/decline`)).status).toBe(400);
});
test("declining deletes the account", async () => {
const admin = { v: "" };
await call(admin, "POST", "/api/auth/sign-in/username", { username: "ada", password: "a long password" });
const cy = await signUp("cyd");
const [p] = (await call(admin, "GET", "/api/v1/console/people?waiting=true")).json.people;
expect(p.username).toBe("cyd");
expect((await call(admin, "POST", `/api/v1/console/people/${p.id}/decline`)).status).toBe(200);
expect((await call(cy, "GET", "/api/v1/me")).status).toBe(401);
expect((await call({ v: "" }, "POST", "/api/auth/sign-in/username", { username: "cyd", password: "a long password" })).status).toBe(401);
});
test("only admins open or close registration", async () => {
const admin = { v: "" };
await call(admin, "POST", "/api/auth/sign-in/username", { username: "ada", password: "a long password" });
const mod = await signUp("dot");
const dot = (await call(admin, "GET", "/api/v1/console/people?waiting=true")).json.people[0];
await call(admin, "POST", `/api/v1/console/people/${dot.id}/approve`);
// Roles and hub settings are sensitive: two-factor sign-in first.
expect((await call(admin, "POST", `/api/v1/console/people/${dot.id}/role`, { role: "moderator" })).json.error).toBe("two_factor_required");
expect((await call(admin, "PUT", "/api/v1/console/settings", { registration: "open" })).json.error).toBe("two_factor_required");
await twoFactorOn(db, "ada");
await call(admin, "POST", `/api/v1/console/people/${dot.id}/role`, { role: "moderator" });
expect((await call(mod, "GET", "/api/v1/console/settings")).json).toEqual({ registration: "closed" });
expect((await call(mod, "PUT", "/api/v1/console/settings", { registration: "open" })).status).toBe(403);
expect((await call(admin, "PUT", "/api/v1/console/settings", { registration: "open" })).json).toEqual({ registration: "open" });
expect((await call({ v: "" }, "GET", "/api/v1/hub")).json).toEqual({ registration: "open", discord: false });
// Open: new accounts can use the hub at once.
const eve = await signUp("eve");
expect((await call(eve, "GET", "/api/v1/account")).status).toBe(200);
const audit = (await call(admin, "GET", "/api/v1/console")).json.audit.map((e: any) => e.action);
expect(audit).toContain("hub.registration");
});
+215
View File
@@ -0,0 +1,215 @@
// API tokens (docs/console.md): made from a session, limited to their grants and to what their owner holds now,
// usable only on routes that check permissions, audited by name, revocable.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { eq, openDatabase, schema, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { twoFactorOn } from "./two-factor";
import { ImvuClient, type ImvuUser } from "../src/imvu";
const webURL = "http://web.test";
const apiURL = "http://api.test";
const accounts = new Map<number, ImvuUser>();
const fakeIMVU: typeof fetch = (async (input: RequestInfo | URL) => {
const url = new URL(String(input));
if (url.pathname.startsWith("/product/")) return Response.json({ status: "failure" }, { status: 404 });
const u = [...accounts.values()].find(
(u) => url.pathname === `/user/user-${u.id}` || url.searchParams.get("username")?.toLowerCase() === u.username.toLowerCase(),
);
return Response.json({
denormalized: u
? { [`https://api.imvu.com/user/user-${u.id}`]: { data: { legacy_cid: u.id, username: u.username, tagline: u.tagline, is_ageverified: u.ageVerified, is_ap: u.accessPass } } }
: {},
});
}) as typeof fetch;
// Catalog addresses that answer /health (for address changes).
const healthy = new Set<string>(["https://moved.example.test"]);
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL, webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({
db,
auth,
imvu: new ImvuClient("http://imvu.test", fakeIMVU),
apiURL,
webURL,
catalogHealthy: async (url) => healthy.has(url),
});
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
type Person = { cookie: string; name: string };
async function call(p: Person | undefined, method: string, path: string, body?: unknown, headers: Record<string, string> = {}) {
const res = await fetch(base + path, {
method,
headers: { Origin: webURL, ...(body !== undefined ? { "Content-Type": "application/json" } : {}), ...(p ? { Cookie: p.cookie } : {}), ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json: any;
try {
json = JSON.parse(text);
} catch {
json = text;
}
return { status: res.status, json };
}
async function person(name: string): Promise<Person> {
const res = await fetch(base + "/api/auth/sign-up/email", {
method: "POST",
headers: { Origin: webURL, "Content-Type": "application/json" },
body: JSON.stringify({ email: `${name}@example.test`, password: "a long password", name, username: name }),
});
await twoFactorOn(db, name);
return { cookie: res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "), name };
}
const file = (name: string, n: number) => ({ name, sha256: n.toString(16).padStart(64, "0"), size: 100 * n });
/** A person's catalog, registered and approved; its key's Authorization header. */
async function catalogOf(owner: Person, admin: Person, name: string, membership = "open") {
const reg = await call(owner, "POST", "/api/v1/catalogs", {
name,
url: `https://${name.toLowerCase().replace(/\W/g, "")}.example.test`,
contact: "[email protected]",
visibility: "public",
membership,
});
expect(reg.status).toBe(201);
const id = reg.json.catalog.id as string;
expect((await call(admin, "POST", `/api/v1/console/catalogs/${id}/approve`)).status).toBe(200);
return { id, auth: { Authorization: `Catalog ${id}:${reg.json.key}` } };
}
/** A product uploaded by a person to a catalog; its ID. */
async function upload(maker: Person, c: { id: string; auth: Record<string, string> }, name: string, n: number, rating = "general") {
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
expect(tok.status).toBe(200);
const r = await call(
undefined,
"POST",
"/api/v1/catalog/revisions",
{ uploadToken: tok.json.token, files: [file("index.xml", n)], rating, parent: 0, name, notes: "" },
c.auth,
);
expect(r.status).toBe(201);
expect((await call(maker, "POST", `/api/v1/products/${r.json.product}/publish`)).status).toBe(200);
return r.json.product as string;
}
/** A revision with these files, by a person, to a catalog: the answer. */
async function uploadFiles(maker: Person, c: { id: string; auth: Record<string, string> }, name: string, files: unknown[]) {
const tok = await call(maker, "POST", "/api/v1/products/upload", { catalog: c.id });
return call(undefined, "POST", "/api/v1/catalog/revisions", { uploadToken: tok.json.token, files, rating: "general", parent: 0, name, notes: "" }, c.auth);
}
let admin: Person;
let mod: Person;
test("the first account is the admin; a moderator", async () => {
admin = await person("admin1");
mod = await person("warden");
const id = (await call(mod, "GET", "/api/v1/me")).json.person.id;
expect((await call(admin, "POST", `/api/v1/console/people/${id}/role`, { role: "moderator" })).status).toBe(200);
});
const bearer = (token: string) => ({ Authorization: `Bearer ${token}` });
const at = (type: "product" | "catalog", id: string) => ({ type, id });
test("tokens: made from a session, limited to their grants, usable only where permissions are checked", async () => {
const owner = await person("shelfowner");
const maker = await person("maker");
const c = await catalogOf(owner, admin, "Token Shelf");
const hat = await upload(maker, c, "Hat", 1);
const scarf = await upload(maker, c, "Scarf", 2);
const theirs = await upload(owner, c, "Owner's Coat", 3);
// Only what the person holds now.
const make = (p: Person, grants: unknown[], name = "script", days = 30) => call(p, "POST", "/api/v1/account/tokens", { name, days, grants });
expect((await make(maker, [{ permission: "product:edit", scope: at("product", theirs) }])).json.error).toBe("not_held");
expect((await make(maker, [{ permission: "product:remove", scope: { type: "hub" } }])).json.error).toBe("not_held");
expect((await make(maker, [{ permission: "no:such", scope: at("product", hat) }])).status).toBe(400);
expect((await make(maker, [])).status).toBe(400);
expect((await make(maker, [{ permission: "product:edit", scope: at("product", hat) }], "x", 400)).status).toBe(400);
expect((await make(undefined as unknown as Person, [{ permission: "product:edit", scope: at("product", hat) }])).status).toBe(401);
const made = await make(maker, [
{ permission: "product:edit", scope: at("product", hat) },
{ permission: "revision:upload", scope: at("product", hat) },
{ permission: "product:edit", scope: at("product", hat) },
], "Hat updater");
expect(made.status).toBe(201);
const tok = made.json.token as string;
expect(tok).toMatch(/^t5de_pat_[A-Za-z0-9_-]{43}$/);
expect(made.json.info).toMatchObject({ name: "Hat updater", status: "active", lastUsedAt: null });
expect(made.json.info.grants).toEqual([
{ permission: "product:edit", scope: at("product", hat), name: "Hat" },
{ permission: "revision:upload", scope: at("product", hat), name: "Hat" },
]);
expect(JSON.stringify(made.json.info)).not.toContain(tok);
// What it grants, there.
const asToken = (method: string, path: string, body?: unknown) => call(undefined, method, path, body, bearer(tok));
expect((await asToken("PATCH", `/api/v1/products/${hat}`, { description: "By script" })).status).toBe(200);
const other = await asToken("PATCH", `/api/v1/products/${scarf}`, { description: "Nope" });
expect(other.status).toBe(403);
expect(other.json.missing).toEqual({ permission: "product:edit", scope: { product: scarf } });
expect((await asToken("POST", `/api/v1/products/${hat}/publish`)).status).toBe(403);
expect((await asToken("POST", "/api/v1/products/upload", { catalog: c.id, product: hat })).status).toBe(200);
expect((await asToken("POST", "/api/v1/products/upload", { catalog: c.id, product: scarf })).status).toBe(403);
expect((await asToken("POST", "/api/v1/products/upload", { catalog: c.id })).json.error).toBe("token_not_allowed");
// Nothing else: session-only routes refuse it, and it can't make tokens; elsewhere it's signed out.
expect((await asToken("GET", "/api/v1/me")).json.error).toBe("token_not_allowed");
expect((await asToken("POST", "/api/v1/account/tokens", { name: "more", days: 1, grants: [{ permission: "product:edit", scope: at("product", hat) }] })).json.error).toBe("token_not_allowed");
expect((await asToken("DELETE", `/api/v1/products/${hat}`)).json.error).toBe("token_not_allowed");
expect((await asToken("POST", "/api/v1/cases", { kind: "report", about: { product: theirs }, reason: "x" })).json.error).toBe("token_not_allowed");
// Audited as the person, by token; listed with its last use.
const entry = (await call(maker, "GET", `/api/v1/console/audit?action=product.edit&product=${hat}`)).json.entries[0];
expect(entry).toMatchObject({ actor: "maker", detail: { token: "Hat updater" } });
const listed = (await call(maker, "GET", "/api/v1/account/tokens")).json.tokens;
expect(listed).toHaveLength(1);
expect(listed[0].lastUsedAt).not.toBeNull();
expect((await call(owner, "GET", "/api/v1/account/tokens")).json.tokens).toEqual([]);
// Revoked or expired: refused.
expect((await call(owner, "DELETE", `/api/v1/account/tokens/${listed[0].id}`)).status).toBe(404);
expect((await call(maker, "DELETE", `/api/v1/account/tokens/${listed[0].id}`)).status).toBe(204);
expect((await asToken("PATCH", `/api/v1/products/${hat}`, { description: "Again" })).json.error).toBe("bad_token");
expect((await call(maker, "GET", "/api/v1/account/tokens")).json.tokens[0].status).toBe("revoked");
expect((await call(undefined, "PATCH", `/api/v1/products/${hat}`, { description: "x" }, bearer("t5de_pat_nope"))).json.error).toBe("bad_token");
const short = (await make(maker, [{ permission: "product:edit", scope: at("product", hat) }], "short", 1)).json;
await db.update(schema.apiToken).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(schema.apiToken.id, short.info.id));
expect((await call(undefined, "PATCH", `/api/v1/products/${hat}`, { description: "x" }, bearer(short.token))).json.error).toBe("bad_token");
});
test("tokens never have more than their owner holds now", async () => {
const made = await call(mod, "POST", "/api/v1/account/tokens", { name: "blocks", days: 7, grants: [{ permission: "product:remove", scope: { type: "hub" } }] });
expect(made.status).toBe(201);
const tok = made.json.token as string;
expect((await call(undefined, "GET", "/api/v1/blocks", undefined, bearer(tok))).status).toBe(200);
// Its grants don't reach other permissions the moderator holds.
expect((await call(undefined, "GET", `/api/v1/catalogs/${(await call(mod, "GET", "/api/v1/console/catalogs")).json.catalogs[0].id}/team`, undefined, bearer(tok))).status).toBe(403);
const id = (await call(mod, "GET", "/api/v1/me")).json.person.id;
expect((await call(admin, "POST", `/api/v1/console/people/${id}/role`, { role: "user" })).status).toBe(200);
expect((await call(undefined, "GET", "/api/v1/blocks", undefined, bearer(tok))).status).toBe(403);
});
+132
View File
@@ -0,0 +1,132 @@
// Two-factor sign-in (docs/console.md): turning it on with an authenticator app, signing in with a code or a backup
// code, and sensitive permissions needing it.
import { afterAll, beforeAll, expect, test } from "bun:test";
import { createHmac } from "node:crypto";
import { openDatabase, type Database } from "@t5de/db";
import { createApp } from "../src/app";
import { createAuth } from "../src/auth";
import { ImvuClient } from "../src/imvu";
const webURL = "http://web.test";
const fakeIMVU = (async () => Response.json({ denormalized: {} })) as unknown as typeof fetch;
let db: Database;
let close: () => Promise<void>;
let base: string;
let stop: () => void;
beforeAll(async () => {
({ db, close } = await openDatabase("memory"));
const auth = createAuth(db, { apiURL: "http://api.test", webURL, secret: "test-secret-test-secret-test-secret-1234", rateLimit: false });
const hub = createApp({ db, auth, imvu: new ImvuClient("http://imvu.test", fakeIMVU), webURL });
hub.app.listen({ port: 0, hostname: "127.0.0.1" });
const server = hub.app.server as unknown as { port: number; stop: () => void };
stop = () => server.stop();
base = `http://127.0.0.1:${server.port}`;
});
afterAll(async () => {
stop();
await close();
});
/** A browser: keeps its cookies (sign-in replaces them). */
class Browser {
cookies = new Map<string, string>();
async call(method: string, path: string, body?: unknown) {
const res = await fetch(base + path, {
method,
headers: {
Origin: webURL,
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
Cookie: [...this.cookies].map(([k, v]) => `${k}=${v}`).join("; "),
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
for (const c of res.headers.getSetCookie()) {
const [pair, ...attrs] = c.split(";");
const [k, v] = [pair!.slice(0, pair!.indexOf("=")), pair!.slice(pair!.indexOf("=") + 1)];
if (!v || attrs.some((a) => /max-age=0\b/i.test(a.trim()))) this.cookies.delete(k);
else this.cookies.set(k, v);
}
const text = await res.text();
return { status: res.status, json: text ? JSON.parse(text) : undefined };
}
}
/** The current code for an otpauth:// URI's secret (RFC 6238: SHA-1, 6 digits, 30 seconds). */
function totp(uri: string): string {
const secret = new URL(uri).searchParams.get("secret")!;
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let bits = "";
for (const ch of secret.replace(/=+$/, "").toUpperCase()) bits += alphabet.indexOf(ch).toString(2).padStart(5, "0");
const key = Buffer.from(bits.match(/.{8}/g)!.map((b) => parseInt(b, 2)));
const counter = Buffer.alloc(8);
counter.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 1000 / 30)));
const h = createHmac("sha1", key).update(counter).digest();
const o = h[h.length - 1]! & 0xf;
return ((h.readUInt32BE(o) & 0x7fffffff) % 1_000_000).toString().padStart(6, "0");
}
const password = "a long password";
test("sensitive permissions need two-factor sign-in; turning it on, signing in with a code or a backup code", async () => {
const admin = new Browser();
expect((await admin.call("POST", "/api/auth/sign-up/email", { email: "[email protected]", password, name: "root", username: "root" })).status).toBe(200);
const other = new Browser();
await other.call("POST", "/api/auth/sign-up/email", { email: "[email protected]", password, name: "pat", username: "pat" });
const patId = (await other.call("GET", "/api/v1/me")).json.person.id;
// Off: the account and the console say what needs it, and sensitive actions refuse.
const before = (await admin.call("GET", "/api/v1/account")).json;
expect(before.twoFactor.enabled).toBe(false);
expect(before.twoFactor.neededFor).toContain("person:ban");
expect(before.twoFactor.neededFor).toContain("settings:edit");
expect((await admin.call("GET", "/api/v1/console")).json.twoFactorNeededFor).toContain("person:role");
const refused = await admin.call("POST", `/api/v1/console/people/${patId}/ban`, { reason: "testing" });
expect(refused.status).toBe(403);
expect(refused.json).toMatchObject({ error: "two_factor_required", permission: "person:ban" });
// People with nothing sensitive aren't asked.
expect((await other.call("GET", "/api/v1/account")).json.twoFactor).toEqual({ enabled: false, neededFor: [] });
// Better Auth's own admin endpoints are closed: they'd skip the check and the audit log.
expect((await admin.call("GET", "/api/auth/admin/list-users")).status).toBe(404);
expect((await admin.call("POST", "/api/auth/admin/ban-user", { userId: patId })).status).toBe(404);
// Turning it on takes the password, then a code from the app.
expect((await admin.call("POST", "/api/auth/two-factor/enable", { password: "wrong password!" })).status).toBe(400);
const setup = (await admin.call("POST", "/api/auth/two-factor/enable", { password })).json;
expect(setup.totpURI).toStartWith("otpauth://totp/T5DE:");
expect(setup.backupCodes).toHaveLength(10);
expect((await admin.call("GET", "/api/v1/account")).json.twoFactor.enabled).toBe(false);
expect((await admin.call("POST", "/api/auth/two-factor/verify-totp", { code: "000000" === totp(setup.totpURI) ? "111111" : "000000" })).status).toBe(401);
expect((await admin.call("POST", "/api/auth/two-factor/verify-totp", { code: totp(setup.totpURI) })).status).toBe(200);
const after = (await admin.call("GET", "/api/v1/account")).json;
expect(after.twoFactor.enabled).toBe(true);
expect(after.person.twoFactor).toBe(true);
expect((await admin.call("GET", "/api/v1/console")).json.twoFactorNeededFor).toEqual([]);
expect((await admin.call("POST", `/api/v1/console/people/${patId}/ban`, { reason: "testing" })).status).toBe(200);
// Signing in now asks for a code: no session until it's given.
const again = new Browser();
const first = await again.call("POST", "/api/auth/sign-in/username", { username: "root", password });
expect(first.json).toMatchObject({ twoFactorRedirect: true, twoFactorMethods: ["totp"] });
expect((await again.call("GET", "/api/v1/me")).status).toBe(401);
expect((await again.call("POST", "/api/auth/two-factor/verify-totp", { code: totp(setup.totpURI) })).status).toBe(200);
expect((await again.call("GET", "/api/v1/me")).json.person.username).toBe("root");
// A backup code works once.
const lost = new Browser();
await lost.call("POST", "/api/auth/sign-in/username", { username: "root", password });
expect((await lost.call("POST", "/api/auth/two-factor/verify-backup-code", { code: setup.backupCodes[0] })).status).toBe(200);
expect((await lost.call("GET", "/api/v1/me")).status).toBe(200);
const reused = new Browser();
await reused.call("POST", "/api/auth/sign-in/username", { username: "root", password });
expect((await reused.call("POST", "/api/auth/two-factor/verify-backup-code", { code: setup.backupCodes[0] })).status).not.toBe(200);
expect((await reused.call("GET", "/api/v1/me")).status).toBe(401);
// Turning it off takes the password; sensitive actions refuse again.
expect((await admin.call("POST", "/api/auth/two-factor/disable", { password })).status).toBe(200);
expect((await admin.call("GET", "/api/v1/account")).json.twoFactor.enabled).toBe(false);
expect((await admin.call("POST", `/api/v1/console/people/${patId}/unban`)).json.error).toBe("two_factor_required");
});
+7
View File
@@ -0,0 +1,7 @@
// Moderation tests act as people with two-factor sign-in on (sensitive permissions need it); two-factor.test.ts tests
// the sign-in itself.
import { eq, schema, type Database } from "@t5de/db";
/** Turns two-factor sign-in on for an account, as if they'd set it up. Signing in again would then ask for a code. */
export const twoFactorOn = (db: Database, username: string) =>
db.update(schema.user).set({ twoFactorEnabled: true }).where(eq(schema.user.username, username.toLowerCase()));
+76 -1
View File
@@ -1,6 +1,7 @@
"use server";
import { revalidatePath } from "next/cache";
import { api, unwrap } from "@/lib/api";
import { redirect } from "next/navigation";
import { api, ApiError, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
const done = () => revalidatePath("/account");
@@ -51,6 +52,27 @@ export async function saveSettings(
});
}
/** Unlinks Discord (members keep their username and password). */
export async function unlinkDiscord(_: ActionState, _form: FormData): Promise<ActionState> {
return attempt(async () => {
unwrap(await api.account.discord.delete());
done();
});
}
/** A basic account (Discord only) becomes a member: a username and password. */
export async function finishSetup(_: ActionState, form: FormData): Promise<ActionState> {
// Passwords aren't trimmed.
const password = typeof form.get("password") === "string" ? (form.get("password") as string) : "";
if (password !== form.get("password2")) return { error: "The passwords don't match." };
const state = await attempt(async () => {
unwrap(await api.account.finish.post({ username: field(form, "username"), password }));
});
if (state?.error) return state;
revalidatePath("/", "layout");
redirect("/account?welcome=1");
}
export async function signOutComputers(_: ActionState, _form: FormData): Promise<ActionState> {
return attempt(async () => {
unwrap(await api.account["signout-computers"].post());
@@ -58,3 +80,56 @@ export async function signOutComputers(_: ActionState, _form: FormData): Promise
return "Signed out everywhere.";
});
}
/** Starts an age check with a provider that checks the person, and sends them to its page. */
export async function startAgeCheck(_: ActionState, form: FormData): Promise<ActionState> {
let url: string | undefined;
const state = await attempt(async () => {
const started = unwrap(await api.age({ provider: field(form, "provider") }).start.post({ returnURL: "/account?age=back" }));
if (started.kind === "redirect") url = started.url;
done();
});
if (url) redirect(url);
return state;
}
/** What making a token answers: the token itself, shown once. */
export type TokenState = { error?: string; token?: string; name?: string } | null;
/** Makes an API token. `grants` is JSON: [{permission, scope}]. */
export async function createToken(_: TokenState, form: FormData): Promise<TokenState> {
let grants: { permission: string; scope: { type: "hub" } | { type: "catalog" | "product"; id: string } }[];
try {
grants = JSON.parse(field(form, "grants") || "[]");
} catch {
return { error: "Choose what it may do." };
}
if (!Array.isArray(grants) || grants.length === 0) return { error: "Choose what it may do." };
try {
const made = unwrap(await api.account.tokens.post({ name: field(form, "name"), days: Number(field(form, "days")), grants }));
done();
return { token: made.token, name: made.info.name };
} catch (e) {
if (e instanceof ApiError) return { error: e.message };
throw e;
}
}
/** Revokes an API token. */
export async function revokeToken(_: ActionState, form: FormData): Promise<ActionState> {
return attempt(async () => {
unwrap(await api.account.tokens({ id: field(form, "id") }).delete());
done();
return "Revoked.";
});
}
/** Claims what an admin recorded for an IMVU account of theirs (an unclaimed creator's products and grants). */
export async function claimCreator(_: ActionState, form: FormData): Promise<ActionState> {
return attempt(async () => {
const r = unwrap(await api.account.claims({ imvu: field(form, "imvuId") }).post());
done();
revalidatePath("/imports");
return `They're yours: ${r.products} product${r.products === 1 ? "" : "s"}. Manage them on the Imports page.`;
});
}
+68
View File
@@ -0,0 +1,68 @@
import { ActionForm, SubmitButton } from "@/components/forms";
import { Tag } from "@/components/status";
import { TimeAgo } from "@/components/time";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { AgeInfo } from "@/lib/api";
import { startAgeCheck } from "./actions";
/** The person's own age check (an ID document, say), which covers all their IMVU accounts. */
export function AgeCard({ age, back }: { age: AgeInfo; back: boolean }) {
const ways = age.providers.filter((p) => p.scope === "person");
if (ways.length === 0) return null;
const now = Date.now();
const verified = age.checks.find(
(c) => c.status === "complete" && c.overEighteen && (!c.expiresAt || new Date(c.expiresAt).getTime() > now),
);
const latest = age.checks[0];
const pending = latest?.status === "pending" ? latest : undefined;
const vendorOf = (id: string) => age.providers.find((p) => p.id === id)?.vendor ?? id;
return (
<Card>
<CardHeader>
<CardTitle>Age Verification</CardTitle>
</CardHeader>
<CardContent className="space-y-4 text-sm">
{verified ? (
<p className="flex flex-wrap items-center gap-2">
<Tag tone="adult">Age verified</Tag>
<span className="text-muted-foreground">
with {vendorOf(verified.provider)} <TimeAgo iso={verified.checkedAt ?? verified.createdAt} />. All your
IMVU accounts count as adult.
</span>
</p>
) : (
<>
{pending ? (
<p>
{back
? "Thanks. Your check is being processed; this page shows the result when it's done."
: "Your check isn't finished yet."}
</p>
) : latest?.status === "complete" && !latest.overEighteen ? (
<p>Your last check found you're under 18.</p>
) : latest?.status === "failed" || latest?.status === "revoked" ? (
<p>Your last check didn&apos;t pass. You can try again.</p>
) : (
<p className="text-muted-foreground">
Verify your age once to count as adult on all your IMVU accounts, not only those IMVU has age verified.
</p>
)}
{ways.map((p) => (
<ActionForm key={p.id} action={startAgeCheck} fields={{ provider: p.id }}>
<div className="space-y-2">
<SubmitButton variant={pending && pending.provider !== p.id ? "outline" : "default"} pendingLabel="Starting…">
{pending?.provider === p.id ? "Continue check" : `Verify with ${p.label}`}
</SubmitButton>
<p className="text-xs text-muted-foreground">
Done by {p.vendor}. T5DE only keeps whether you&apos;re over 18, never your ID, photo or birth date.
</p>
</div>
</ActionForm>
))}
</>
)}
</CardContent>
</Card>
);
}
+36
View File
@@ -0,0 +1,36 @@
// Discord on a member's account: link it to sign in with Discord too (and on T5DE's other sites), or unlink it.
import { DiscordButton } from "@/components/discord-button";
import { ActionForm, ErrorText, SubmitButton } from "@/components/forms";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { unlinkDiscord } from "./actions";
export function DiscordCard({ linked, error }: { linked: boolean; error?: string }) {
return (
<Card>
<CardHeader>
<CardTitle>Discord</CardTitle>
<CardDescription>
{linked
? "Linked: you can sign in with Discord, here and on T5DE's other sites."
: "Link Discord to sign in with it, here and on T5DE's other sites."}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{error && <ErrorText>{error}</ErrorText>}
{linked ? (
<ActionForm action={unlinkDiscord}>
<SubmitButton
variant="outline"
pendingLabel="Unlinking…"
confirm="Unlink Discord? You'll sign in with your username and password only."
>
Unlink Discord
</SubmitButton>
</ActionForm>
) : (
<DiscordButton mode="link" />
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,31 @@
"use client";
// A basic account (made by signing in with Discord) chooses a username and password, and becomes a member.
import { ActionForm, SubmitButton } from "@/components/forms";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { finishSetup } from "./actions";
export function FinishSetupForm() {
return (
<ActionForm action={finishSetup}>
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" name="username" autoComplete="username" required minLength={3} maxLength={32} pattern="[A-Za-z0-9_]+" autoFocus />
<FieldDescription>Letters, digits and underscores. Other T5DE members see it.</FieldDescription>
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input id="password" name="password" type="password" autoComplete="new-password" required minLength={10} maxLength={256} />
</Field>
<Field>
<FieldLabel htmlFor="password2">Password again</FieldLabel>
<Input id="password2" name="password2" type="password" autoComplete="new-password" required minLength={10} maxLength={256} />
</Field>
<Field>
<SubmitButton pendingLabel="Setting up…">Finish setting up</SubmitButton>
</Field>
</FieldGroup>
</ActionForm>
);
}
+50 -6
View File
@@ -7,18 +7,28 @@ import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { api, getMe, isModerator, unwrap } from "@/lib/api";
import { linkAccount, signOutComputers } from "./actions";
import { discordError } from "@/lib/discord";
import { claimCreator, linkAccount, signOutComputers } from "./actions";
import { AgeCard } from "./age-card";
import { ChallengeCard } from "./challenge-card";
import { DiscordCard } from "./discord-card";
import { LinkCard } from "./link-card";
import { TokensCard } from "./tokens-card";
import { TwoFactorCard } from "./two-factor-card";
export const metadata: Metadata = { title: "Account" };
export default async function Account({ searchParams }: { searchParams: Promise<{ welcome?: string }> }) {
export default async function Account({ searchParams }: { searchParams: Promise<{ welcome?: string; age?: string; error?: string }> }) {
const me = await getMe();
if (!me) redirect("/signin?next=/account");
const account = unwrap(await api.account.get());
const [account, age, tokens] = await Promise.all([
api.account.get().then(unwrap),
api.age.get().then(unwrap),
api.account.tokens.get().then(unwrap),
]);
const { person, links, challenges, computers } = account;
const welcome = (await searchParams).welcome !== undefined;
const params = await searchParams;
const welcome = params.welcome !== undefined;
return (
<div className="space-y-6">
@@ -56,6 +66,25 @@ export default async function Account({ searchParams }: { searchParams: Promise<
</CardContent>
</Card>
{account.claims.map((c) => (
<Card key={c.imvuId}>
<CardHeader>
<CardTitle>Your IMVU Products on T5DE</CardTitle>
<CardDescription>
Before you joined, you agreed with T5DE to bring {c.username}&apos;s products here, and an admin recorded
it. They&apos;re waiting for you: {c.products} imported product{c.products === 1 ? "" : "s"} and{" "}
{c.grants} catalog{c.grants === 1 ? "" : "s"} hosting them. Claim them to manage them yourself, or to
withdraw them.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={claimCreator} fields={{ imvuId: c.imvuId }}>
<SubmitButton pendingLabel="Claiming…">Claim them</SubmitButton>
</ActionForm>
</CardContent>
</Card>
))}
{challenges.map((c) => (
<ChallengeCard key={c.imvuId} challenge={c} />
))}
@@ -78,12 +107,23 @@ export default async function Account({ searchParams }: { searchParams: Promise<
</p>
)}
<p className="text-sm text-muted-foreground">
Other people can&apos;t see which IMVU accounts are yours. Age-verified IMVU accounts (or with Access Pass)
can see adult community products; each account is checked on its own.
Other people can&apos;t see which IMVU accounts are yours. Adult IMVU accounts can see adult community
products: those IMVU has age verified (or with Access Pass), or all of them once you verify your age below.
</p>
<p className="text-sm text-muted-foreground">
Made products on IMVU?{" "}
<Link href="/imports" className="text-foreground underline underline-offset-4">
Bring them to T5DE
</Link>
.
</p>
</CardContent>
</Card>
<AgeCard age={age} back={params.age === "back"} />
{account.discord.available && <DiscordCard linked={account.discord.linked} error={discordError(params.error)} />}
<Card>
<CardHeader>
<CardTitle>T5DE on your computers</CardTitle>
@@ -112,6 +152,10 @@ export default async function Account({ searchParams }: { searchParams: Promise<
)}
</CardContent>
</Card>
<TwoFactorCard enabled={account.twoFactor.enabled} neededFor={account.twoFactor.neededFor} />
<TokensCard data={tokens} />
</div>
);
}
+168
View File
@@ -0,0 +1,168 @@
"use client";
// Making an API token: a name, how long it lasts, and what it may do where (some of the person's own permissions).
import { ChevronRightIcon } from "lucide-react";
import { useActionState, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import type { TokenScope } from "@/lib/api";
import { createToken } from "./actions";
const keyOf = (s: TokenScope["scope"]) => (s.type === "hub" ? "hub" : `${s.type}:${s.id}`);
const kindOf = { hub: "Everything", catalog: "Catalog", product: "Product" } as const;
type Row = { scope: string; permissions: string[] };
// Permissions are `resource:action`; they're grouped by resource, in this order (new resources go last, by name).
const groupNames: Record<string, string> = {
product: "Products",
revision: "Revisions",
catalog: "Catalog",
team: "Team",
member: "Members",
hosting: "Hosting",
import: "Imports",
case: "Cases",
audit: "Audit Log",
stats: "Stats",
person: "People",
room: "Rooms",
settings: "Settings",
};
const order = Object.keys(groupNames);
/** A scope's permissions, grouped by resource: [group name, permissions]. */
function groupsOf(permissions: string[]): [string, string[]][] {
const by = new Map<string, string[]>();
for (const p of permissions) {
const resource = p.split(":")[0]!;
by.set(resource, [...(by.get(resource) ?? []), p]);
}
const rank = (r: string) => (order.includes(r) ? order.indexOf(r) : order.length);
return [...by.entries()]
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
.map(([r, list]) => [groupNames[r] ?? r.charAt(0).toUpperCase() + r.slice(1), list]);
}
export function TokenForm({ scopes, maxDays }: { scopes: TokenScope[]; maxDays: number }) {
const [state, formAction, pending] = useActionState(createToken, null);
const [rows, setRows] = useState<Row[]>([{ scope: keyOf(scopes[0]!.scope), permissions: [] }]);
const byKey = new Map(scopes.map((s) => [keyOf(s.scope), s]));
const grants = rows.flatMap((r) => r.permissions.map((permission) => ({ permission, scope: byKey.get(r.scope)!.scope })));
const set = (i: number, row: Row) => setRows(rows.map((r, j) => (j === i ? row : r)));
const unused = scopes.find((s) => !rows.some((r) => r.scope === keyOf(s.scope)));
return (
<form action={formAction} className="space-y-4">
<input type="hidden" name="grants" value={JSON.stringify(grants)} />
<div className="flex flex-wrap gap-2">
<Input name="name" required maxLength={64} placeholder="Name, e.g. Upload script" aria-label="Name" className="max-w-xs" />
<NativeSelect name="days" defaultValue="90" aria-label="Lasts" className="w-36">
{[7, 30, 90, maxDays].map((d) => (
<NativeSelectOption key={d} value={d}>
{d === 365 ? "1 year" : `${d} days`}
</NativeSelectOption>
))}
</NativeSelect>
</div>
{rows.map((row, i) => {
const scope = byKey.get(row.scope)!;
return (
<fieldset key={i} className="space-y-2 rounded-lg border p-3">
<div className="flex flex-wrap items-center gap-2">
<NativeSelect
value={row.scope}
onChange={(e) => set(i, { scope: e.target.value, permissions: [] })}
aria-label="Where"
className="min-w-56"
>
{scopes.map((s) => {
const k = keyOf(s.scope);
if (k !== row.scope && rows.some((r) => r.scope === k)) return null;
return (
<NativeSelectOption key={k} value={k}>
{s.scope.type === "hub" ? "Everything on T5DE" : `${kindOf[s.scope.type]}: ${s.name}`}
</NativeSelectOption>
);
})}
</NativeSelect>
{rows.length > 1 && (
<Button type="button" variant="ghost" size="sm" onClick={() => setRows(rows.filter((_, j) => j !== i))}>
Remove
</Button>
)}
</div>
<div className="divide-y rounded-md border">
{groupsOf(scope.permissions).map(([group, list]) => {
const chosen = list.filter((p) => row.permissions.includes(p)).length;
const toggleAll = (on: boolean) =>
set(i, { ...row, permissions: on ? [...new Set([...row.permissions, ...list])] : row.permissions.filter((x) => !list.includes(x)) });
return (
<details key={group} className="group/perm">
<summary className="flex cursor-pointer list-none items-center gap-2 px-3 py-2 text-sm select-none [&::-webkit-details-marker]:hidden">
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-open/perm:rotate-90" aria-hidden />
<input
type="checkbox"
aria-label={`All ${group}`}
checked={chosen === list.length}
ref={(el) => {
if (el) el.indeterminate = chosen > 0 && chosen < list.length;
}}
onChange={(e) => toggleAll(e.target.checked)}
/>
<span className="font-medium">{group}</span>
<span className="text-xs text-muted-foreground">
{chosen > 0 ? `${chosen} of ${list.length}` : list.length === 1 ? "1 permission" : `${list.length} permissions`}
</span>
</summary>
<div className="grid gap-x-4 gap-y-1 px-3 pt-1 pb-3 pl-10 sm:grid-cols-2">
{list.map((p) => (
<label key={p} className="flex items-center gap-2 font-mono text-xs">
<input
type="checkbox"
checked={row.permissions.includes(p)}
onChange={(e) =>
set(i, { ...row, permissions: e.target.checked ? [...row.permissions, p] : row.permissions.filter((x) => x !== p) })
}
/>
{p.slice(p.indexOf(":") + 1)}
</label>
))}
</div>
</details>
);
})}
</div>
</fieldset>
);
})}
<div className="flex flex-wrap gap-2">
{unused && (
<Button type="button" variant="outline" onClick={() => setRows([...rows, { scope: keyOf(unused.scope), permissions: [] }])}>
Add another place
</Button>
)}
<Button type="submit" disabled={pending || grants.length === 0}>
{pending ? "Making…" : "Make token"}
</Button>
</div>
{state?.error && <ErrorText>{state.error}</ErrorText>}
{state?.token && (
<div role="status" className="space-y-2 rounded-lg border p-3 text-sm">
<p>
Your token <strong>{state.name}</strong>. Copy it now: it won&apos;t be shown again.
</p>
<div className="flex flex-wrap items-center gap-2">
<code className="min-w-0 flex-1 rounded bg-muted px-2 py-1 font-mono text-xs break-all">{state.token}</code>
<CopyButton text={state.token} />
</div>
<p className="text-muted-foreground">
Send it as <code className="font-mono text-xs">Authorization: Bearer &lt;token&gt;</code>.
</p>
</div>
)}
</form>
);
}
+97
View File
@@ -0,0 +1,97 @@
// API tokens on the account page: the person's tokens, and making one.
import { ActionForm, SubmitButton } from "@/components/forms";
import { Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import type { TokenEntry, TokenList } from "@/lib/api";
import { revokeToken } from "./actions";
import { TokenForm } from "./token-form";
export function TokensCard({ data }: { data: TokenList }) {
const active = data.tokens.filter((t) => t.status === "active");
const past = data.tokens.filter((t) => t.status !== "active").slice(0, 10);
return (
<Card>
<CardHeader>
<CardTitle>API Tokens</CardTitle>
<CardDescription>
For your own scripts. A token can do only what you give it, and never more than you can do yourself.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{active.length > 0 && (
<ul className="divide-y">
{active.map((t) => (
<TokenRow key={t.id} token={t} />
))}
</ul>
)}
{data.scopes.length > 0 ? (
<TokenForm scopes={data.scopes} maxDays={data.maxDays} />
) : (
<p className="text-sm text-muted-foreground">
Tokens act on what you manage: your products or a catalog&apos;s team. You don&apos;t manage anything yet.
</p>
)}
{past.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">Revoked and expired</summary>
<ul className="mt-2 divide-y">
{past.map((t) => (
<TokenRow key={t.id} token={t} />
))}
</ul>
</details>
)}
</CardContent>
</Card>
);
}
function TokenRow({ token: t }: { token: TokenEntry }) {
return (
<li className="space-y-1 py-3 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{t.name}</span>
{t.status !== "active" && <Tag tone={t.status === "revoked" ? "danger" : "neutral"}>{t.status}</Tag>}
<span className="flex-1" />
{t.status === "active" && (
<ActionForm action={revokeToken} fields={{ id: t.id }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Revoking…" confirm={`Revoke ${t.name}? Scripts using it stop working.`}>
Revoke
</SubmitButton>
</ActionForm>
)}
</div>
<p className="text-xs text-muted-foreground">
{t.grants.map((g, i) => (
<span key={i}>
{i > 0 && ", "}
<span className="font-mono">{g.permission}</span> on {g.scope.type === "hub" ? "everything" : g.name}
</span>
))}
</p>
<p className="text-xs text-muted-foreground">
Made <DateTime iso={t.createdAt} dateOnly />
{" · "}
{t.status === "revoked" && t.revokedAt ? (
<>
revoked <DateTime iso={t.revokedAt} dateOnly />
</>
) : (
<>
{t.status === "expired" ? "expired" : "expires"} <DateTime iso={t.expiresAt} dateOnly />
</>
)}
{" · "}
{t.lastUsedAt ? (
<>
last used <DateTime iso={t.lastUsedAt} />
</>
) : (
"never used"
)}
</p>
</li>
);
}
+232
View File
@@ -0,0 +1,232 @@
"use client";
// Two-factor sign-in on the account page: turning it on (scan a code into an authenticator app, keep the backup codes,
// confirm with a code), new backup codes, and turning it off. Sensitive permissions need it on.
import { useRouter } from "next/navigation";
import { useState } from "react";
import { renderSVG } from "uqr";
import { CopyButton } from "@/components/copy-button";
import { ErrorText } from "@/components/forms";
import { Tag } from "@/components/status";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
type Stage =
| { kind: "idle" }
| { kind: "password"; then: "enable" | "codes" | "disable" }
| { kind: "setup"; uri: string; codes: string[] }
| { kind: "codes"; codes: string[] };
export function TwoFactorCard({ enabled, neededFor }: { enabled: boolean; neededFor: string[] }) {
const router = useRouter();
const [stage, setStage] = useState<Stage>({ kind: "idle" });
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
async function run(fn: () => Promise<string | void>) {
setError("");
setPending(true);
const failed = await fn();
if (failed) setError(failed);
setPending(false);
}
async function withPassword(then: "enable" | "codes" | "disable", password: string) {
if (then === "enable") {
const { data, error } = await authClient.twoFactor.enable({ password });
if (error || !data || !("totpURI" in data) || !data.totpURI)
return error?.message ?? "That didn't work. Try again.";
setStage({
kind: "setup",
uri: data.totpURI,
codes: data.backupCodes ?? [],
});
} else if (then === "codes") {
const { data, error } = await authClient.twoFactor.generateBackupCodes({
password,
});
if (error || !data) return error?.message ?? "That didn't work. Try again.";
setStage({ kind: "codes", codes: data.backupCodes });
} else {
const { error } = await authClient.twoFactor.disable({ password });
if (error) return error.message ?? "That didn't work. Try again.";
setStage({ kind: "idle" });
router.refresh();
}
}
async function confirm(code: string) {
const { error } = await authClient.twoFactor.verifyTotp({
code: code.replace(/\s+/g, ""),
});
if (error) return error.message ?? "That code didn't work. Try again.";
setStage({ kind: "idle" });
router.refresh();
}
const submitTo = (fn: (form: FormData) => Promise<string | void>) => (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const form = new FormData(e.currentTarget);
void run(() => fn(form));
};
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Two-Factor Sign-In {enabled && <Tag tone="strong">on</Tag>}
</CardTitle>
<CardDescription>
Signing in asks for a code from an authenticator app on your phone as well as your password.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{!enabled && neededFor.length > 0 && stage.kind !== "setup" && (
<Alert>
<AlertTitle>Turn this on to use everything you can do</AlertTitle>
<AlertDescription>
<span>
These need it:{" "}
{neededFor.map((p, i) => (
<span key={p}>
{i > 0 && ", "}
<span className="font-mono text-xs">{p}</span>
</span>
))}
.
</span>
</AlertDescription>
</Alert>
)}
{stage.kind === "idle" &&
(enabled ? (
<div className="flex flex-wrap gap-2">
<Button variant="outline" onClick={() => setStage({ kind: "password", then: "codes" })}>
New backup codes
</Button>
<Button variant="outline" onClick={() => setStage({ kind: "password", then: "disable" })}>
Turn off
</Button>
</div>
) : (
<Button onClick={() => setStage({ kind: "password", then: "enable" })}>Turn on</Button>
))}
{stage.kind === "password" && (
<form onSubmit={submitTo((f) => withPassword(stage.then, String(f.get("password"))))} className="space-y-3">
<p className="text-sm">
{stage.then === "disable"
? neededFor.length > 0
? "Turning it off stops the things listed above working until you turn it on again. Enter your password."
: "Enter your password to turn it off."
: stage.then === "codes"
? "Your old backup codes stop working. Enter your password."
: "Enter your password to start."}
</p>
<div className="flex max-w-md flex-wrap gap-2">
<Input
name="password"
type="password"
autoComplete="current-password"
required
autoFocus
aria-label="Password"
className="max-w-xs"
/>
<Button type="submit" variant={stage.then === "disable" ? "destructive" : "default"} disabled={pending}>
{pending ? "Checking…" : stage.then === "disable" ? "Turn off" : "Continue"}
</Button>
<Button type="button" variant="ghost" onClick={() => setStage({ kind: "idle" })}>
Cancel
</Button>
</div>
</form>
)}
{stage.kind === "setup" && (
<div className="space-y-4">
<ol className="list-decimal space-y-4 pl-5 text-sm">
<li className="space-y-2">
<p>
Scan this with an authenticator app (such as Google Authenticator, Microsoft Authenticator or
1Password).
</p>
<div
className="w-44 rounded-md bg-white p-2 [&>svg]:h-auto [&>svg]:w-full"
role="img"
aria-label="QR code for your authenticator app"
dangerouslySetInnerHTML={{
__html: renderSVG(stage.uri, { border: 1 }),
}}
/>
<p className="text-muted-foreground">
Or enter this key:{" "}
<code className="font-mono text-xs break-all text-foreground">
{new URL(stage.uri).searchParams.get("secret")}
</code>
</p>
</li>
<li className="space-y-2">
<p>Keep these backup codes somewhere safe. Each signs you in once if you lose your phone.</p>
<BackupCodes codes={stage.codes} />
</li>
<li className="space-y-2">
<p>Enter the code the app shows.</p>
<form
onSubmit={submitTo((f) => confirm(String(f.get("code"))))}
className="flex max-w-md flex-wrap gap-2"
>
<Input
name="code"
required
inputMode="numeric"
pattern="\s*[0-9]{6}\s*"
maxLength={8}
autoComplete="one-time-code"
aria-label="Code"
placeholder="123456"
className="w-32 font-mono"
/>
<Button type="submit" disabled={pending}>
{pending ? "Checking…" : "Turn on"}
</Button>
<Button type="button" variant="ghost" onClick={() => setStage({ kind: "idle" })}>
Cancel
</Button>
</form>
</li>
</ol>
</div>
)}
{stage.kind === "codes" && (
<div className="space-y-2 text-sm">
<p>Your new backup codes. Keep them somewhere safe: they won&apos;t be shown again.</p>
<BackupCodes codes={stage.codes} />
<Button variant="outline" onClick={() => setStage({ kind: "idle" })}>
Done
</Button>
</div>
)}
{error && <ErrorText>{error}</ErrorText>}
</CardContent>
</Card>
);
}
function BackupCodes({ codes }: { codes: string[] }) {
return (
<div className="flex flex-wrap items-start gap-3">
<ul className="grid grid-cols-2 gap-x-6 gap-y-1 rounded-md bg-muted px-3 py-2 font-mono text-xs">
{codes.map((c) => (
<li key={c}>{c}</li>
))}
</ul>
<CopyButton text={codes.join("\n")} />
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ReportForm } from "@/components/cases";
import { membership as membershipLabel } from "@/components/catalogs";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { api, getMe, unwrap } from "@/lib/api";
import { membership } from "../../console/catalogs/actions";
export const metadata: Metadata = { title: "Catalog" };
export default async function CatalogPage({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ invite?: string | string[] }>;
}) {
const { id } = await params;
const raw = (await searchParams).invite;
const invite = typeof raw === "string" && /^[a-z0-9]{1,32}$/.test(raw) ? raw : "";
const [me, answer] = await Promise.all([getMe(), api.catalogs({ id }).get()]);
if (answer.error) notFound();
const data = unwrap(answer);
const c = data.catalog;
const manage = data.permissions.includes("audit:read");
return (
<div className="space-y-6">
<PageHeader title={c.name}>
<span className="flex flex-wrap items-center gap-2">
<span>{membershipLabel[c.membership] ?? c.membership}</span>
{c.maxRating === "general" && <Tag>General audiences</Tag>}
{data.membership === "member" && <Tag tone="strong">Member</Tag>}
{data.membership === "requested" && <Tag>Asked to join</Tag>}
{data.membership === "banned" && <Tag tone="danger">Banned</Tag>}
</span>
</PageHeader>
<div className="grid gap-4 sm:grid-cols-2">
<Card>
<CardHeader>
<CardDescription>Products</CardDescription>
<CardTitle className="text-3xl font-semibold tabular-nums">{data.hosted.products}</CardTitle>
</CardHeader>
</Card>
<Card>
<CardHeader>
<CardDescription>Takedown Contact</CardDescription>
<CardTitle className="text-base font-normal break-all">{c.contact}</CardTitle>
</CardHeader>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Membership</CardTitle>
<CardDescription>
{c.membership === "open"
? "Anyone on T5DE can get its products."
: c.membership === "approval"
? "Ask to join; its team decides. Anyone can see its products on others."
: "Join with an invitation. Anyone can see its products on others."}
</CardDescription>
</CardHeader>
<CardContent>
{!me ? (
<Link href={`/signin?next=${encodeURIComponent(`/catalogs/${id}${invite ? `?invite=${invite}` : ""}`)}`} className={buttonVariants()}>
Sign in to join
</Link>
) : data.membership === "banned" ? (
<p className="text-sm text-muted-foreground">This catalog&apos;s team banned you from it.</p>
) : data.membership === "member" || data.membership === "requested" ? (
<ActionForm action={membership} fields={{ id, intent: "leave" }}>
<SubmitButton variant="outline" pendingLabel="Leaving…" confirm={data.membership === "member" ? `Leave ${c.name}?` : undefined}>
{data.membership === "member" ? "Leave" : "Withdraw request"}
</SubmitButton>
</ActionForm>
) : c.membership === "open" ? (
<p className="text-sm text-muted-foreground">Nothing to join: get its products from their pages.</p>
) : c.membership === "invite" && !invite ? (
<p className="text-sm text-muted-foreground">You need an invitation link from its team.</p>
) : (
<ActionForm action={membership} fields={{ id, intent: "join", invite }}>
<SubmitButton pendingLabel="Joining…">{invite ? "Accept invitation" : "Ask to join"}</SubmitButton>
</ActionForm>
)}
</CardContent>
</Card>
{manage && (
<Link href={`/console/catalogs/${id}`} className={buttonVariants({ variant: "outline" })}>
Manage
</Link>
)}
{me && !manage && <ReportForm about="catalog" id={id} />}
</div>
);
}
+6 -1
View File
@@ -1,4 +1,5 @@
import type { Metadata } from "next";
import Link from "next/link";
import { CatalogStatus, membership } from "@/components/catalogs";
import { PageHeader } from "@/components/status";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@@ -71,7 +72,11 @@ function CatalogTable({ catalogs, showStatus = false }: { catalogs: Catalog[]; s
<TableBody>
{catalogs.map((c) => (
<TableRow key={c.id}>
<TableCell className="font-medium">{c.name}</TableCell>
<TableCell className="font-medium">
<Link href={showStatus ? `/console/catalogs/${c.id}` : `/catalogs/${c.id}`} className="underline-offset-4 hover:underline">
{c.name}
</Link>
</TableCell>
<TableCell className="font-mono text-xs text-muted-foreground">{c.url}</TableCell>
<TableCell>{membership[c.membership] ?? c.membership}</TableCell>
{showStatus && <TableCell className="capitalize">{c.visibility}</TableCell>}
+45
View File
@@ -0,0 +1,45 @@
"use client";
// Allow or deny a site's request. The provider's client plugin sends the page's signed request (oauth_query) along,
// and answers with where to go next: back to the site, with a code or with access_denied.
import { oauthProviderClient } from "@better-auth/oauth-provider/client";
import { createAuthClient } from "better-auth/react";
import { useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
const consentClient = createAuthClient({
baseURL: typeof window === "undefined" ? undefined : window.location.origin,
plugins: [oauthProviderClient()],
});
export function ConsentForm() {
const [pending, setPending] = useState<"allow" | "deny" | null>(null);
const [error, setError] = useState("");
async function answer(accept: boolean) {
setPending(accept ? "allow" : "deny");
setError("");
const { data, error } = await consentClient.oauth2.consent({ accept });
const url = data && typeof data === "object" && "url" in data ? (data as { url?: string }).url : undefined;
if (error || !url) {
setError(error?.message ?? "That didn't work. Start again from the site.");
setPending(null);
return;
}
window.location.assign(url);
}
return (
<div className="space-y-3">
<div className="flex gap-2">
<Button type="button" disabled={pending !== null} onClick={() => void answer(true)}>
{pending === "allow" ? "Allowing…" : "Allow"}
</Button>
<Button type="button" variant="outline" disabled={pending !== null} onClick={() => void answer(false)}>
{pending === "deny" ? "Denying…" : "Deny"}
</Button>
</div>
{error && <ErrorText>{error}</ErrorText>}
</div>
);
}
+42
View File
@@ -0,0 +1,42 @@
// Another site asks to sign the person in with their T5DE account. T5DE's own sites (Music) are trusted and never get
// here; this is for sites added later (docs/music.md, The OIDC provider).
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { NarrowCard } from "@/components/narrow-card";
import { api, getMe } from "@/lib/api";
import { ConsentForm } from "./consent-form";
export const metadata: Metadata = { title: "Allow Access" };
/** What each scope lets a site see or do, in words. */
const scopeText: Record<string, string> = {
openid: "Know it's you",
profile: "Your name and username",
email: "Your email address",
offline_access: "Stay signed in when you're away",
imvu: "Your linked IMVU accounts",
"imvu:link": "Link and unlink IMVU accounts for you",
};
export default async function Consent({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const params = await searchParams;
const me = await getMe();
if (!me) redirect("/signin");
const clientId = typeof params.client_id === "string" ? params.client_id : "";
const site = clientId ? (await api.oauth.clients({ clientId }).get()).data : undefined;
const name = site && "client" in site ? site.client.name : undefined;
if (!name) return <NarrowCard title="Allow Access" description="This request isn't valid any more. Start again from the site." />;
const scopes = (typeof params.scope === "string" ? params.scope : "").split(" ").filter((s) => s in scopeText);
return (
<NarrowCard title="Allow Access" description={`${name} wants to use your T5DE account, ${me.username}.`}>
<div className="space-y-4">
<ul className="list-disc space-y-1 pl-5 text-sm">
{scopes.map((s) => (
<li key={s}>{scopeText[s]}</li>
))}
</ul>
<ConsentForm />
</div>
</NarrowCard>
);
}
+23
View File
@@ -1,5 +1,6 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { api, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
@@ -52,3 +53,25 @@ export async function decideCatalog(_: ActionState, form: FormData): Promise<Act
revalidatePath("/catalogs");
});
}
/** An account waiting for approval: approve it, or decline it (deleting it). */
export async function decideAccount(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
const decline = field(form, "decision") === "decline";
const state = await attempt(async () => {
if (decline) unwrap(await api.console.people({ id }).decline.post());
else unwrap(await api.console.people({ id }).approve.post());
revalidatePath("/console", "layout");
});
if (decline && !state?.error) redirect("/console/people?waiting=true");
return state;
}
export async function setRegistration(_: ActionState, form: FormData): Promise<ActionState> {
return attempt(async () => {
const registration = field(form, "registration") === "closed" ? "closed" : "open";
unwrap(await api.console.settings.put({ registration }));
revalidatePath("/console");
return registration === "closed" ? "Registration closed: new accounts wait for approval." : "Registration open.";
});
}
+105
View File
@@ -0,0 +1,105 @@
import Link from "next/link";
import { ActionForm, SubmitButton } from "@/components/forms";
import { DateTime } from "@/components/time";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import type { AuditEntry } from "@/lib/api";
import { appeal } from "./cases/actions";
const tagLinks: Record<string, (id: string) => string> = {
catalog: (id) => `/console/catalogs/${id}`,
product: (id) => `/products/${id}`,
room: (id) => `/rooms/${id}/edit`,
};
/** Audit entries: when, who, what, which resources (linked), and the details. */
export function AuditTable({ entries, empty = "Nothing yet." }: { entries: AuditEntry[]; empty?: string }) {
if (entries.length === 0) return <p className="text-sm text-muted-foreground">{empty}</p>;
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>When</TableHead>
<TableHead>Who</TableHead>
<TableHead>What</TableHead>
<TableHead>About</TableHead>
<TableHead>Detail</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{entries.map((e) => (
<TableRow key={e.id}>
<TableCell className="text-muted-foreground">
<DateTime iso={e.at} />
</TableCell>
<TableCell>
{e.actor ? (
<Link href={`/console/audit?actor=${encodeURIComponent(e.actor)}`} className="underline-offset-4 hover:underline">
{e.actor}
</Link>
) : (
<span className="text-muted-foreground">hub</span>
)}
</TableCell>
<TableCell className="font-mono text-xs">{e.action}</TableCell>
<TableCell className="space-x-2 text-sm">
{Object.entries(e.tags as Record<string, string | undefined>).map(([kind, id]) => {
if (!id) return null;
const name = (e.tagNames as Record<string, string>)[id] ?? id;
const href = tagLinks[kind]?.(id);
return (
<span key={kind}>
<span className="text-muted-foreground">{kind} </span>
{href ? (
<Link href={href} className="underline-offset-4 hover:underline">
{name}
</Link>
) : (
name
)}
</span>
);
})}
{Object.keys(e.tags).length === 0 &&
(e.action.startsWith("file.") && /^[0-9a-f]{64}$/.test(e.target) ? (
<Link href={`/console/blocks/${e.target}`} className="font-mono text-xs underline-offset-4 hover:underline">
file {e.target.slice(0, 12)}…
</Link>
) : (
e.target
))}
</TableCell>
<TableCell className="text-xs whitespace-normal text-muted-foreground">
{detailText(e.detail)}
{e.appealable && (
<details className="mt-1">
<summary className="cursor-pointer text-foreground underline-offset-4 hover:underline">Appeal</summary>
<ActionForm action={appeal} fields={{ audit: e.id }} className="mt-2">
<div className="flex gap-2">
<Input name="reason" required maxLength={2000} placeholder="Why it should be undone" aria-label="Why" className="h-8 min-w-48" />
<SubmitButton size="sm" variant="outline" pendingLabel="Sending…">
Send
</SubmitButton>
</div>
</ActionForm>
</details>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
);
}
function detailText(detail: unknown): string {
return Object.entries((detail ?? {}) as Record<string, unknown>)
.map(([k, v]) => {
if (k === "changed" && v && typeof v === "object")
return Object.entries(v as Record<string, { from: unknown; to: unknown }>)
.map(([f, c]) => `${f}: ${String(c?.from)} → ${String(c?.to)}`)
.join(", ");
return `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`;
})
.join(", ");
}
+67
View File
@@ -0,0 +1,67 @@
import type { Metadata } from "next";
import Link from "next/link";
import { PageHeader } from "@/components/status";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { api, unwrap } from "@/lib/api";
import { AuditTable } from "../audit-table";
import { ConsoleNav, requireConsole } from "../console-nav";
export const metadata: Metadata = { title: "Audit Log" };
const filters = ["action", "actor", "person", "catalog", "product", "room", "q", "from", "to"] as const;
type Filters = Partial<Record<(typeof filters)[number], string>>;
export default async function AuditPage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
const { console: data } = await requireConsole("/console/audit");
const params = await searchParams;
const f: Filters = {};
for (const k of filters) {
const v = params[k];
if (typeof v === "string" && v.trim()) f[k] = v.trim().slice(0, 100);
}
const before = typeof params.before === "string" && /^\d+$/.test(params.before) ? Number(params.before) : undefined;
const { entries, before: next } = unwrap(await api.console.audit.get({ query: { ...f, ...(before ? { before } : {}), limit: 100 } }));
const older = new URLSearchParams({ ...f, ...(next ? { before: String(next) } : {}) });
const moderator = data.moderation !== null;
return (
<>
<PageHeader title="Audit Log">
{moderator ? "Every change on the hub." : "Changes to what you manage, and the ones you made."}
</PageHeader>
<ConsoleNav />
<form action="/console/audit" className="mb-6 grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<Input name="q" defaultValue={f.q} placeholder="Search" aria-label="Search" />
<Input name="action" defaultValue={f.action} placeholder="Action, e.g. catalog." aria-label="Action" />
<Input name="actor" defaultValue={f.actor} placeholder="Done by (username)" aria-label="Done by" />
{moderator && <Input name="person" defaultValue={f.person} placeholder="About or by a person" aria-label="Person" />}
<Input name="catalog" defaultValue={f.catalog} placeholder="Catalog ID" aria-label="Catalog" />
<Input name="product" defaultValue={f.product} placeholder="Product ID" aria-label="Product" />
<Input type="date" name="from" defaultValue={f.from} aria-label="From" />
<Input type="date" name="to" defaultValue={f.to} aria-label="To" />
<div className="flex gap-2">
<Button type="submit">Filter</Button>
{Object.keys(f).length > 0 && (
<Link href="/console/audit" className={buttonVariants({ variant: "outline" })}>
Clear
</Link>
)}
</div>
</form>
<Card>
<CardContent>
<AuditTable entries={entries} empty={Object.keys(f).length ? "Nothing matches." : "Nothing yet."} />
</CardContent>
</Card>
{next && entries.length === 100 && (
<div className="mt-4">
<Link href={`/console/audit?${older}`} className={buttonVariants({ variant: "outline" })}>
Older
</Link>
</div>
)}
</>
);
}
@@ -0,0 +1,106 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { api, unwrap } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../../console-nav";
import { blockFile, unblockFile } from "../actions";
export const metadata: Metadata = { title: "Block" };
/** A file: whether it's blocked, the products using it, and blocking or unblocking it. */
export default async function BlockPage({ params }: { params: Promise<{ sha256: string }> }) {
const { sha256 } = await params;
if (!/^[0-9a-f]{64}$/.test(sha256)) notFound();
const { console: c } = await requireConsole(`/console/blocks/${sha256}`);
if (!c.sections.includes("blocks")) notFound();
const { block, products } = unwrap(await api.blocks({ sha256 }).get());
const live = products.filter((p) => !p.removed);
const removeCount = live.length === 1 ? "1 product" : `${live.length} products`;
return (
<>
<PageHeader title="File">
<span className="font-mono text-xs break-all">{sha256}</span>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>{block ? "Blocked" : "Not Blocked"}</CardTitle>
<CardDescription>
{block ? (
<>
By {block.by ?? "a former moderator"}, <DateTime iso={block.at} />: {block.reason}
</>
) : (
"Blocking it removes the products below, tells their catalogs to delete it, and refuses uploads with it."
)}
</CardDescription>
</CardHeader>
<CardContent>
{block ? (
<ActionForm action={unblockFile} fields={{ sha256 }}>
<div className="flex flex-wrap gap-2">
<Input name="reason" maxLength={500} placeholder="Reason" aria-label="Reason" className="max-w-sm" />
<SubmitButton
variant="outline"
pendingLabel="Unblocking…"
confirm="Unblock this file? The products it removed stay removed until restored."
>
Unblock
</SubmitButton>
</div>
</ActionForm>
) : (
<ActionForm action={blockFile} fields={{ sha256 }}>
<div className="flex flex-wrap gap-2">
<Input name="reason" required maxLength={500} placeholder="Reason (creators see it)" aria-label="Reason" className="max-w-sm" />
<SubmitButton
variant="destructive"
pendingLabel="Blocking…"
confirm={live.length ? `Block this file and remove ${removeCount}?` : "Block this file?"}
>
{live.length ? `Block and remove ${removeCount}` : "Block"}
</SubmitButton>
</div>
</ActionForm>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Used By</CardTitle>
<CardDescription>Products with a revision that has this file.</CardDescription>
</CardHeader>
<CardContent>
{products.length === 0 ? (
<p className="text-sm text-muted-foreground">No product uses it.</p>
) : (
<ul className="divide-y">
{products.map((p) => (
<li key={p.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 py-3 first:pt-0 last:pb-0">
<Link
href={p.removed ? `/console/products?q=${encodeURIComponent(p.name)}&status=removed&all=1` : `/products/${p.id}`}
className="font-medium underline-offset-4 hover:underline"
>
{p.name}
</Link>
<span className="text-sm text-muted-foreground">
by {p.creatorUsername ?? "someone"} · {p.revisions.length === 1 ? "revision" : "revisions"} {p.revisions.join(", ")}
</span>
{p.removed && <Tag tone="danger">removed</Tag>}
</li>
))}
</ul>
)}
</CardContent>
</Card>
</div>
</>
);
}
+31
View File
@@ -0,0 +1,31 @@
"use server";
// File blocks, from the console.
import { revalidatePath } from "next/cache";
import { api, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
const done = (sha256: string) => {
revalidatePath("/console/blocks");
revalidatePath(`/console/blocks/${sha256}`);
revalidatePath("/console/products");
};
/** Blocks a file network-wide, removing the products using it. */
export async function blockFile(_: ActionState, form: FormData): Promise<ActionState> {
const sha256 = field(form, "sha256");
return attempt(async () => {
const { removed } = unwrap(await api.blocks({ sha256 }).put({ reason: field(form, "reason") }));
done(sha256);
return removed.length ? `Blocked. Removed ${removed.length === 1 ? "1 product" : `${removed.length} products`}.` : "Blocked.";
});
}
/** Unblocks a file. The products it removed stay removed. */
export async function unblockFile(_: ActionState, form: FormData): Promise<ActionState> {
const sha256 = field(form, "sha256");
return attempt(async () => {
unwrap(await api.blocks({ sha256 }).delete({ reason: field(form, "reason") }));
done(sha256);
return "Unblocked.";
});
}
+88
View File
@@ -0,0 +1,88 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { PageHeader } from "@/components/status";
import { DateTime } from "@/components/time";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../console-nav";
export const metadata: Metadata = { title: "Blocks" };
export default async function BlocksPage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
const { console: c } = await requireConsole("/console/blocks");
if (!c.sections.includes("blocks")) notFound();
const params = await searchParams;
// Looking a file up goes to its page.
if (typeof params.sha256 === "string") {
const sha256 = params.sha256.trim().toLowerCase();
if (/^[0-9a-f]{64}$/.test(sha256)) redirect(`/console/blocks/${sha256}`);
}
const before = typeof params.before === "string" && !Number.isNaN(Date.parse(params.before)) ? params.before : undefined;
const data = unwrap(await api.blocks.get({ query: before ? { before } : {} }));
return (
<>
<PageHeader title="Blocks">Blocked files: uploads with them are refused, and catalogs delete them.</PageHeader>
<ConsoleNav />
<form action="/console/blocks" className="mb-6 flex flex-wrap gap-2">
<Input
name="sha256"
required
pattern="\s*[0-9a-fA-F]{64}\s*"
defaultValue={typeof params.sha256 === "string" ? params.sha256 : ""}
placeholder="A file's sha256"
aria-label="sha256"
className="max-w-xl font-mono"
/>
<Button type="submit">Look up</Button>
</form>
<Card>
<CardContent>
{data.blocks.length === 0 ? (
<p className="text-sm text-muted-foreground">
Nothing blocked. Block a file from a product&apos;s files, or look it up above.
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>File</TableHead>
<TableHead>Reason</TableHead>
<TableHead>By</TableHead>
<TableHead>When</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.blocks.map((b) => (
<TableRow key={b.sha256}>
<TableCell className="font-mono text-xs">
<Link href={`/console/blocks/${b.sha256}`} className="underline-offset-4 hover:underline">
{b.sha256.slice(0, 16)}…
</Link>
</TableCell>
<TableCell className="whitespace-normal">{b.reason}</TableCell>
<TableCell className="text-muted-foreground">{b.by ?? ""}</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={b.at} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
{data.before && (
<div className="mt-4">
<Link href={`/console/blocks?before=${encodeURIComponent(data.before)}`} className={buttonVariants({ variant: "outline" })}>
Older
</Link>
</div>
)}
</>
);
}
+191
View File
@@ -0,0 +1,191 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { CaseAbout, caseKinds, CaseStatus, resolveLabel } from "@/components/cases";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { api, unwrap } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../../console-nav";
import { addNote, assign, decide } from "../actions";
export const metadata: Metadata = { title: "Case" };
/** What each kind of case asks. */
const asks: Record<string, string> = {
report: "Someone reported this.",
"rating-review": "Its creator asks to lower its rating from adult to general.",
"removal-request": "A catalog hosting it asks for it to be removed everywhere.",
"catalog-deletion": "Its owner asks for it to be deleted.",
appeal: "The person it affected asks for this action to be undone.",
};
export default async function CasePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
if (!/^\d{1,9}$/.test(id)) notFound();
const { me } = await requireConsole(`/console/cases/${id}`);
const answer = await api.cases({ id: Number(id) }).get();
if (answer.error) notFound();
const { case: c, notes, canDecide, canAssign } = unwrap(answer);
const appealed = c.kind === "appeal" ? (c.data as { action?: string; detail?: Record<string, unknown> }) : undefined;
return (
<>
<PageHeader title={`${caseKinds[c.kind] ?? c.kind} #${c.id}`}>
<span className="flex flex-wrap items-center gap-2">
<CaseStatus status={c.status} />
<span>
opened by {c.openedBy || "someone"} <DateTime iso={c.createdAt} />
</span>
{c.assignee && <Tag>assigned to {c.assignee}</Tag>}
</span>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>About</CardTitle>
<CardDescription>{asks[c.kind]}</CardDescription>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<p>
<CaseAbout tags={c.tags} names={c.tagNames} />
</p>
{appealed && (
<p>
<span className="text-muted-foreground">Action appealed: </span>
<span className="font-mono text-xs">{appealed.action}</span>
{appealed.detail && Object.keys(appealed.detail).length > 0 && (
<span className="text-muted-foreground">
{" "}
({Object.entries(appealed.detail)
.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
.join(", ")}
)
</span>
)}
</p>
)}
{c.reason && <p className="whitespace-pre-line">{c.reason}</p>}
{c.status !== "open" && (
<div className="rounded-lg border p-3">
<p className="font-medium">
{c.status === "resolved" ? "Resolved" : "Declined"} by {c.decidedBy || "a moderator"}{" "}
{c.decidedAt && (
<span className="font-normal text-muted-foreground">
<DateTime iso={c.decidedAt} />
</span>
)}
</p>
{c.resolution && <p className="mt-1 whitespace-pre-line">{c.resolution}</p>}
</div>
)}
</CardContent>
</Card>
{canDecide && (
<Card>
<CardHeader>
<CardTitle>Decide</CardTitle>
<CardDescription>
{c.kind === "report" || c.kind === "appeal"
? "Resolving records the decision; take any action where it's done (removed products are restored from Console › Products, edits undone from the product's history)."
: `Resolving does it: ${resolveLabel[c.kind]?.toLowerCase()}.`}{" "}
{c.openedBy ? `${c.openedBy} is told, with what you write.` : ""}
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={decide} fields={{ case: c.id }}>
<Textarea name="resolution" maxLength={2000} rows={3} placeholder="What you decided, and why" aria-label="Resolution" />
<div className="flex flex-wrap gap-2">
<SubmitButton
name="decision"
value="resolve"
pendingLabel="Saving…"
confirm={c.kind === "catalog-deletion" || c.kind === "removal-request" ? `${resolveLabel[c.kind]}?` : undefined}
>
{resolveLabel[c.kind] ?? "Resolve"}
</SubmitButton>
<SubmitButton name="decision" value="decline" variant="outline" pendingLabel="Saving…">
Decline
</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
{canAssign && c.status === "open" && (
<Card>
<CardHeader>
<CardTitle>Assignment</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap gap-2">
<ActionForm action={assign} fields={{ case: c.id }} className="flex flex-wrap gap-2 space-y-0">
<Input name="to" defaultValue={c.assignee ?? me.username} maxLength={64} aria-label="Moderator" className="max-w-48" />
<SubmitButton variant="outline" pendingLabel="Saving…">
Assign
</SubmitButton>
</ActionForm>
{c.assignee && (
<ActionForm action={assign} fields={{ case: c.id, to: "" }}>
<SubmitButton variant="ghost" pendingLabel="Saving…">
Unassign
</SubmitButton>
</ActionForm>
)}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Thread</CardTitle>
{canDecide && <CardDescription>Internal notes are only for those deciding.</CardDescription>}
</CardHeader>
<CardContent className="space-y-4">
{notes.length === 0 ? (
<p className="text-sm text-muted-foreground">No notes yet.</p>
) : (
<ul className="divide-y">
{notes.map((n) => (
<li key={n.id} className="space-y-1 py-3 first:pt-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{n.by || "Someone"}</span>
{n.internal && <Tag>Internal</Tag>}
<span className="text-muted-foreground">
<DateTime iso={n.at} />
</span>
</div>
<p className="text-sm whitespace-pre-line">{n.body}</p>
</li>
))}
</ul>
)}
<ActionForm action={addNote} fields={{ case: c.id }}>
<Textarea name="body" required maxLength={4000} rows={3} placeholder="Write a note" aria-label="Note" />
<div className="flex flex-wrap items-center gap-4">
<SubmitButton variant="outline" pendingLabel="Sending…">
Add note
</SubmitButton>
{canDecide && (
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="internal" className="size-4 accent-foreground" />
Internal
</label>
)}
</div>
</ActionForm>
</CardContent>
</Card>
<Link href="/console/cases" className="text-sm underline-offset-4 hover:underline">
All cases
</Link>
</div>
</>
);
}
+98
View File
@@ -0,0 +1,98 @@
"use server";
// Cases (reports, reviews, requests, appeals) and notifications, from the website.
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { api, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
/** Reports a product, catalog, room or person. */
export async function report(_: ActionState, form: FormData): Promise<ActionState> {
const kind = field(form, "about");
const id = field(form, "id");
if (!["product", "catalog", "room", "person"].includes(kind)) return { error: "Nothing to report." };
return attempt(async () => {
unwrap(await api.cases.post({ kind: "report", about: { [kind]: id }, reason: field(form, "reason") }));
revalidatePath("/console/cases");
return "Reported. Moderators will look at it; you'll be told what they decide.";
});
}
/** Appeals an action from the audit log. */
export async function appeal(_: ActionState, form: FormData): Promise<ActionState> {
let id = 0;
const state = await attempt(async () => {
const { case: c } = unwrap(await api.cases.post({ kind: "appeal", audit: Number(field(form, "audit")), reason: field(form, "reason") }));
id = c.id;
});
if (state?.error) return state;
redirect(`/console/cases/${id}`);
}
/** A catalog's team asks moderators to remove a product everywhere. */
export async function requestRemoval(_: ActionState, form: FormData): Promise<ActionState> {
return attempt(async () => {
unwrap(
await api.cases.post({
kind: "removal-request",
about: { product: field(form, "product") },
catalog: field(form, "catalog"),
reason: field(form, "reason"),
}),
);
revalidatePath("/console/cases");
return "Asked. Moderators will decide.";
});
}
/** A catalog's owner asks for it to be deleted. */
export async function requestDeletion(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
let kase = 0;
const state = await attempt(async () => {
kase = unwrap(await api.catalogs({ id }).delete.post({ reason: field(form, "reason") })).case;
});
if (state?.error) return state;
redirect(`/console/cases/${kase}`);
}
const onCase = (form: FormData) => {
const id = Number(field(form, "case"));
return { id, done: () => revalidatePath(`/console/cases/${id}`) };
};
export async function addNote(_: ActionState, form: FormData): Promise<ActionState> {
const { id, done } = onCase(form);
return attempt(async () => {
unwrap(await api.cases({ id }).notes.post({ body: field(form, "body"), internal: form.get("internal") === "on" }));
done();
});
}
export async function assign(_: ActionState, form: FormData): Promise<ActionState> {
const { id, done } = onCase(form);
return attempt(async () => {
const to = field(form, "to");
unwrap(await api.cases({ id }).assign.post({ to: to || null }));
done();
});
}
export async function decide(_: ActionState, form: FormData): Promise<ActionState> {
const { id, done } = onCase(form);
const decision = field(form, "decision");
if (decision !== "resolve" && decision !== "decline") return { error: "Choose to resolve or decline it." };
return attempt(async () => {
unwrap(await api.cases({ id }).decide.post({ decision, resolution: field(form, "resolution") }));
done();
revalidatePath("/console/cases");
revalidatePath("/console");
});
}
export async function markAllRead(_: ActionState): Promise<ActionState> {
return attempt(async () => {
unwrap(await api.notifications.read.post({}));
revalidatePath("/notifications");
revalidatePath("/", "layout");
});
}
+122
View File
@@ -0,0 +1,122 @@
import type { Metadata } from "next";
import Link from "next/link";
import { CaseAbout, caseKinds, CaseStatus } from "@/components/cases";
import { PageHeader } from "@/components/status";
import { DateTime } from "@/components/time";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../console-nav";
export const metadata: Metadata = { title: "Cases" };
const statuses = ["open", "resolved", "declined"] as const;
const kinds = ["report", "rating-review", "removal-request", "catalog-deletion", "appeal"] as const;
export default async function CasesPage({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
await requireConsole("/console/cases");
const params = await searchParams;
// Open cases unless asked otherwise ("any" for all).
const status = params.status === "any" ? undefined : (statuses.find((s) => s === params.status) ?? "open");
const kind = kinds.find((k) => k === params.kind);
const mine = params.mine === "1";
const before = typeof params.before === "string" && /^\d+$/.test(params.before) ? Number(params.before) : undefined;
const data = unwrap(
await api.cases.get({
query: {
...(status ? { status } : {}),
...(kind ? { kind } : {}),
...(mine ? { mine: "1" as const } : {}),
...(before ? { before } : {}),
limit: 50,
},
}),
);
const older = new URLSearchParams({
status: status ?? "any",
...(kind ? { kind } : {}),
...(mine ? { mine: "1" } : {}),
...(data.before ? { before: String(data.before) } : {}),
});
return (
<>
<PageHeader title="Cases">
{data.moderator ? "Reports, reviews, requests and appeals." : "Cases you opened, and those about what you manage."}
</PageHeader>
<ConsoleNav />
<form action="/console/cases" className="mb-6 flex flex-wrap gap-2">
<NativeSelect name="status" defaultValue={status ?? "any"} aria-label="Status" className="w-36">
<NativeSelectOption value="open">Open</NativeSelectOption>
<NativeSelectOption value="resolved">Resolved</NativeSelectOption>
<NativeSelectOption value="declined">Declined</NativeSelectOption>
<NativeSelectOption value="any">Any status</NativeSelectOption>
</NativeSelect>
<NativeSelect name="kind" defaultValue={kind ?? ""} aria-label="Kind" className="w-44">
<NativeSelectOption value="">Any kind</NativeSelectOption>
{kinds.map((k) => (
<NativeSelectOption key={k} value={k}>
{caseKinds[k]}
</NativeSelectOption>
))}
</NativeSelect>
<NativeSelect name="mine" defaultValue={mine ? "1" : ""} aria-label="Whose" className="w-44">
<NativeSelectOption value="">{data.moderator ? "Everyone's" : "All I can see"}</NativeSelectOption>
<NativeSelectOption value="1">Opened by me</NativeSelectOption>
</NativeSelect>
<Button type="submit">Filter</Button>
</form>
<Card>
<CardContent>
{data.cases.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing here.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Case</TableHead>
<TableHead>About</TableHead>
<TableHead>Opened by</TableHead>
<TableHead>Assigned</TableHead>
<TableHead>Status</TableHead>
<TableHead>Changed</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.cases.map((c) => (
<TableRow key={c.id}>
<TableCell className="font-medium">
<Link href={`/console/cases/${c.id}`} className="underline-offset-4 hover:underline">
{caseKinds[c.kind] ?? c.kind} #{c.id}
</Link>
</TableCell>
<TableCell className="text-sm">
<CaseAbout tags={c.tags} names={c.tagNames} />
</TableCell>
<TableCell className="text-muted-foreground">{c.openedBy || "someone"}</TableCell>
<TableCell className="text-muted-foreground">{c.assignee ?? ""}</TableCell>
<TableCell>
<CaseStatus status={c.status} />
</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={c.updatedAt} />
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
{data.before && data.cases.length === 50 && (
<div className="mt-4">
<Link href={`/console/cases?${older}`} className={buttonVariants({ variant: "outline" })}>
Older
</Link>
</div>
)}
</>
);
}
@@ -0,0 +1,186 @@
"use client";
// Adds an IMVU account to the catalog's importer, or gives one a new password (docs/imports.md "IMVU accounts").
// The account is looked up and shown for confirmation first; then the password is sealed here, in the browser, for
// the importer's public key, so the hub only ever has the sealed copy.
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { Tag } from "@/components/status";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { shortFingerprint } from "@/lib/importer";
import { lookupImporterAccount, saveImporterAccount, type ImvuAccountInfo } from "../../actions";
/** Seals {imvuId, password} for the importer's key: RSA-OAEP with SHA-256, base64. */
async function seal(publicKey: string, imvuId: number, password: string): Promise<string> {
if (!globalThis.crypto?.subtle) throw new Error("This browser can't encrypt here (the page needs HTTPS).");
const spki = Uint8Array.from(atob(publicKey), (c) => c.charCodeAt(0));
const key = await crypto.subtle.importKey("spki", spki, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["encrypt"]);
const data = new TextEncoder().encode(JSON.stringify({ imvuId, password }));
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "RSA-OAEP" }, key, data));
let s = "";
for (const b of sealed) s += String.fromCharCode(b);
return btoa(s);
}
export function ImporterAccountForm({
catalogId,
publicKey,
fingerprint,
version,
account,
}: {
catalogId: string;
publicKey: string;
fingerprint: string;
version: string;
/** Set to give an existing account a new password. */
account?: { id: string; imvuId: number; username: string };
}) {
const router = useRouter();
const [username, setUsername] = useState(account?.username ?? "");
const [password, setPassword] = useState("");
const [found, setFound] = useState<ImvuAccountInfo | null>(null);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
const [pending, start] = useTransition();
const [saving, setSaving] = useState(false); // the confirm step, not the lookup
const check = (e: React.FormEvent) => {
e.preventDefault();
setError("");
setNotice("");
if (!username.trim() || !password) return setError("Give the account's username and password.");
if (password.length > 128) return setError("That password is too long.");
start(async () => {
const r = await lookupImporterAccount(catalogId, username);
if ("error" in r) return setError(r.error);
if (account && r.ok.imvuId !== account.imvuId)
return setError(
`${account.username} is another IMVU account now (ID ${r.ok.imvuId}). Remove it and add that one.`,
);
setFound(r.ok);
});
};
const confirm = () => {
if (!found) return;
setSaving(true);
start(async () => {
try {
await save(found);
} finally {
setSaving(false);
}
});
};
const save = async (found: ImvuAccountInfo) => {
let sealed: string;
try {
sealed = await seal(publicKey, found.imvuId, password);
} catch (e) {
setFound(null);
return setError(e instanceof Error ? e.message : "The password couldn't be encrypted.");
}
const r = await saveImporterAccount(catalogId, { imvuId: found.imvuId, account: account?.id, sealed, fingerprint });
setFound(null);
if ("error" in r) return setError(r.error);
setPassword("");
if (!account) setUsername("");
setNotice(
account
? "Saved. The importer picks the new password up within a minute."
: `${found.username} added. The importer picks it up within a minute.`,
);
router.refresh();
};
return (
<>
<form onSubmit={check} className="flex max-w-2xl flex-wrap items-center gap-2">
{!account && (
<Input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="IMVU username"
aria-label="IMVU username"
autoComplete="off"
maxLength={64}
className="min-w-44 flex-1"
/>
)}
{/* No name: the password is never sent as a form field, only sealed. */}
<Input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={account ? `New password for ${account.username}` : "Password"}
aria-label="Password"
autoComplete="new-password"
className="min-w-44 flex-1"
/>
<Button type="submit" variant={account ? "outline" : "default"} disabled={pending}>
{pending && !saving ? "Checking…" : account ? "Save password" : "Add account"}
</Button>
</form>
{error && <p className="mt-2 text-sm text-red-700 dark:text-red-400">{error}</p>}
{notice && <p className="mt-2 text-sm text-muted-foreground">{notice}</p>}
<Dialog open={found !== null} onOpenChange={(open) => !open && !pending && setFound(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>{account ? "New Password for This Account?" : "Add This Account?"}</DialogTitle>
<DialogDescription>The importer signs in to IMVU with it to import products.</DialogDescription>
</DialogHeader>
{found && (
<div className="flex items-center gap-3 rounded-lg border p-3">
{found.picture ? (
<img src={found.picture} alt="" className="size-14 rounded-md bg-muted object-cover object-top" />
) : (
<span
className="grid size-14 place-items-center rounded-md bg-muted text-lg font-semibold uppercase"
aria-hidden
>
{found.username.slice(0, 1)}
</span>
)}
<div className="min-w-0 space-y-1">
<p className="truncate font-medium">{found.username}</p>
<p className="text-xs text-muted-foreground">IMVU ID {found.imvuId}</p>
<div className="flex flex-wrap gap-1">
{found.accessPass ? <Tag tone="adult">Access Pass</Tag> : <Tag>Access Pass not shown</Tag>}
{found.ageVerified ? <Tag tone="adult">Age verified</Tag> : <Tag>Not age verified</Tag>}
</div>
</div>
</div>
)}
{found && !found.accessPass && (
<p className="text-sm text-amber-700 dark:text-amber-400">
IMVU shows Access Pass publicly only if the member chooses to; the importer checks when it signs in.
Without Access Pass, it can&apos;t import Access Pass products with this account.
</p>
)}
<p className="text-xs text-muted-foreground">
The password is encrypted in this browser for your importer (key {shortFingerprint(fingerprint)}
{version ? `, version ${version}` : ""}) and kept only there. T5DE&apos;s hub never sees it.
</p>
<DialogFooter>
<DialogClose render={<Button variant="outline" disabled={pending} />}>Cancel</DialogClose>
<Button onClick={confirm} disabled={pending}>
{saving ? "Saving…" : account ? "Save password" : "Add account"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,517 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap, type ImportGrant } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../../../console-nav";
import { shortFingerprint } from "@/lib/importer";
import {
changeImporterAccount,
decideGrant,
listShop,
retryJob,
setImporter,
setImporterSettings,
} from "../../actions";
import { ShopListing } from "@/components/shop-listing";
import { ImporterAccountForm } from "./importer-account-form";
export const metadata: Metadata = { title: "Imports" };
const statuses = ["queued", "claimed", "failed", "done"] as const;
const grantTone = {
pending: "strong",
active: "online",
declined: "neutral",
suspended: "danger",
withdrawn: "neutral",
} as const;
const jobTone = {
queued: "neutral",
claimed: "strong",
failed: "danger",
done: "online",
} as const;
const accountState = {
waiting: { tone: "neutral", label: "waiting for the importer" },
received: { tone: "strong", label: "not tried yet" },
ok: { tone: "online", label: "signed in" },
sign_in_failed: { tone: "danger", label: "sign-in failed" },
needs_password: { tone: "danger", label: "needs its password" },
} as const;
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
const imvuShop = (creator: number) => `https://www.imvu.com/shop/web_search.php?manufacturers_id=${creator}`;
export default async function CatalogImports({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ status?: string }>;
}) {
const { id } = await params;
await requireConsole(`/console/catalogs/${id}/imports`);
const wanted = (await searchParams).status;
const status = statuses.find((s) => s === wanted);
const [catalogAnswer, answer] = await Promise.all([
api.catalogs({ id }).get(),
api.catalogs({ id }).importer.get({ query: status ? { status } : {} }),
]);
if (catalogAnswer.error || answer.error) notFound();
const c = unwrap(catalogAnswer).catalog;
const data = unwrap(answer);
const can = data.permissions;
const pending = data.grants.filter((g) => g.status === "pending");
const others = data.grants.filter((g) => g.status !== "pending");
return (
<>
<PageHeader title={`${c.name}: Imports`}>
<Link href={`/console/catalogs/${id}`} className="underline-offset-4 hover:underline">
Back to the catalog
</Link>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Importer{" "}
<Tag tone={data.importer === "on" ? "online" : data.importer === "paused" ? "strong" : "neutral"}>
{data.importer}
</Tag>
</CardTitle>
<CardDescription>
{data.importer === "off"
? "With imports on, creators can bring their IMVU products here, and your importer (t5de-importer, run beside the catalog) imports what they allow."
: `The importer signs in with the catalog's ID (${id}) and its importer key. ${data.counts.queued} queued, ${data.counts.claimed} working, ${data.counts.failed} failed, ${data.counts.done} done.`}
</CardDescription>
{data.importer !== "off" && (
<p className="text-sm text-muted-foreground">
{data.program.seenAt ? (
<>
Importer {data.program.version || "(no version)"}, last heard from{" "}
<DateTime iso={data.program.seenAt} />
{data.program.fingerprint && <>, key {shortFingerprint(data.program.fingerprint)}</>}.
</>
) : (
"The importer hasn't connected yet."
)}
</p>
)}
</CardHeader>
{(can.run || can.pause) && (
<CardContent>
<ActionForm action={setImporter} fields={{ id }}>
<div className="flex flex-wrap gap-2">
{data.importer === "off" ? (
can.run && (
<SubmitButton name="intent" value="on" pendingLabel="Turning on…">
Turn imports on
</SubmitButton>
)
) : (
<>
{can.pause &&
(data.importer === "paused" ? (
<SubmitButton name="intent" value="resume" pendingLabel="Resuming…">
Resume
</SubmitButton>
) : (
<SubmitButton name="intent" value="pause" variant="outline" pendingLabel="Pausing…">
Pause
</SubmitButton>
))}
{can.run && (
<SubmitButton
name="intent"
value="key"
variant="outline"
pendingLabel="Making one…"
confirm="The old importer key stops working at once. Go on?"
>
New key
</SubmitButton>
)}
{can.run && (
<SubmitButton
name="intent"
value="off"
variant="outline"
pendingLabel="Turning off…"
confirm="Turn imports off? No new grants, and the importer stops. What's imported stays."
>
Turn off
</SubmitButton>
)}
</>
)}
</div>
</ActionForm>
</CardContent>
)}
</Card>
{data.importer !== "off" && (
<Card>
<CardHeader>
<CardTitle>IMVU Accounts</CardTitle>
<CardDescription>
The importer signs in to IMVU with these, in this order, moving to the next when one fails. Without an
account it imports only what IMVU shows signed out; AP products need one with Access Pass. Passwords are
encrypted in your browser for the importer and kept only by it.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{data.accounts.length > 0 && (
<ol className="divide-y">
{data.accounts.map((a, i) => {
const st = accountState[a.state];
return (
<li key={a.id} className="space-y-2 py-3 first:pt-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="w-5 text-muted-foreground tabular-nums">{i + 1}.</span>
<span className="font-medium">{a.username}</span>
<span className="text-muted-foreground">(IMVU {a.imvuId})</span>
<Tag tone={st.tone}>{st.label}</Tag>
{a.accessPass ? (
<Tag tone="adult">Access Pass</Tag>
) : (
<Tag>{a.state === "ok" ? "No Access Pass" : "Access Pass not checked"}</Tag>
)}
{a.stateMessage && <span className="text-xs text-muted-foreground">{a.stateMessage}</span>}
</div>
{can.run && (
<div className="flex flex-wrap items-start gap-2 pl-7">
<ActionForm action={changeImporterAccount} fields={{ id, account: a.id }}>
<div className="flex gap-2">
{i > 0 && (
<SubmitButton
name="intent"
value="up"
size="sm"
variant="outline"
pendingLabel="Moving…"
>
Up
</SubmitButton>
)}
{i < data.accounts.length - 1 && (
<SubmitButton
name="intent"
value="down"
size="sm"
variant="outline"
pendingLabel="Moving…"
>
Down
</SubmitButton>
)}
<SubmitButton
name="intent"
value="remove"
size="sm"
variant="outline"
pendingLabel="Removing…"
confirm={`Remove ${a.username}? The importer forgets it and its password.`}
>
Remove
</SubmitButton>
</div>
</ActionForm>
{data.program.publicKey && data.program.fingerprint && (
<details
className="min-w-64 flex-1"
open={a.state === "needs_password" || a.state === "sign_in_failed"}
>
<summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground">
New password
</summary>
<div className="mt-2">
<ImporterAccountForm
catalogId={id}
publicKey={data.program.publicKey}
fingerprint={data.program.fingerprint}
version={data.program.version}
account={{ id: a.id, imvuId: a.imvuId, username: a.username }}
/>
</div>
</details>
)}
</div>
)}
</li>
);
})}
</ol>
)}
{can.run &&
(!data.program.publicKey || !data.program.fingerprint ? (
<p className="text-sm text-muted-foreground">
Start the importer to add accounts: passwords are encrypted for its key, which it sends when it
connects.
</p>
) : data.accounts.length >= data.maxAccounts ? (
<p className="text-sm text-muted-foreground">
An importer can have at most {data.maxAccounts} accounts.
</p>
) : (
<ImporterAccountForm
catalogId={id}
publicKey={data.program.publicKey}
fingerprint={data.program.fingerprint}
version={data.program.version}
/>
))}
{!can.run && data.accounts.length === 0 && <p className="text-sm text-muted-foreground">None yet.</p>}
</CardContent>
</Card>
)}
{data.importer !== "off" && (
<Card>
<CardHeader>
<CardTitle>Importer Settings</CardTitle>
<CardDescription>The importer picks changes up within a minute.</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={setImporterSettings} fields={{ id }}>
<div className="flex max-w-2xl flex-wrap items-end gap-4">
<label className="grid gap-1.5 text-sm">
Requests a second to IMVU
<Input
type="number"
name="rate"
step="0.1"
min={data.settingsBounds.rate.min}
max={data.settingsBounds.rate.max}
defaultValue={data.settings.rate}
disabled={!can.run}
className="w-32"
/>
</label>
<label className="grid gap-1.5 text-sm">
Jobs at once
<Input
type="number"
name="concurrency"
step="1"
min={data.settingsBounds.concurrency.min}
max={data.settingsBounds.concurrency.max}
defaultValue={data.settings.concurrency}
disabled={!can.run}
className="w-32"
/>
</label>
{can.run && <SubmitButton pendingLabel="Saving…">Save</SubmitButton>}
</div>
</ActionForm>
</CardContent>
</Card>
)}
{pending.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Waiting for You</CardTitle>
<CardDescription>
Creators asking this catalog to host their IMVU products. Nothing is imported until you accept.
</CardDescription>
</CardHeader>
<CardContent className="divide-y">
{pending.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} />
))}
</CardContent>
</Card>
)}
{others.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Grants</CardTitle>
</CardHeader>
<CardContent className="divide-y">
{others.map((g) => (
<GrantRow key={g.id} id={id} grant={g} accept={can.accept} withdraw={can.withdraw} run={can.run} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Queue</CardTitle>
<CardDescription className="flex flex-wrap gap-3">
{[undefined, ...statuses].map((s) => (
<Link
key={s ?? "all"}
href={`/console/catalogs/${id}/imports${s ? `?status=${s}` : ""}`}
className={s === status ? "font-medium text-foreground" : "underline-offset-4 hover:underline"}
>
{s ?? "all"}
</Link>
))}
</CardDescription>
</CardHeader>
<CardContent>
{data.jobs.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing here.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>IMVU product</TableHead>
<TableHead>Job</TableHead>
<TableHead>Status</TableHead>
<TableHead>Updated</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{data.jobs.map((j) => (
<TableRow key={j.id}>
<TableCell>
{j.kind === "list" ? (
<a
href={imvuShop(j.imvuProduct)}
target="_blank"
rel="noreferrer"
className="underline-offset-4 hover:underline"
>
IMVU shop {j.imvuProduct}
</a>
) : (
<a
href={imvuPage(j.imvuProduct)}
target="_blank"
rel="noreferrer"
className="underline-offset-4 hover:underline"
>
{j.name || j.imvuProduct}
</a>
)}
</TableCell>
<TableCell className="text-muted-foreground">
{j.kind === "list" ? "listing, signed in" : j.kind}
{j.imvuRevision ? ` · revision ${j.imvuRevision}` : ""}
</TableCell>
<TableCell className="whitespace-normal">
<Tag tone={jobTone[j.status]}>{j.status}</Tag>
{j.reason && j.reason !== "unchanged" && (
<span className="ml-2 text-xs text-muted-foreground">
{j.reason}
{j.attempts > 0 && ` (attempt ${j.attempts})`}
</span>
)}
</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={j.updatedAt} />
</TableCell>
<TableCell className="text-right">
{can.run && (j.status === "failed" || j.status === "done") && (
<ActionForm action={retryJob} fields={{ id, job: j.id }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Queuing…">
{j.status === "failed" ? "Retry" : "Again"}
</SubmitButton>
</ActionForm>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
</>
);
}
function GrantRow({
id,
grant: g,
accept,
withdraw,
run = false,
}: {
id: string;
grant: ImportGrant;
accept: boolean;
withdraw: boolean;
run?: boolean;
}) {
const open = g.status === "pending" || g.status === "active" || g.status === "suspended";
return (
<div className="space-y-2 py-4 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || `IMVU account ${g.imvuId}`}</span>
<span className="text-muted-foreground">(IMVU {g.imvuId})</span>
<Tag tone={grantTone[g.status]}>{g.status}</Tag>
{g.consentKind === "recorded" && (
<Tag>{g.consentProven ? "consent recorded by an admin, proven" : "consent recorded by an admin"}</Tag>
)}
<span className="text-xs text-muted-foreground">
<DateTime iso={g.createdAt} dateOnly />
</span>
</div>
<p className="text-sm">
{g.scope === "shop"
? `The whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}: ${g.products.slice(0, 10).join(", ")}${g.products.length > 10 ? "…" : ""}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
<ShopListing grant={g} />
</p>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
{run && g.status === "active" && g.scope === "shop" && (
<ActionForm action={listShop} fields={{ id, grant: g.id }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Listing…">
{g.shopListedAt ? "List the shop again" : "List the shop now"}
</SubmitButton>
</ActionForm>
)}
{open && (accept || withdraw) && (
<ActionForm action={decideGrant} fields={{ id, grant: g.id }}>
<div className="flex max-w-2xl flex-wrap gap-2">
{(g.status === "pending" || withdraw) && (
<Input
name="reason"
maxLength={500}
placeholder={g.status === "pending" ? "Reason (if declining)" : "Reason (if ending)"}
aria-label="Reason"
className="min-w-56 flex-1"
/>
)}
{g.status === "pending" && accept && (
<>
<SubmitButton name="intent" value="accept" pendingLabel="Accepting…">
Accept
</SubmitButton>
<SubmitButton name="intent" value="decline" variant="outline" pendingLabel="Declining…">
Decline
</SubmitButton>
</>
)}
{g.status !== "pending" && withdraw && (
<SubmitButton
name="intent"
value="end"
variant="outline"
pendingLabel="Ending…"
confirm="End this grant? Its imported products are taken away from everyone who has them."
>
End
</SubmitButton>
)}
</div>
</ActionForm>
)}
</div>
);
}
+554
View File
@@ -0,0 +1,554 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { CatalogStatus } from "@/components/catalogs";
import { ActionForm, SubmitButton } from "@/components/forms";
import { formatSize, RatingTag } from "@/components/products";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap, type CatalogMember, type CatalogPage } from "@/lib/api";
import { AuditTable } from "../../audit-table";
import { requestDeletion, requestRemoval } from "../../cases/actions";
import { ConsoleNav, requireConsole } from "../../console-nav";
import {
addOperator,
createInvite,
decideMember,
delist,
removeFromTeam,
revokeInvite,
rotateKey,
saveCatalog,
setSuspended,
} from "../actions";
export const metadata: Metadata = { title: "Catalog" };
type Perm = CatalogPage["permissions"][number];
export default async function ManageCatalog({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const { me } = await requireConsole(`/console/catalogs/${id}`);
const answer = await api.catalogs({ id }).get();
if (answer.error) notFound();
const data = unwrap(answer);
const has = (p: Perm) => data.permissions.includes(p);
if (!has("audit:read")) notFound();
const c = data.catalog;
const [team, members, invites, hosted, audit] = await Promise.all([
api.catalogs({ id }).team.get().then(unwrap),
has("member:approve") ? api.catalogs({ id }).members.get().then(unwrap) : undefined,
has("member:invite") ? api.catalogs({ id }).invites.get().then(unwrap) : undefined,
api.catalogs({ id }).products.get().then(unwrap),
api.console.audit.get({ query: { catalog: id, limit: 20 } }).then(unwrap),
]);
const byStatus = (s: CatalogMember["status"]) => members?.members.filter((m) => m.status === s) ?? [];
const onTeam = team.roles.some((r) => r.personId === me.id);
return (
<>
<PageHeader title={c.name}>
<span className="flex flex-wrap items-center gap-2">
<CatalogStatus status={c.status} />
<span className="font-mono text-xs">{c.url}</span>
{c.status === "approved" && (
<Link href={`/catalogs/${id}`} className="text-sm underline-offset-4 hover:underline">
Public page
</Link>
)}
</span>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
{(c.status === "suspended" || c.status === "rejected") && (
<Alert>
<AlertTitle>{c.status === "suspended" ? "Suspended by moderation" : "Rejected"}</AlertTitle>
<AlertDescription>
{c.statusReason || "No reason given."}{" "}
{c.status === "suspended" && "Its products aren't available from it, and it can't take uploads."}
</AlertDescription>
</Alert>
)}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Stat label="Products" value={String(data.hosted.products)} note={`${data.hosted.revisions} revisions`} />
<Stat label="Storage" value={formatSize(data.hosted.bytes)} note="in the revisions it hosts" />
{data.members && (
<>
<Stat label="Members" value={String(data.members.members)} note={`${data.members.banned} banned`} />
<Stat label="Requests" value={String(data.members.requests)} note="waiting" />
</>
)}
</div>
<Card>
<CardHeader>
<CardTitle>Settings</CardTitle>
{!has("catalog:edit") && <CardDescription>Only the owner and operators change these.</CardDescription>}
</CardHeader>
<CardContent>
<ActionForm action={saveCatalog} fields={{ id }}>
<fieldset disabled={!has("catalog:edit")} className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input id="name" name="name" defaultValue={c.name} required maxLength={64} />
</Field>
<Field>
<FieldLabel htmlFor="url">Address</FieldLabel>
<Input id="url" name="url" type="url" defaultValue={c.url} required maxLength={300} />
</Field>
<Field>
<FieldLabel htmlFor="contact">Takedown contact</FieldLabel>
<Input id="contact" name="contact" defaultValue={c.contact} required maxLength={200} />
</Field>
<Choice
name="visibility"
label="Visibility"
value={c.visibility}
options={[
["public", "Public (listed)"],
["private", "Private (by link)"],
]}
/>
<Choice
name="membership"
label="Membership"
value={c.membership}
options={[
["open", "Open"],
["approval", "By approval"],
["invite", "Invite only"],
]}
/>
<Choice
name="maxRating"
label="Highest rating"
value={c.maxRating}
options={[
["general", "General only"],
["adult", "Adult too"],
]}
/>
<Choice
name="uploads"
label="Who may upload"
value={c.uploads}
options={[
["anyone", "Anyone"],
["members", "Members"],
["team", "Only the team"],
]}
/>
<Choice
name="mirrors"
label="Mirroring others' products"
value={c.mirrors}
options={[
["auto", "Accept"],
["approve", "Team approves"],
["off", "Off"],
]}
/>
</fieldset>
{has("catalog:edit") && <SubmitButton pendingLabel="Saving…">Save</SubmitButton>}
</ActionForm>
</CardContent>
</Card>
{(has("import:accept") || has("import:pause")) && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
Imports <Tag tone={c.importer === "on" ? "online" : "neutral"}>{c.importer}</Tag>
</CardTitle>
<CardDescription>
Creators&apos; IMVU products, imported with their permission: grants, the importer and its queue.
</CardDescription>
</CardHeader>
<CardContent>
<Link href={`/console/catalogs/${id}/imports`} className="text-sm underline underline-offset-4">
Manage imports
</Link>
</CardContent>
</Card>
)}
{has("catalog:rotate-key") && (
<Card>
<CardHeader>
<CardTitle>Key</CardTitle>
<CardDescription>
The catalog signs in to the hub with its ID ({id}) and key. A new key stops the old one at once.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={rotateKey} fields={{ id }}>
<SubmitButton variant="outline" pendingLabel="Making one…" confirm="The old key stops working at once. Go on?">
New key
</SubmitButton>
</ActionForm>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Team</CardTitle>
<CardDescription>The owner, and operators: they manage everything but the team itself.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ul className="divide-y text-sm">
{team.owner && (
<li className="flex items-center justify-between py-2">
<span>{team.owner.username}</span>
<Tag tone="strong">owner</Tag>
</li>
)}
{team.roles.map((r) => (
<li key={r.personId + r.role} className="flex items-center justify-between gap-2 py-2">
<span>{r.username}</span>
<span className="flex items-center gap-2">
<Tag>operator</Tag>
{(has("team:manage") || r.personId === me.id) && (
<ActionForm action={removeFromTeam} fields={{ id, username: r.username }}>
<SubmitButton
size="sm"
variant="outline"
pendingLabel="Removing…"
confirm={r.personId === me.id ? "Leave this catalog's team?" : `Take ${r.username} off the team?`}
>
{r.personId === me.id ? "Leave" : "Remove"}
</SubmitButton>
</ActionForm>
)}
</span>
</li>
))}
</ul>
{has("team:manage") && (
<ActionForm action={addOperator} fields={{ id }}>
<div className="flex max-w-md gap-2">
<Input name="username" placeholder="T5DE username" aria-label="Username" required maxLength={64} />
<SubmitButton pendingLabel="Adding…">Add operator</SubmitButton>
</div>
</ActionForm>
)}
{!onTeam && team.owner?.personId !== me.id && (
<p className="text-sm text-muted-foreground">You see this as a moderator.</p>
)}
</CardContent>
</Card>
{members && (
<Card>
<CardHeader>
<CardTitle>Members</CardTitle>
<CardDescription>
{c.membership === "open"
? "Open: anyone can get its products. Bans still apply."
: c.membership === "approval"
? "By approval: people ask, the team decides."
: "Invite only: people join with an invitation."}
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<MemberList id={id} title="Requests" members={byStatus("requested")} actions={["approve", "decline"]} />
<MemberList id={id} title="Members" members={byStatus("member")} actions={["ban", "remove"]} />
<MemberList id={id} title="Banned" members={byStatus("banned")} actions={["unban"]} />
<ActionForm action={decideMember} fields={{ id, decision: "add" }}>
<div className="flex max-w-md gap-2">
<Input name="username" placeholder="T5DE username" aria-label="Username" required maxLength={64} />
<SubmitButton variant="outline" pendingLabel="Adding…">
Add member
</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
{invites && (
<Card>
<CardHeader>
<CardTitle>Invitations</CardTitle>
<CardDescription>Links that let people join (also an approval or invite-only catalog) at once.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{invites.invites.length > 0 && (
<Table>
<TableHeader>
<TableRow>
<TableHead>Link</TableHead>
<TableHead>Used</TableHead>
<TableHead>Expires</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{invites.invites.map((i) => (
<TableRow key={i.code}>
<TableCell className="font-mono text-xs break-all whitespace-normal">{i.url}</TableCell>
<TableCell className="tabular-nums">
{i.uses}
{i.maxUses !== null && ` of ${i.maxUses}`}
</TableCell>
<TableCell className="text-muted-foreground">
{i.expiresAt ? <DateTime iso={i.expiresAt} dateOnly /> : "never"}
</TableCell>
<TableCell className="text-right">
<ActionForm action={revokeInvite} fields={{ id, code: i.code }}>
<SubmitButton size="sm" variant="outline" pendingLabel="Revoking…">
Revoke
</SubmitButton>
</ActionForm>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
<ActionForm action={createInvite} fields={{ id }}>
<div className="flex flex-wrap items-end gap-2">
<Field className="w-36">
<FieldLabel htmlFor="maxUses">Uses</FieldLabel>
<Input id="maxUses" name="maxUses" type="number" min={1} max={10000} placeholder="Any" />
</Field>
<Field className="w-36">
<FieldLabel htmlFor="expiresInDays">Days</FieldLabel>
<Input id="expiresInDays" name="expiresInDays" type="number" min={1} max={365} placeholder="Never" />
</Field>
<SubmitButton pendingLabel="Making it…">New invitation</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Products</CardTitle>
<CardDescription>What it hosts. Delisting stops hosting a product here; other catalogs may still host it.</CardDescription>
</CardHeader>
<CardContent>
{hosted.products.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing yet.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead>Creator</TableHead>
<TableHead>Revisions</TableHead>
<TableHead>Since</TableHead>
{has("hosting:delist") && <TableHead />}
</TableRow>
</TableHeader>
<TableBody>
{hosted.products.map((p) => (
<TableRow key={p.id}>
<TableCell className="font-medium">
<Link href={`/products/${p.id}`} className="underline-offset-4 hover:underline">
{p.name}
</Link>{" "}
<RatingTag rating={p.rating === "adult" ? "adult" : "general"} />{" "}
{p.removed && <Tag tone="danger">removed</Tag>}
{p.deleted && <Tag>deleted</Tag>}
</TableCell>
<TableCell>{p.creator}</TableCell>
<TableCell className="tabular-nums">{p.revisions.join(", ")}</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={p.since} dateOnly />
</TableCell>
{has("hosting:delist") && (
<TableCell className="text-right">
<ActionForm action={delist} fields={{ id, product: p.id }}>
<div className="flex justify-end gap-2">
<Input name="reason" placeholder="Reason" aria-label="Reason" required maxLength={500} className="h-8 w-40" />
<SubmitButton size="sm" variant="outline" pendingLabel="Delisting…" confirm={`Stop hosting ${p.name}?`}>
Delist
</SubmitButton>
</div>
</ActionForm>
{!p.removed && (
<details className="mt-1 text-left text-xs">
<summary className="cursor-pointer text-right text-muted-foreground hover:text-foreground">
Ask moderators to remove it everywhere
</summary>
<ActionForm action={requestRemoval} fields={{ catalog: id, product: p.id }} className="mt-2">
<div className="flex justify-end gap-2">
<Input name="reason" placeholder="Why" aria-label="Why" required maxLength={2000} className="h-8 w-48" />
<SubmitButton size="sm" variant="outline" pendingLabel="Asking…">
Ask
</SubmitButton>
</div>
</ActionForm>
</details>
)}
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
{has("catalog:suspend") && (c.status === "approved" || c.status === "suspended") && (
<Card>
<CardHeader>
<CardTitle>Moderation</CardTitle>
<CardDescription>
A suspended catalog's products aren't available from it, it can't take uploads, and its team sees why.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={setSuspended} fields={{ id }}>
{c.status === "suspended" ? (
<SubmitButton name="intent" value="reinstate" pendingLabel="Reinstating…">
Reinstate
</SubmitButton>
) : (
<div className="flex max-w-xl gap-2">
<Input name="reason" placeholder="Reason (shown to its team)" aria-label="Reason" required maxLength={500} />
<SubmitButton name="intent" value="suspend" variant="outline" pendingLabel="Suspending…" confirm={`Suspend ${c.name}?`}>
Suspend
</SubmitButton>
</div>
)}
</ActionForm>
</CardContent>
</Card>
)}
{has("catalog:delete-request") && c.status !== "deleted" && (
<Card>
<CardHeader>
<CardTitle>Delete Catalog</CardTitle>
<CardDescription>
Moderators review deletions for now. Once deleted, nothing is available from it; people who got its products
keep them only where other catalogs host them.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={requestDeletion} fields={{ id }}>
<div className="flex max-w-xl gap-2">
<Input name="reason" placeholder="Why" aria-label="Why" required maxLength={2000} />
<SubmitButton variant="destructive" pendingLabel="Asking…" confirm={`Ask moderators to delete ${c.name}?`}>
Ask to delete
</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Recent Changes</CardTitle>
<CardDescription>
<Link href={`/console/audit?catalog=${id}`} className="underline-offset-4 hover:underline">
All changes to this catalog
</Link>
</CardDescription>
</CardHeader>
<CardContent>
<AuditTable entries={audit.entries} />
</CardContent>
</Card>
</div>
</>
);
}
function Stat({ label, value, note }: { label: string; value: string; note: string }) {
return (
<Card>
<CardHeader>
<CardDescription>{label}</CardDescription>
<CardTitle className="text-3xl font-semibold tabular-nums">{value}</CardTitle>
</CardHeader>
<CardContent className="text-sm text-muted-foreground">{note}</CardContent>
</Card>
);
}
function Choice({ name, label, value, options }: { name: string; label: string; value: string; options: [string, string][] }) {
return (
<Field>
<FieldLabel htmlFor={name}>{label}</FieldLabel>
<NativeSelect id={name} name={name} defaultValue={value} className="w-full">
{options.map(([v, l]) => (
<NativeSelectOption key={v} value={v}>
{l}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
);
}
const memberActions = {
approve: { label: "Approve", variant: "default" as const },
decline: { label: "Decline", variant: "outline" as const },
ban: { label: "Ban", variant: "outline" as const },
remove: { label: "Remove", variant: "outline" as const },
unban: { label: "Unban", variant: "outline" as const },
};
function MemberList({
id,
title,
members,
actions,
}: {
id: string;
title: string;
members: CatalogMember[];
actions: (keyof typeof memberActions)[];
}) {
if (members.length === 0) return null;
return (
<div className="space-y-2">
<h3 className="text-sm font-medium">
{title} <span className="text-muted-foreground tabular-nums">{members.length}</span>
</h3>
<ul className="divide-y text-sm">
{members.map((m) => (
<li key={m.personId} className="flex items-center justify-between gap-2 py-2">
<span>
{m.username}{" "}
<span className="text-muted-foreground">
{m.invited ? "invited, " : ""}
<DateTime iso={m.since} dateOnly />
</span>
</span>
<ActionForm action={decideMember} fields={{ id, username: m.username }}>
<div className="flex gap-2">
{actions.map((a) => (
<SubmitButton
key={a}
size="sm"
variant={memberActions[a].variant}
name="decision"
value={a}
confirm={a === "ban" ? `Ban ${m.username} from this catalog?` : undefined}
>
{memberActions[a].label}
</SubmitButton>
))}
</div>
</ActionForm>
</li>
))}
</ul>
</div>
);
}
+273
View File
@@ -0,0 +1,273 @@
"use server";
// Managing a catalog from the console: settings, key, team, members, invitations, what it hosts, suspension.
import { revalidatePath } from "next/cache";
import { api, ApiError, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
/** Runs a change to a catalog, then shows its pages again. */
async function onCatalog(form: FormData, change: (id: string) => Promise<string | void>): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
const notice = await change(id);
revalidatePath(`/console/catalogs/${id}`);
revalidatePath(`/catalogs/${id}`);
revalidatePath("/console/catalogs");
revalidatePath("/catalogs");
return notice;
});
}
const pick = <T extends string>(v: string, options: readonly T[]): T | undefined => options.find((o) => o === v);
export async function saveCatalog(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
unwrap(
await api.catalogs({ id }).patch({
name: field(form, "name"),
url: field(form, "url"),
contact: field(form, "contact"),
visibility: pick(field(form, "visibility"), ["public", "private"] as const),
membership: pick(field(form, "membership"), ["open", "approval", "invite"] as const),
maxRating: pick(field(form, "maxRating"), ["general", "adult"] as const),
uploads: pick(field(form, "uploads"), ["anyone", "members", "team"] as const),
mirrors: pick(field(form, "mirrors"), ["auto", "approve", "off"] as const),
}),
);
return "Saved.";
});
}
export async function rotateKey(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const { key } = unwrap(await api.catalogs({ id }).key.post());
return `New key (shown once; put it in the catalog's CATALOG_KEY and restart it): ${key}`;
});
}
export async function setSuspended(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
if (field(form, "intent") === "reinstate") unwrap(await api.catalogs({ id }).reinstate.post());
else unwrap(await api.catalogs({ id }).suspend.post({ reason: field(form, "reason") }));
});
}
export async function addOperator(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const username = field(form, "username");
unwrap(await api.catalogs({ id }).team({ username }).put({ role: "catalog-operator" }));
return `${username} is an operator now.`;
});
}
export async function removeFromTeam(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
unwrap(await api.catalogs({ id }).team({ username: field(form, "username") }).delete({}, { query: { role: "catalog-operator" } }));
});
}
/** A member or request: approve, decline, add, ban, unban or remove. */
export async function decideMember(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const member = api.catalogs({ id }).members({ username: field(form, "username") });
switch (field(form, "decision")) {
case "approve":
case "add":
unwrap(await member.put({ status: "member" }));
break;
case "ban":
unwrap(await member.put({ status: "banned" }));
break;
default: // decline, unban, remove
unwrap(await member.delete());
}
});
}
export async function createInvite(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const maxUses = Number(field(form, "maxUses")) || undefined;
const expiresInDays = Number(field(form, "expiresInDays")) || undefined;
const { invite } = unwrap(await api.catalogs({ id }).invites.post({ maxUses, expiresInDays }));
return `Invitation link: ${invite.url}`;
});
}
export async function revokeInvite(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
unwrap(await api.catalogs({ id }).invites({ code: field(form, "code") }).delete());
});
}
export async function delist(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
const product = field(form, "product");
unwrap(await api.catalogs({ id }).products({ product }).delete({}, { query: { reason: field(form, "reason") } }));
revalidatePath(`/products/${product}`);
});
}
/** Someone joins a catalog (or asks to), with an invitation code if they have one; or leaves it. */
export async function membership(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
if (field(form, "intent") === "leave") {
unwrap(await api.catalogs({ id }).join.delete());
revalidatePath("/library");
return "You left.";
}
const invite = field(form, "invite");
const { membership } = unwrap(await api.catalogs({ id }).join.post(invite ? { invite } : {}));
revalidatePath("/library");
return membership === "member" ? "You're a member." : "Asked. The catalog's team will decide.";
});
}
// ---- imports (docs/imports.md) ----
/** Turns the importer on (its key, shown once) or off, pauses or resumes it, or makes a new key. */
export async function setImporter(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const intent = field(form, "intent");
if (intent === "key") {
const { key } = unwrap(await api.catalogs({ id }).importer.key.post());
return `New importer key (shown once; put it in the importer's IMPORTER_KEY and restart it): ${key}`;
}
const body =
intent === "on" ? { enabled: true } : intent === "off" ? { enabled: false } : { paused: intent === "pause" };
const r = unwrap(await api.catalogs({ id }).importer.post(body));
if (r.key) return `Imports are on. The importer's key (shown once; put it in IMPORTER_KEY): ${r.key}`;
});
}
/** The catalog's team accepts, declines or ends a creator's grant. */
export async function decideGrant(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const grant = field(form, "grant");
const intent = field(form, "intent");
const reason = field(form, "reason");
if (intent === "end") {
unwrap(await api.imports.grants({ id: grant }).delete(reason ? { reason } : {}));
return "Ended. Its imported products were taken away.";
}
const decision = intent === "accept" ? "accept" : "decline";
const r = unwrap(
await api.imports
.grants({ id: grant })({ decision })
.post(reason ? { reason } : {}),
);
if (decision !== "accept") return "Declined.";
return r.grant.scope === "shop"
? `Accepted. ${r.queued} queued for the importer; the shop's other products follow once it's listed on IMVU.`
: `Accepted. ${r.queued} queued for the importer.`;
});
}
/** Lists a whole-shop grant's products on IMVU again (new ones are queued). */
export async function listShop(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
const r = unwrap(await api.imports.grants({ id: field(form, "grant") }).list.post());
return `${r.listed} product${r.listed === 1 ? "" : "s"} on IMVU; ${r.queued} new queued.`;
});
}
/** Retries a failed import job (or imports a product again). */
export async function retryJob(_: ActionState, form: FormData): Promise<ActionState> {
return onCatalog(form, async (id) => {
revalidatePath(`/console/catalogs/${id}/imports`);
unwrap(
await api
.catalogs({ id })
.importer.jobs({ job: field(form, "job") })
.retry.post(),
);
return "Queued.";
});
}
// ---- the importer program and its IMVU accounts (docs/imports.md "IMVU accounts") ----
export type ImvuAccountInfo = {
imvuId: number;
username: string;
picture: string | null;
accessPass: boolean;
ageVerified: boolean;
};
/** Called from the browser: an error to show, or what was asked for. */
async function answered<T>(fn: () => Promise<T>): Promise<{ error: string } | { ok: T }> {
try {
return { ok: await fn() };
} catch (e) {
if (e instanceof ApiError) return { error: e.message };
throw e;
}
}
/** Looks an IMVU account up for the confirmation dialog (public info only). */
export async function lookupImporterAccount(id: string, username: string) {
return answered<ImvuAccountInfo>(async () =>
unwrap(await api.catalogs({ id }).importer["imvu-account"].get({ query: { username: username.trim() } })),
);
}
/**
* Adds an account, or gives one a new password (account set). The password arrives sealed in the browser for the
* importer's key; it never passes through here readable.
*/
export async function saveImporterAccount(
id: string,
a: { imvuId: number; account?: string; sealed: string; fingerprint: string },
) {
const r = await answered(async () => {
if (a.account)
unwrap(
await api
.catalogs({ id })
.importer.accounts({ account: a.account })
.password.put({ sealed: a.sealed, fingerprint: a.fingerprint }),
);
else unwrap(await api.catalogs({ id }).importer.accounts.post({ imvuId: a.imvuId, sealed: a.sealed, fingerprint: a.fingerprint }));
return true;
});
revalidatePath(`/console/catalogs/${id}/imports`);
return r;
}
/** Moves an account up or down, or removes it. */
export async function changeImporterAccount(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
const account = field(form, "account");
return attempt(async () => {
const intent = field(form, "intent");
if (intent === "remove") {
unwrap(await api.catalogs({ id }).importer.accounts({ account }).delete());
revalidatePath(`/console/catalogs/${id}/imports`);
return "Removed. The importer forgets it within a minute.";
}
unwrap(
await api
.catalogs({ id })
.importer.accounts({ account })
.move.post({ direction: intent === "up" ? "up" : "down" }),
);
revalidatePath(`/console/catalogs/${id}/imports`);
});
}
/** The importer's settings. */
export async function setImporterSettings(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
unwrap(
await api.catalogs({ id }).importer.settings.post({
rate: Number(field(form, "rate")),
concurrency: Number(field(form, "concurrency")),
}),
);
revalidatePath(`/console/catalogs/${id}/imports`);
return "Saved. The importer picks it up within a minute.";
});
}
+38 -32
View File
@@ -1,23 +1,24 @@
import type { Metadata } from "next";
import Link from "next/link";
import { CatalogStatus, membership } from "@/components/catalogs";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader } from "@/components/status";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap } from "@/lib/api";
import { decideCatalog } from "../actions";
import { ConsoleNav, requireModerator } from "../console-nav";
import { ConsoleNav, requireConsole } from "../console-nav";
export const metadata: Metadata = { title: "Catalogs" };
export default async function ConsoleCatalogs() {
await requireModerator("/console/catalogs");
const { catalogs } = unwrap(await api.console.catalogs.get());
await requireConsole("/console/catalogs");
const { catalogs, moderator } = unwrap(await api.console.catalogs.get());
return (
<>
<PageHeader title="Catalogs" />
<PageHeader title="Catalogs">{moderator ? "Every registered catalog." : "Catalogs you're on the team of."}</PageHeader>
<ConsoleNav />
<Card>
<CardContent>
@@ -29,19 +30,22 @@ export default async function ConsoleCatalogs() {
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Address</TableHead>
<TableHead>Takedown contact</TableHead>
<TableHead>Access</TableHead>
<TableHead>Registered</TableHead>
<TableHead>Status</TableHead>
<TableHead />
{moderator && <TableHead />}
</TableRow>
</TableHeader>
<TableBody>
{catalogs.map((c) => (
<TableRow key={c.id}>
<TableCell className="font-medium">{c.name}</TableCell>
<TableCell className="font-medium">
<Link href={`/console/catalogs/${c.id}`} className="underline-offset-4 hover:underline">
{c.name}
</Link>{" "}
{c.mine ? <Tag>owner</Tag> : c.team ? <Tag>team</Tag> : null}
</TableCell>
<TableCell className="font-mono text-xs">{c.url}</TableCell>
<TableCell className="text-muted-foreground">{c.contact}</TableCell>
<TableCell className="text-muted-foreground">
<span className="capitalize">{c.visibility}</span>, {membership[c.membership]?.toLowerCase() ?? c.membership}
</TableCell>
@@ -51,29 +55,31 @@ export default async function ConsoleCatalogs() {
<TableCell>
<CatalogStatus status={c.status} />
</TableCell>
<TableCell className="text-right">
<ActionForm action={decideCatalog} fields={{ id: c.id }} className="space-y-1">
<div className="flex justify-end gap-2">
{c.status !== "approved" && (
<SubmitButton size="sm" name="decision" value="approve" pendingLabel="Approving…">
Approve
</SubmitButton>
)}
{c.status !== "rejected" && (
<SubmitButton
size="sm"
variant="outline"
name="decision"
value="reject"
pendingLabel="Rejecting…"
confirm={`Reject ${c.name}?`}
>
Reject
</SubmitButton>
)}
</div>
</ActionForm>
</TableCell>
{moderator && (
<TableCell className="text-right">
{(c.status === "pending" || c.status === "rejected") && (
<ActionForm action={decideCatalog} fields={{ id: c.id }} className="space-y-1">
<div className="flex justify-end gap-2">
<SubmitButton size="sm" name="decision" value="approve" pendingLabel="Approving…">
Approve
</SubmitButton>
{c.status !== "rejected" && (
<SubmitButton
size="sm"
variant="outline"
name="decision"
value="reject"
pendingLabel="Rejecting…"
confirm={`Reject ${c.name}?`}
>
Reject
</SubmitButton>
)}
</div>
</ActionForm>
)}
</TableCell>
)}
</TableRow>
))}
</TableBody>
+68 -10
View File
@@ -1,8 +1,11 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import { NavLink } from "@/components/header-client";
import { getMe, isModerator, type Person } from "@/lib/api";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { api, getMe, isModerator, unwrap, type ConsoleData, type Person } from "@/lib/api";
/** The signed-in moderator, or off to sign in; others get not found (the console isn't for them). */
/** The signed-in moderator, or off to sign in; others get not found (these pages aren't for them). */
export async function requireModerator(path: string): Promise<Person> {
const me = await getMe();
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
@@ -10,14 +13,69 @@ export async function requireModerator(path: string): Promise<Person> {
return me;
}
export function ConsoleNav() {
/** The console as this person sees it (once per request); undefined if it isn't for them. */
const loadConsole = cache(async (): Promise<ConsoleData | undefined> => {
const answer = await api.console.get();
if (answer.error) return undefined;
return unwrap(answer);
});
/**
* The signed-in person and their console, or off to sign in. People who manage nothing get not found: the console
* is for those controlling a product, catalog or room.
*/
export async function requireConsole(path: string): Promise<{ me: Person; console: ConsoleData }> {
const me = await getMe();
if (!me) redirect(`/signin?next=${encodeURIComponent(path)}`);
const data = await loadConsole();
if (!data) notFound();
return { me, console: data };
}
type Section = ConsoleData["sections"][number];
// Settings are on the overview.
const tabs: { section: Section; href: string; label: string }[] = [
{ section: "overview", href: "/console", label: "Overview" },
{ section: "products", href: "/console/products", label: "Products" },
{ section: "catalogs", href: "/console/catalogs", label: "Catalogs" },
{ section: "cases", href: "/console/cases", label: "Cases" },
{ section: "people", href: "/console/people", label: "People" },
{ section: "imports", href: "/console/imports", label: "Imports" },
{ section: "blocks", href: "/console/blocks", label: "Blocks" },
{ section: "audit", href: "/console/audit", label: "Audit" },
];
/** The console's sections this person may see, and a reminder when sensitive actions need two-factor sign-in. */
export async function ConsoleNav() {
const data = await loadConsole();
const sections = new Set<Section>(data?.sections ?? ["overview"]);
const needed = data?.twoFactorNeededFor ?? [];
return (
<nav className="mb-8 flex gap-1 border-b pb-3 text-sm">
<NavLink href="/console" exact>
Overview
</NavLink>
<NavLink href="/console/people">People</NavLink>
<NavLink href="/console/catalogs">Catalogs</NavLink>
</nav>
<>
{needed.length > 0 && (
<Alert className="mb-6">
<AlertTitle>Turn on two-factor sign-in</AlertTitle>
<AlertDescription>
<span>
Some of what you can do here needs it ({needed.join(", ")}).{" "}
<Link href="/account" className="text-foreground underline underline-offset-4">
Turn it on in your account
</Link>
.
</span>
</AlertDescription>
</Alert>
)}
<nav className="mb-8 flex gap-1 border-b pb-3 text-sm">
{tabs
.filter((t) => sections.has(t.section))
.map((t) => (
<NavLink key={t.section} href={t.href} exact={t.section === "overview"}>
{t.label}
</NavLink>
))}
</nav>
</>
);
}
+71
View File
@@ -0,0 +1,71 @@
"use server";
// Recorded grants from the console (docs/imports.md): admins record consent for IMVU creators who won't make an
// account, prove it with a tagline code, and change or withdraw them until the creator claims them.
import { revalidatePath } from "next/cache";
import { api, ApiError, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
import { productIDs } from "@/lib/imvu";
const done = () => revalidatePath("/console/imports");
/** Records a creator's consent: a grant for an unclaimed creator standing in for their IMVU account. */
export async function recordGrant(_: ActionState, form: FormData): Promise<ActionState> {
const scope = field(form, "scope") === "products" ? "products" : "shop";
const list = productIDs(field(form, scope === "products" ? "products" : "exclude"));
if (!list) return { error: "Products are IMVU product IDs or shop links, separated by spaces, commas or lines." };
return attempt(async () => {
const r = unwrap(
await api.console.imports.grants.post({
catalog: field(form, "catalog"),
imvu: field(form, "imvu"),
scope,
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
evidence: field(form, "evidence"),
}),
);
done();
return `Recorded for ${r.grant.imvuName}. The catalog's team accepts it before anything is imported.`;
});
}
/** Proof without an account: a code for the creator's tagline, then checking it. */
export async function grantProof(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
if (field(form, "intent") === "check") {
unwrap(await api.console.imports.grants({ id }).proof.check.post());
done();
return "Proven: the code is in their tagline. They can take it out now.";
}
const { code } = unwrap(await api.console.imports.grants({ id }).proof.post());
done();
return `Send them this code to put in their IMVU tagline: ${code}`;
});
}
/** Changes what a recorded grant covers, or withdraws it. */
export async function changeRecorded(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
if (field(form, "intent") === "withdraw") {
const reason = field(form, "reason") || "Withdrawn at the creator's request.";
const r = unwrap(await api.imports.grants({ id }).delete({ reason }));
done();
return r.withdrawn.length ? `Withdrawn. ${r.withdrawn.length} imported products were taken away.` : "Withdrawn.";
}
const scope = field(form, "scope") === "products" ? "products" : "shop";
const list = productIDs(field(form, "list"));
if (!list) throw new ApiError(400, "invalid", "Products are IMVU product IDs or shop links.");
const r = unwrap(
await api.imports.grants({ id }).patch({
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
}),
);
done();
return r.withdrawn.length
? `Saved. ${r.withdrawn.length} imported products it no longer covers were taken away.`
: "Saved.";
});
}
+293
View File
@@ -0,0 +1,293 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { ShopListing } from "@/components/shop-listing";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { api, unwrap } from "@/lib/api";
import { ConsoleNav, requireConsole } from "../console-nav";
import { changeRecorded, grantProof, recordGrant } from "./actions";
export const metadata: Metadata = { title: "Imports" };
type Recorded = Awaited<ReturnType<typeof load>>["grants"][number];
const load = async () => unwrap(await api.console.imports.get());
const statusTone = {
pending: "strong",
active: "online",
declined: "neutral",
suspended: "danger",
withdrawn: "neutral",
} as const;
const imvuShop = (id: number) => `https://www.imvu.com/shop/web_search.php?manufacturers_id=${id}`;
export default async function ConsoleImports() {
const { console: c } = await requireConsole("/console/imports");
if (!c.sections.includes("imports")) notFound();
const data = await load();
const open = data.grants.filter((g) => g.status !== "withdrawn" && g.status !== "declined");
const ended = data.grants.filter((g) => g.status === "withdrawn" || g.status === "declined");
return (
<>
<PageHeader title="Imports">
Consent recorded for IMVU creators who won&apos;t make an account, and the creators people ask for most.
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Record a Creator&apos;s Consent</CardTitle>
<CardDescription>
For creators who agreed to have their IMVU products on T5DE but won&apos;t make an account. Their products
belong to a placeholder until they join and link that IMVU account, when they can claim them. The
catalog&apos;s team still accepts it.
</CardDescription>
</CardHeader>
<CardContent>
{data.catalogs.length === 0 ? (
<p className="text-sm text-muted-foreground">No catalog takes imports yet.</p>
) : (
<ActionForm action={recordGrant} className="max-w-2xl space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="imvu">IMVU creator</FieldLabel>
<Input id="imvu" name="imvu" required maxLength={64} placeholder="Username or account ID" />
</Field>
<Field>
<FieldLabel htmlFor="catalog">Catalog</FieldLabel>
<NativeSelect id="catalog" name="catalog">
{data.catalogs.map((k) => (
<NativeSelectOption key={k.id} value={k.id}>
{k.name}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
</div>
<fieldset className="space-y-2">
<legend className="mb-2 text-sm font-medium">What they agreed to</legend>
<label className="flex items-center gap-2 text-sm">
<input type="radio" name="scope" value="shop" defaultChecked />
Their whole shop, including new products (leave some out below)
</label>
<label className="flex items-center gap-2 text-sm">
<input type="radio" name="scope" value="products" />
Only the products listed below
</label>
</fieldset>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="exclude">Leave out (whole shop)</FieldLabel>
<Textarea
id="exclude"
name="exclude"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<Field>
<FieldLabel htmlFor="products">Products (only these)</FieldLabel>
<Textarea
id="products"
name="products"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
</div>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked />
Listed (shown in search; unlisted ones work by link)
</label>
<Field>
<FieldLabel htmlFor="evidence">How they agreed</FieldLabel>
<Textarea
id="evidence"
name="evidence"
rows={2}
required
maxLength={1000}
placeholder="Where and when, e.g. Discord DM, 2026-11-07"
/>
<FieldDescription>
They agreed to: &ldquo;{data.consent.text}&rdquo; You can prove it afterwards with a code in their
IMVU tagline.
</FieldDescription>
</Field>
<SubmitButton pendingLabel="Recording…">Record</SubmitButton>
</ActionForm>
)}
</CardContent>
</Card>
{open.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Recorded Grants</CardTitle>
</CardHeader>
<CardContent className="divide-y">
{open.map((g) => (
<RecordedRow key={g.id} grant={g} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Most Asked For</CardTitle>
<CardDescription>
IMVU creators whose products T5DE users ask for: whom it&apos;s worth asking.
</CardDescription>
</CardHeader>
<CardContent>
{data.creators.length === 0 ? (
<p className="text-sm text-muted-foreground">Nobody has asked for anything yet.</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>IMVU creator</TableHead>
<TableHead className="text-right">People</TableHead>
<TableHead className="text-right">Products</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.creators.map((k) => (
<TableRow key={k.imvuCreator}>
<TableCell>
<a
href={imvuShop(k.imvuCreator)}
target="_blank"
rel="noreferrer"
className="underline-offset-4 hover:underline"
>
{k.name || `IMVU account ${k.imvuCreator}`}
</a>
</TableCell>
<TableCell className="text-right tabular-nums">{k.people}</TableCell>
<TableCell className="text-right tabular-nums">{k.products}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
{ended.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">Ended</summary>
<ul className="mt-2 divide-y">
{ended.map((g) => (
<li key={g.id} className="py-2">
{g.imvuName || g.imvuId} → {g.catalogName} <Tag tone={statusTone[g.status]}>{g.status}</Tag>{" "}
<span className="text-muted-foreground">{g.statusReason}</span>
</li>
))}
</ul>
</details>
)}
</div>
</>
);
}
function RecordedRow({ grant: g }: { grant: Recorded }) {
const list = g.scope === "products" ? g.products : g.exclude;
return (
<div className="space-y-3 py-4 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || `IMVU account ${g.imvuId}`}</span>
<span className="text-muted-foreground">(IMVU {g.imvuId}) to</span>
<span className="font-medium">{g.catalogName}</span>
<Tag tone={statusTone[g.status]}>{g.status === "pending" ? "waiting for the catalog" : g.status}</Tag>
{g.consentProven ? <Tag tone="online">proven</Tag> : <Tag>not proven</Tag>}
{g.claimed && <Tag tone="strong">claimed</Tag>}
</div>
<p className="text-sm text-muted-foreground">
{g.evidence} · recorded by {g.recordedBy || "someone"} on <DateTime iso={g.createdAt} dateOnly />
</p>
<p className="text-sm">
{g.scope === "shop"
? `The whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
<ShopListing grant={g} />
</p>
{g.claimed ? (
<p className="text-sm text-muted-foreground">The creator claimed it: they manage it now.</p>
) : (
<>
{!g.consentProven && (
<ActionForm action={grantProof} fields={{ id: g.id }}>
<div className="flex flex-wrap items-center gap-2 text-sm">
{g.proofCode ? (
<>
<span>
Code for their tagline: <code className="font-mono">{g.proofCode}</code>
</span>
<SubmitButton name="intent" value="check" size="sm" variant="outline" pendingLabel="Checking…">
Check their tagline
</SubmitButton>
</>
) : (
<SubmitButton name="intent" value="code" size="sm" variant="outline" pendingLabel="Making one…">
Prove it with a tagline code
</SubmitButton>
)}
</div>
</ActionForm>
)}
<ActionForm action={changeRecorded} fields={{ id: g.id, scope: g.scope }} className="max-w-2xl space-y-2">
<Field>
<FieldLabel htmlFor={`list-${g.id}`}>{g.scope === "shop" ? "Left out" : "Products"}</FieldLabel>
<Textarea
id={`list-${g.id}`}
name="list"
rows={2}
defaultValue={list.join("\n")}
className="font-mono text-xs"
/>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked={g.listed} />
Listed
</label>
<div className="flex flex-wrap gap-2">
<Input
name="reason"
maxLength={500}
placeholder="Reason (if withdrawing)"
aria-label="Reason"
className="max-w-xs"
/>
<SubmitButton name="intent" value="save" variant="outline" pendingLabel="Saving…">
Save
</SubmitButton>
<SubmitButton
name="intent"
value="withdraw"
variant="outline"
pendingLabel="Withdrawing…"
confirm="Withdraw? Its imported products are taken away from everyone who has them."
>
Withdraw
</SubmitButton>
</div>
</ActionForm>
</>
)}
</div>
);
}
+104 -65
View File
@@ -1,59 +1,107 @@
import type { Metadata } from "next";
import Link from "next/link";
import { ActionForm, SubmitButton } from "@/components/forms";
import { OnlineList } from "@/components/online-list";
import { PageHeader } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, unwrap, type AuditEntry } from "@/lib/api";
import { ConsoleNav, requireModerator } from "./console-nav";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { api, unwrap } from "@/lib/api";
import { setRegistration } from "./actions";
import { AuditTable } from "./audit-table";
import { ConsoleNav, requireConsole } from "./console-nav";
export const metadata: Metadata = { title: "Console" };
type Stat = { label: string; value: number; note: string; href?: string };
export default async function Console() {
await requireModerator("/console");
const data = unwrap(await api.console.get());
const stats = [
{ label: "People", value: data.counts.people, note: "accounts" },
{ label: "IMVU accounts", value: data.counts.links, note: "linked" },
{ label: "Computers", value: data.counts.computers, note: "signed in" },
const { me, console: data } = await requireConsole("/console");
const settings = me.role === "admin" ? await api.console.settings.get().then(unwrap) : undefined;
const todo: Stat[] = [
{ label: "Cases", value: data.todo.cases, note: "open, for you to decide", href: "/console/cases" },
{ label: "Drafts", value: data.todo.drafts, note: "to review and publish", href: "/console/products?status=draft" },
{ label: "Member Requests", value: data.todo.memberRequests, note: "waiting in your catalogs", href: "/console/catalogs" },
];
if (data.moderation) {
todo.push(
{ label: "Catalogs", value: data.todo.pendingCatalogs, note: "waiting for approval", href: "/console/catalogs" },
{ label: "Accounts", value: data.todo.waitingPeople, note: "waiting for approval", href: "/console/people?waiting=true" },
);
}
const mine: Stat[] = [
{ label: "Your Products", value: data.mine.products, note: "you created", href: "/console/products" },
{ label: "Your Catalogs", value: data.mine.catalogs, note: "you're on the team of", href: "/console/catalogs" },
{ label: "Your Rooms", value: data.mine.rooms, note: "you host", href: "/rooms" },
];
const hub: Stat[] = data.moderation
? [
{ label: "People", value: data.moderation.counts.people, note: "accounts" },
{ label: "IMVU Accounts", value: data.moderation.counts.links, note: "linked" },
{ label: "Computers", value: data.moderation.counts.computers, note: "signed in" },
]
: [];
return (
<>
<PageHeader title="Console">Moderation.</PageHeader>
<PageHeader title="Console">What you manage on T5DE.</PageHeader>
<ConsoleNav />
<div className="space-y-6">
<div className="grid gap-4 sm:grid-cols-3">
{stats.map((s) => (
<Card key={s.label}>
<CardHeader>
<CardDescription>{s.label}</CardDescription>
<CardTitle className="text-3xl font-semibold tabular-nums">{s.value}</CardTitle>
</CardHeader>
<CardContent className="text-sm text-muted-foreground">{s.note}</CardContent>
</Card>
))}
</div>
<StatGrid stats={todo.filter((s) => s.value > 0 || data.moderation)} />
<StatGrid stats={mine.filter((s) => s.value > 0)} />
{hub.length > 0 && <StatGrid stats={hub} />}
{data.moderation && (
<Card>
<CardHeader>
<CardTitle>Online Now</CardTitle>
<CardDescription>
{data.moderation.connections} {data.moderation.connections === 1 ? "connection" : "connections"} when
the page loaded
</CardDescription>
</CardHeader>
<CardContent>
<OnlineList initial={data.moderation.online} moderator />
</CardContent>
</Card>
)}
{settings && (
<Card id="settings">
<CardHeader>
<CardTitle>Registration</CardTitle>
<CardDescription>
{settings.registration === "closed"
? "Closed: new accounts can sign in, but wait for a moderator's approval."
: "Open: new accounts can use the hub at once."}
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={setRegistration}>
<div className="flex gap-2">
<NativeSelect name="registration" defaultValue={settings.registration} aria-label="Registration">
<NativeSelectOption value="open">Open</NativeSelectOption>
<NativeSelectOption value="closed">Closed</NativeSelectOption>
</NativeSelect>
<SubmitButton pendingLabel="Setting…">Set</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Online now</CardTitle>
<CardTitle>Recent Changes</CardTitle>
<CardDescription>
{data.connections} {data.connections === 1 ? "connection" : "connections"} when the page loaded
{data.moderation ? "Across the hub." : "To what you manage, and by you."}{" "}
<Link href="/console/audit" className="underline-offset-4 hover:underline">
Full audit log
</Link>
</CardDescription>
</CardHeader>
<CardContent>
<OnlineList initial={data.online} moderator />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Audit log</CardTitle>
<CardDescription>The latest 50 changes.</CardDescription>
</CardHeader>
<CardContent>
<AuditLog entries={data.audit} />
<AuditTable entries={data.audit} />
</CardContent>
</Card>
</div>
@@ -61,36 +109,27 @@ export default async function Console() {
);
}
function AuditLog({ entries }: { entries: AuditEntry[] }) {
if (entries.length === 0) return <p className="text-sm text-muted-foreground">Nothing yet.</p>;
function StatGrid({ stats }: { stats: Stat[] }) {
if (stats.length === 0) return null;
return (
<Table>
<TableHeader>
<TableRow>
<TableHead>When</TableHead>
<TableHead>Who</TableHead>
<TableHead>What</TableHead>
<TableHead>Target</TableHead>
<TableHead>Detail</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{entries.map((e, i) => (
<TableRow key={i}>
<TableCell className="text-muted-foreground">
<DateTime iso={e.at} />
</TableCell>
<TableCell>{e.actor || <span className="text-muted-foreground">hub</span>}</TableCell>
<TableCell className="font-mono text-xs">{e.action}</TableCell>
<TableCell>{e.target}</TableCell>
<TableCell className="text-xs whitespace-normal text-muted-foreground">
{Object.entries((e.detail ?? {}) as Record<string, unknown>)
.map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
.join(", ")}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((s) => (
<Card key={s.label}>
<CardHeader>
<CardDescription>{s.label}</CardDescription>
<CardTitle className="text-3xl font-semibold tabular-nums">{s.value}</CardTitle>
</CardHeader>
<CardContent className="text-sm text-muted-foreground">
{s.href ? (
<Link href={s.href} className="underline-offset-4 hover:underline">
{s.note}
</Link>
) : (
s.note
)}
</CardContent>
</Card>
))}
</div>
);
}
+33 -1
View File
@@ -8,7 +8,7 @@ import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api, ApiError, unwrap } from "@/lib/api";
import { ban, setLinkCap, setRole, unban } from "../../actions";
import { ban, decideAccount, setLinkCap, setRole, unban } from "../../actions";
import { ConsoleNav, requireModerator } from "../../console-nav";
export const metadata: Metadata = { title: "Person" };
@@ -35,11 +35,43 @@ export default async function PersonPage({ params }: { params: Promise<{ id: str
joined <DateTime iso={person.createdAt} dateOnly />
</span>
{person.banned && <Tag tone="danger">banned: {person.banReason}</Tag>}
{!person.approved && <Tag tone="strong">waiting for approval</Tag>}
{person.kind === "basic" && <Tag>Discord only: hasn't finished setting up</Tag>}
{person.twoFactor && <Tag>two-factor on</Tag>}
</span>
</PageHeader>
<ConsoleNav />
<div className="space-y-6">
{!person.approved && (
<Card>
<CardHeader>
<CardTitle>Waiting for Approval</CardTitle>
<CardDescription>
{person.email}. Until approved, they can only sign in. Declining deletes the account.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={decideAccount} fields={{ id: person.id }}>
<div className="flex gap-2">
<SubmitButton name="decision" value="approve" pendingLabel="Approving…">
Approve
</SubmitButton>
<SubmitButton
name="decision"
value="decline"
variant="outline"
pendingLabel="Declining…"
confirm={`Decline ${person.username}? Their account is deleted.`}
>
Decline
</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>IMVU accounts</CardTitle>
+42 -14
View File
@@ -11,11 +11,17 @@ import { ConsoleNav, requireModerator } from "../console-nav";
export const metadata: Metadata = { title: "People" };
export default async function People({ searchParams }: { searchParams: Promise<{ q?: string | string[] }> }) {
const raw = (await searchParams).q;
const q = typeof raw === "string" ? raw.slice(0, 64) : "";
await requireModerator(q ? `/console/people?q=${encodeURIComponent(q)}` : "/console/people");
const { people } = unwrap(await api.console.people.get({ query: q ? { q } : {} }));
export default async function People({
searchParams,
}: {
searchParams: Promise<{ q?: string | string[]; waiting?: string | string[] }>;
}) {
const params = await searchParams;
const q = typeof params.q === "string" ? params.q.slice(0, 64) : "";
const waiting = params.waiting === "true";
const query = new URLSearchParams({ ...(q ? { q } : {}), ...(waiting ? { waiting: "true" } : {}) }).toString();
await requireModerator(`/console/people${query ? `?${query}` : ""}`);
const { people } = unwrap(await api.console.people.get({ query: { ...(q ? { q } : {}), ...(waiting ? { waiting: true } : {}) } }));
return (
<>
@@ -23,14 +29,23 @@ export default async function People({ searchParams }: { searchParams: Promise<{
<ConsoleNav />
<Card>
<CardContent className="space-y-6">
<form action="/console/people" className="flex max-w-md gap-2">
<Input type="search" name="q" defaultValue={q} placeholder="T5DE or IMVU username" aria-label="Search" />
<Button type="submit" variant="outline">
Search
</Button>
</form>
<div className="flex flex-wrap items-center gap-4">
<form action="/console/people" className="flex max-w-md flex-1 gap-2">
<Input type="search" name="q" defaultValue={q} placeholder="T5DE or IMVU username" aria-label="Search" />
{waiting && <input type="hidden" name="waiting" value="true" />}
<Button type="submit" variant="outline">
Search
</Button>
</form>
<Link
href={waiting ? "/console/people" : "/console/people?waiting=true"}
className="text-sm text-muted-foreground underline-offset-4 hover:underline"
>
{waiting ? "Show everyone" : "Waiting for approval"}
</Link>
</div>
{people.length === 0 ? (
<p className="text-sm text-muted-foreground">Nobody found.</p>
<p className="text-sm text-muted-foreground">{waiting ? "Nobody is waiting." : "Nobody found."}</p>
) : (
<Table>
<TableHeader>
@@ -50,12 +65,25 @@ export default async function People({ searchParams }: { searchParams: Promise<{
{p.username}
</Link>
</TableCell>
<TableCell className="capitalize">{p.role}</TableCell>
<TableCell>
<span className="capitalize">{p.role}</span>
{p.role !== "user" && !p.twoFactor && (
<span className="ml-2 text-xs text-muted-foreground">no two-factor</span>
)}
</TableCell>
<TableCell className="tabular-nums">{p.linkCap}</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={p.createdAt} dateOnly />
</TableCell>
<TableCell className="text-right">{p.banned && <Tag tone="danger">banned</Tag>}</TableCell>
<TableCell className="text-right">
{p.banned ? (
<Tag tone="danger">banned</Tag>
) : p.kind === "basic" ? (
<Tag>Discord only</Tag>
) : (
!p.approved && <Tag tone="strong">waiting</Tag>
)}
</TableCell>
</TableRow>
))}
</TableBody>
+143
View File
@@ -0,0 +1,143 @@
import type { Metadata } from "next";
import Link from "next/link";
import { RatingTag, StateTags } from "@/components/products";
import { PageHeader } from "@/components/status";
import { DateTime } from "@/components/time";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ActionForm, SubmitButton } from "@/components/forms";
import { api, unwrap } from "@/lib/api";
import { restoreProduct } from "../../products/actions";
import { ConsoleNav, requireConsole } from "../console-nav";
export const metadata: Metadata = { title: "Products" };
const statuses = [
["", "Any status"],
["draft", "Drafts"],
["published", "Published"],
["unlisted", "Unlisted"],
["locked", "Locked"],
["deleted", "Deleted"],
["removed", "Removed"],
] as const;
type Status = Exclude<(typeof statuses)[number][0], "">;
export default async function ConsoleProducts({ searchParams }: { searchParams: Promise<Record<string, string | string[]>> }) {
await requireConsole("/console/products");
const params = await searchParams;
const q = typeof params.q === "string" ? params.q.trim().slice(0, 100) : "";
const status = statuses.find(([s]) => s && s === params.status)?.[0] as Status | undefined;
const all = params.all === "1";
const data = unwrap(
await api.console.products.get({
query: { ...(q ? { q } : {}), ...(status ? { status } : {}), ...(all ? { all: "1" as const } : {}) },
}),
);
const filtered = q !== "" || status !== undefined;
return (
<>
<div className="flex flex-wrap items-start justify-between gap-4">
<PageHeader title="Products">
{data.all ? "Everyone's products, drafts and removed ones included." : "Your products, drafts included."}
</PageHeader>
<Link href="/products/new" className={buttonVariants({ className: "px-4" })}>
New product
</Link>
</div>
<ConsoleNav />
<form action="/console/products" className="mb-6 flex flex-wrap gap-2">
<Input
name="q"
defaultValue={q}
placeholder={data.all ? "Name, ID or creator" : "Name or ID"}
aria-label="Search"
className="max-w-xs"
/>
<NativeSelect name="status" defaultValue={status ?? ""} aria-label="Status" className="w-40">
{statuses.map(([value, label]) => (
<NativeSelectOption key={value} value={value}>
{label}
</NativeSelectOption>
))}
</NativeSelect>
{data.moderator && (
<NativeSelect name="all" defaultValue={all ? "1" : ""} aria-label="Whose" className="w-40">
<NativeSelectOption value="">Yours</NativeSelectOption>
<NativeSelectOption value="1">Everyone&apos;s</NativeSelectOption>
</NativeSelect>
)}
<Button type="submit">Filter</Button>
{(filtered || all) && (
<Link href="/console/products" className={buttonVariants({ variant: "outline" })}>
Clear
</Link>
)}
</form>
<Card>
<CardContent>
{data.products.length === 0 ? (
<p className="text-sm text-muted-foreground">{filtered ? "Nothing matches." : "None yet."}</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
{data.all && <TableHead>Creator</TableHead>}
<TableHead>State</TableHead>
<TableHead className="text-right">Libraries</TableHead>
<TableHead>Changed</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
{data.products.map((p) => (
<TableRow key={p.id}>
<TableCell className="font-medium">
<Link href={`/products/${p.id}`} className="underline-offset-4 hover:underline">
{p.name}
</Link>
</TableCell>
{data.all && <TableCell className="text-muted-foreground">{p.creator}</TableCell>}
<TableCell>
<span className="flex flex-wrap gap-1">
<StateTags product={p} />
<RatingTag rating={p.rating} />
</span>
</TableCell>
<TableCell className="text-right tabular-nums">{p.libraries}</TableCell>
<TableCell className="text-muted-foreground">
<DateTime iso={p.updatedAt} dateOnly />
</TableCell>
<TableCell className="text-right">
{!p.removed ? (
<Link href={`/products/${p.id}/edit`} className={buttonVariants({ size: "sm", variant: "outline" })}>
{p.status === "draft" ? "Review" : "Edit"}
</Link>
) : (
data.moderator && (
<ActionForm action={restoreProduct} fields={{ id: p.id }}>
<div className="flex justify-end gap-2">
<Input name="reason" placeholder="Reason" aria-label="Reason" maxLength={500} className="h-8 w-36" />
<SubmitButton size="sm" variant="outline" pendingLabel="Restoring…" confirm={`Restore ${p.name}?`}>
Restore
</SubmitButton>
</div>
</ActionForm>
)
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</>
);
}
+79
View File
@@ -0,0 +1,79 @@
"use server";
// Imports from the website: asking for an IMVU product, and creators' grants (bring, change, withdraw).
import { revalidatePath } from "next/cache";
import { api, ApiError, unwrap } from "@/lib/api";
import { attempt, field, type ActionState } from "@/lib/actions";
import { productIDs } from "@/lib/imvu";
const done = () => {
revalidatePath("/imports");
revalidatePath("/library");
};
const answers = {
added: "It's in your library.",
queued: "Its creator lets T5DE have it: it'll be in your library once the catalog imports it.",
suggested: "Its creator brings chosen products to T5DE; they'll see you asked for this one.",
counted: "Its creator hasn't brought it to T5DE. Your request is counted, and they'll see it if they do.",
} as const;
/** Someone asks for an IMVU product (an ID or a shop link). */
export async function requestProduct(_: ActionState, form: FormData): Promise<ActionState> {
const ids = productIDs(field(form, "product"));
if (!ids || ids.length !== 1) return { error: "Give one IMVU product ID or shop link." };
return attempt(async () => {
const r = unwrap(await api.imports.requests.post({ imvuProduct: ids[0]! }));
done();
return answers[r.status];
});
}
/** A creator brings their IMVU products to a catalog. */
export async function createGrant(_: ActionState, form: FormData): Promise<ActionState> {
if (form.get("agree") !== "on") return { error: "Agree to the terms to go on." };
const scope = field(form, "scope") === "products" ? "products" : "shop";
const list = productIDs(field(form, scope === "products" ? "products" : "exclude"));
if (!list)
return {
error: "Products are IMVU product IDs or shop links, separated by spaces, commas or lines.",
};
return attempt(async () => {
unwrap(
await api.imports.grants.post({
catalog: field(form, "catalog"),
imvuId: Number(field(form, "imvuId")),
scope,
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
consentVersion: Number(field(form, "consentVersion")),
}),
);
done();
return "Sent. The catalog's team accepts it before anything is imported.";
});
}
/** A creator changes what a grant covers, or withdraws it. */
export async function changeGrant(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
if (field(form, "intent") === "withdraw") {
const r = unwrap(await api.imports.grants({ id }).delete({}));
done();
return r.withdrawn.length ? `Withdrawn. ${r.withdrawn.length} imported products were taken away.` : "Withdrawn.";
}
const scope = field(form, "scope") === "products" ? "products" : "shop";
const list = productIDs(field(form, "list"));
if (!list) throw new ApiError(400, "invalid", "Products are IMVU product IDs or shop links.");
const r = unwrap(
await api.imports.grants({ id }).patch({
...(scope === "products" ? { products: list } : { exclude: list }),
listed: form.get("listed") === "on",
}),
);
done();
return r.withdrawn.length
? `Saved. ${r.withdrawn.length} imported products it no longer covers were taken away.`
: "Saved.";
});
}
+319
View File
@@ -0,0 +1,319 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader, Tag } from "@/components/status";
import { ShopListing } from "@/components/shop-listing";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { api, getMe, unwrap, type ImportGrant } from "@/lib/api";
import { changeGrant, createGrant, requestProduct } from "./actions";
export const metadata: Metadata = { title: "Imports" };
const statusTone = {
pending: "neutral",
active: "online",
declined: "danger",
suspended: "danger",
withdrawn: "neutral",
} as const;
const imvuPage = (id: number) => `https://www.imvu.com/shop/product.php?products_id=${id}`;
export default async function Imports() {
const me = await getMe();
if (!me) redirect("/signin?next=/imports");
const [account, offered, mine] = await Promise.all([
api.account.get().then(unwrap),
api.imports.catalogs.get().then(unwrap),
api.imports.grants.get().then(unwrap),
]);
const asked = await Promise.all(
account.links.map(async (l) => ({
link: l,
requests: unwrap(await api.imports.requests.get({ query: { imvuCreator: l.imvuId } })).requests,
})),
);
const open = mine.grants.filter((g) => g.status !== "withdrawn" && g.status !== "declined");
const ended = mine.grants.filter((g) => g.status === "withdrawn" || g.status === "declined");
return (
<div className="space-y-6">
<PageHeader title="IMVU Imports">
Creators can let T5DE users wear their IMVU products for free: a catalog imports them, with their permission.
</PageHeader>
<Card>
<CardHeader>
<CardTitle>Ask for a Product</CardTitle>
<CardDescription>
An IMVU product you&apos;d like on T5DE. If its creator lets T5DE have it, it comes to your library; if not,
they&apos;ll see that people asked.
</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={requestProduct}>
<div className="flex max-w-xl flex-wrap gap-2">
<Input
name="product"
required
placeholder="IMVU product ID or shop link"
aria-label="IMVU product"
className="min-w-64 flex-1"
/>
<SubmitButton pendingLabel="Asking…">Ask</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
{open.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Your Products on T5DE</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
{open.map((g) => (
<GrantRow key={g.id} grant={g} />
))}
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Bring Your IMVU Products</CardTitle>
<CardDescription>
Made products on IMVU? Choose a catalog to host them. Its team accepts first; then T5DE users can wear them
for free, and you can change what&apos;s included or stop any time.
</CardDescription>
</CardHeader>
<CardContent>
{account.links.length === 0 ? (
<p className="text-sm text-muted-foreground">
First{" "}
<Link href="/account" className="text-foreground underline underline-offset-4">
link your IMVU account
</Link>
, the one that made the products.
</p>
) : offered.catalogs.length === 0 ? (
<p className="text-sm text-muted-foreground">No catalog takes imports yet.</p>
) : (
<ActionForm
action={createGrant}
fields={{ consentVersion: offered.consent.version }}
className="max-w-2xl space-y-4"
>
<div className="grid gap-4 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="imvuId">Your IMVU account</FieldLabel>
<NativeSelect id="imvuId" name="imvuId">
{account.links.map((l) => (
<NativeSelectOption key={l.imvuId} value={l.imvuId}>
{l.username}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
<Field>
<FieldLabel htmlFor="catalog">Catalog</FieldLabel>
<NativeSelect id="catalog" name="catalog">
{offered.catalogs.map((c) => (
<NativeSelectOption key={c.id} value={c.id}>
{c.name}
</NativeSelectOption>
))}
</NativeSelect>
</Field>
</div>
<fieldset className="space-y-2">
<legend className="mb-2 text-sm font-medium">What to bring</legend>
<label className="flex items-start gap-2 text-sm">
<input type="radio" name="scope" value="shop" defaultChecked className="mt-1" />
<span>
My whole shop, including new products
<span className="block text-muted-foreground">Leave some out below (optional).</span>
</span>
</label>
<label className="flex items-start gap-2 text-sm">
<input type="radio" name="scope" value="products" className="mt-1" />
<span>
Only the products I list
<span className="block text-muted-foreground">List them below; you can add more later.</span>
</span>
</label>
</fieldset>
<Field>
<FieldLabel htmlFor="exclude">Leave out (whole shop)</FieldLabel>
<Textarea
id="exclude"
name="exclude"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<Field>
<FieldLabel htmlFor="products">Products (only these)</FieldLabel>
<Textarea
id="products"
name="products"
rows={2}
placeholder="IMVU product IDs or shop links"
className="font-mono text-xs"
/>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked />
Listed (shown in search and on your page; unlisted ones work by link)
</label>
<div className="rounded-md border bg-muted/40 p-3 text-sm">
<p>{offered.consent.text}</p>
<label className="mt-3 flex items-center gap-2 font-medium">
<input type="checkbox" name="agree" required />I agree
</label>
</div>
<SubmitButton pendingLabel="Sending…">Send to the catalog</SubmitButton>
</ActionForm>
)}
</CardContent>
</Card>
{asked.some((a) => a.requests.length > 0) && (
<Card>
<CardHeader>
<CardTitle>What People Asked For</CardTitle>
<CardDescription>Your IMVU products that T5DE users would like.</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{asked
.filter((a) => a.requests.length > 0)
.map((a) => (
<div key={a.link.imvuId}>
<p className="mb-2 text-sm font-medium">{a.link.username}</p>
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead className="text-right">People</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{a.requests.slice(0, 20).map((r) => (
<TableRow key={r.imvuProduct}>
<TableCell>
{r.imvuProduct === 0 ? (
"Your whole shop"
) : (
<a
href={imvuPage(r.imvuProduct)}
className="underline-offset-4 hover:underline"
target="_blank"
rel="noreferrer"
>
{r.name || r.imvuProduct}
</a>
)}
</TableCell>
<TableCell className="text-right tabular-nums">{r.requests}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
))}
</CardContent>
</Card>
)}
{ended.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">Ended</summary>
<ul className="mt-2 divide-y">
{ended.map((g) => (
<li key={g.id} className="py-2">
{g.imvuName || g.imvuId} → {g.catalogName} <Tag tone={statusTone[g.status]}>{g.status}</Tag>{" "}
<span className="text-muted-foreground">{g.statusReason}</span>
</li>
))}
</ul>
</details>
)}
</div>
);
}
function GrantRow({ grant: g }: { grant: ImportGrant }) {
const list = g.scope === "products" ? g.products : g.exclude;
return (
<div className="space-y-3 border-b pb-6 last:border-b-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{g.imvuName || g.imvuId}</span>
<span className="text-muted-foreground">to</span>
<span className="font-medium">{g.catalogName}</span>
<Tag tone={statusTone[g.status]}>{g.status === "pending" ? "waiting for the catalog" : g.status}</Tag>
<span className="text-xs text-muted-foreground">
since <DateTime iso={g.createdAt} dateOnly />
</span>
</div>
{g.statusReason && <p className="text-sm text-muted-foreground">{g.statusReason}</p>}
<p className="text-sm">
{g.scope === "shop"
? `Your whole shop${g.exclude.length ? `, less ${g.exclude.length} left out` : ""}.`
: `${g.products.length} chosen product${g.products.length === 1 ? "" : "s"}.`}{" "}
{g.listed ? "Listed." : "Unlisted."}
<ShopListing grant={g} />
</p>
{g.status === "suspended" ? (
<p className="text-sm text-muted-foreground">Withdraw it, then bring your products again to start over.</p>
) : null}
<ActionForm action={changeGrant} fields={{ id: g.id, scope: g.scope }} className="max-w-2xl space-y-2">
{g.status !== "suspended" && (
<>
<Field>
<FieldLabel htmlFor={`list-${g.id}`}>{g.scope === "shop" ? "Left out" : "Products"}</FieldLabel>
<Textarea
id={`list-${g.id}`}
name="list"
rows={2}
defaultValue={list.join("\n")}
className="font-mono text-xs"
/>
<FieldDescription>
{g.scope === "shop"
? "Products left out that were imported are taken away from everyone."
: "Products taken off the list that were imported are taken away from everyone."}
</FieldDescription>
</Field>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="listed" defaultChecked={g.listed} />
Listed
</label>
</>
)}
<div className="flex flex-wrap gap-2">
{g.status !== "suspended" && (
<SubmitButton name="intent" value="save" variant="outline" pendingLabel="Saving…">
Save
</SubmitButton>
)}
<SubmitButton
name="intent"
value="withdraw"
variant="outline"
pendingLabel="Withdrawing…"
confirm="Withdraw? Your imported products are taken away from everyone who has them."
>
Withdraw
</SubmitButton>
</div>
</ActionForm>
</div>
);
}
+22 -2
View File
@@ -1,7 +1,10 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Header } from "@/components/header";
import { NarrowCard } from "@/components/narrow-card";
import { StagingBanner } from "@/components/staging-banner";
import { getMe } from "@/lib/api";
import { FinishSetupForm } from "./account/finish-setup-form";
import { cn } from "@/lib/utils";
import "./globals.css";
@@ -13,13 +16,30 @@ export const metadata: Metadata = {
description: "One account for all your IMVU avatars.",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const me = await getMe();
return (
<html lang="en" className={cn("font-sans antialiased", sans.variable, mono.variable)}>
<body className="flex min-h-dvh flex-col">
<StagingBanner />
<Header />
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-10 sm:px-6 sm:py-14">{children}</main>
<main className="mx-auto w-full max-w-5xl flex-1 px-4 py-10 sm:px-6 sm:py-14">
{me?.kind === "basic" ? (
<NarrowCard
title="Finish Setting Up Your Account"
description={`You're signed in with Discord as ${me.username}. Choose a username and password to use the hub; T5DE's other sites already work with your Discord sign-in.`}
>
<FinishSetupForm />
</NarrowCard>
) : me && !me.approved ? (
<NarrowCard
title="Waiting for Approval"
description={`Thanks for signing up, ${me.username}. A moderator will approve your account soon; until then you can't use the hub.`}
/>
) : (
children
)}
</main>
<footer className="border-t">
<div className="mx-auto max-w-5xl px-4 py-6 text-sm text-muted-foreground sm:px-6">
T5DE is unofficial: not made by or affiliated with IMVU.
+127
View File
@@ -0,0 +1,127 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { caseKinds } from "@/components/cases";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader } from "@/components/status";
import { DateTime } from "@/components/time";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { api, getMe, unwrap, type NotificationEntry } from "@/lib/api";
import { cn } from "@/lib/utils";
import { markAllRead } from "../console/cases/actions";
export const metadata: Metadata = { title: "Notifications" };
export default async function Notifications({ searchParams }: { searchParams: Promise<{ before?: string | string[] }> }) {
const me = await getMe();
if (!me) redirect("/signin?next=/notifications");
const raw = (await searchParams).before;
const before = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : undefined;
const data = unwrap(await api.notifications.get({ query: before ? { before } : {} }));
return (
<>
<div className="flex flex-wrap items-start justify-between gap-4">
<PageHeader title="Notifications">
{data.unread > 0 ? `${data.unread} unread.` : "You're up to date."}
</PageHeader>
{data.unread > 0 && (
<ActionForm action={markAllRead}>
<SubmitButton variant="outline" pendingLabel="Marking…">
Mark all as read
</SubmitButton>
</ActionForm>
)}
</div>
<Card>
<CardContent>
{data.notifications.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing yet.</p>
) : (
<ul className="divide-y">
{data.notifications.map((n) => {
const { text, href } = describe(n);
return (
<li key={n.id} className={cn("flex flex-wrap items-baseline gap-x-3 gap-y-1 py-3 first:pt-0 last:pb-0", n.read && "text-muted-foreground")}>
{!n.read && <span className="size-2 shrink-0 self-center rounded-full bg-foreground" aria-label="Unread" />}
<span className="min-w-0 flex-1 text-sm">
{href ? (
<Link href={href} className="underline-offset-4 hover:underline">
{text}
</Link>
) : (
text
)}
</span>
<span className="text-xs text-muted-foreground">
<DateTime iso={n.at} />
</span>
</li>
);
})}
</ul>
)}
</CardContent>
</Card>
{data.before && (
<div className="mt-4">
<Link href={`/notifications?before=${data.before}`} className={buttonVariants({ variant: "outline" })}>
Older
</Link>
</div>
)}
</>
);
}
/** A notification in words, and where it leads. */
function describe(n: NotificationEntry): { text: string; href?: string } {
const d = n.data as Record<string, unknown>;
const s = (k: string) => (typeof d[k] === "string" ? (d[k] as string) : "");
const why = s("reason") ? `: “${s("reason")}”` : "";
switch (n.type) {
case "product_edited": {
const what =
s("kind") === "lock"
? "changed the locks on"
: s("kind") === "revert"
? "undid a change to"
: `changed the ${(d.fields as string[] | undefined)?.join(", ") ?? "info"} of`;
return { text: `${s("by") || "A moderator"} ${what} ${s("name")}${why}`, href: `/products/${s("product")}/edit` };
}
case "product_removed":
return { text: `Moderation removed ${s("name")}${why}. You can appeal it from your audit log.`, href: `/console/audit?product=${s("product")}` };
case "product_restored":
return { text: `Moderation restored ${s("name")}${why}`, href: `/products/${s("product")}` };
case "case_decided": {
const status = s("status") === "resolved" ? "resolved" : "declined";
const res = s("resolution") ? `: “${s("resolution")}”` : "";
return { text: `Your ${caseKinds[s("kind")]?.toLowerCase() ?? "case"} was ${status}${res}`, href: `/console/cases/${d.case}` };
}
case "case_note":
return { text: `${s("by") || "Someone"} replied on your ${caseKinds[s("kind")]?.toLowerCase() ?? "case"}`, href: `/console/cases/${d.case}` };
case "membership_decided": {
const status = s("status");
const text =
status === "member"
? `You're a member of ${s("name")}`
: status === "banned"
? `${s("name")} banned you`
: `${s("name")} declined your request to join`;
return { text, href: `/catalogs/${s("catalog")}` };
}
case "import_grant_decided":
return {
text:
s("decision") === "accept"
? `${s("name")} accepted importing your IMVU products`
: `${s("name")} declined importing your IMVU products${why}`,
href: "/imports",
};
case "import_grant_ended":
return { text: `${s("name")} stopped importing your IMVU products${why}`, href: "/imports" };
default:
return { text: n.type };
}
}
+272 -20
View File
@@ -2,44 +2,100 @@ import type { Metadata } from "next";
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ActionForm, SubmitButton } from "@/components/forms";
import { PageHeader } from "@/components/status";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { StateTags } from "@/components/products";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Textarea } from "@/components/ui/textarea";
import { UploadCard } from "@/components/upload-card";
import { getMe } from "@/lib/api";
import { saveProduct } from "../../actions";
import { api, getMe, unwrap, type InfoEntry } from "@/lib/api";
import { publishProduct, revertInfo, saveLocks, saveProduct } from "../../actions";
import { loadProduct } from "../../load";
export const metadata: Metadata = { title: "Edit product" };
const fieldNames: Record<string, string> = {
name: "Name",
description: "Description",
rating: "Rating",
tags: "Tags",
listed: "Listed",
category: "Category",
locked: "Locks",
status: "Status",
};
export default async function EditProduct({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const me = await getMe();
if (!me) redirect(`/signin?next=/products/${id}/edit`);
const { product, mine } = await loadProduct(id);
if (!mine) notFound();
const { product, mine, permissions } = await loadProduct(id);
const can = (p: string) => (permissions as string[]).includes(p);
if (!can("product:edit")) notFound();
if (mine && product.deleted) redirect(`/products/${id}`);
const [{ entries }, { choices, parent }] = await Promise.all([
api.products({ id }).history.get().then(unwrap),
api.products({ id }).categories.get().then(unwrap),
]);
const path = (c: { name: string }[]) => c.map((x) => x.name).join(" › ");
const editLocked = can("product:edit-locked");
const locked = (f: string) => product.locked.includes(f) && !editLocked;
const draft = product.status === "draft";
return (
<div className="space-y-6">
<PageHeader title={`Edit ${product.name}`}>
<Link href={`/products/${id}`} className="underline-offset-4 hover:underline">
Back to the product
</Link>
<PageHeader title={draft ? `Review ${product.name}` : `Edit ${product.name}`}>
<span className="flex flex-wrap items-center gap-2">
<StateTags product={product} />
<Link href={`/products/${id}`} className="underline-offset-4 hover:underline">
{draft ? "Preview its page" : "Back to the product"}
</Link>
</span>
</PageHeader>
{draft && (
<Card>
<CardHeader>
<CardTitle>Draft</CardTitle>
<CardDescription>
Only you and moderators see it. Check its info below, then publish it so people can get it. Drafts not
published within 30 days are deleted.
</CardDescription>
</CardHeader>
{can("product:publish") && (
<CardContent>
<ActionForm action={publishProduct} fields={{ id }}>
<SubmitButton pendingLabel="Publishing…">Publish</SubmitButton>
</ActionForm>
</CardContent>
)}
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Info</CardTitle>
{!mine && <CardDescription>You&apos;re editing someone else&apos;s product: they see your reason.</CardDescription>}
</CardHeader>
<CardContent>
<ActionForm action={saveProduct} fields={{ id }}>
<FieldGroup>
<Field>
<FieldLabel htmlFor="name">Name</FieldLabel>
<Input id="name" name="name" defaultValue={product.name} required maxLength={64} className="max-w-md" />
<Input
id="name"
name="name"
defaultValue={product.name}
required
maxLength={64}
disabled={locked("name")}
className="max-w-md"
/>
{locked("name") && <LockedNote />}
</Field>
<Field>
<FieldLabel htmlFor="description">Description</FieldLabel>
@@ -49,22 +105,103 @@ export default async function EditProduct({ params }: { params: Promise<{ id: st
defaultValue={product.description}
maxLength={20000}
rows={8}
disabled={locked("description")}
className="font-mono text-xs md:text-xs"
/>
<FieldDescription>HTML, as on IMVU. Scripts and unsafe tags are removed.</FieldDescription>
{locked("description") ? (
<LockedNote />
) : (
<FieldDescription>HTML, as on IMVU. Scripts and unsafe tags are removed.</FieldDescription>
)}
</Field>
<Field>
<FieldLabel htmlFor="rating">Rating</FieldLabel>
{product.rating === "adult" ? (
<p className="text-sm">Adult</p>
<FieldLabel htmlFor="tags">Tags</FieldLabel>
<Input
id="tags"
name="tags"
defaultValue={product.tags.join(", ")}
maxLength={300}
disabled={locked("tags")}
placeholder="formal, wool, winter"
className="max-w-md"
/>
{locked("tags") ? <LockedNote /> : <FieldDescription>Up to 10, separated by commas.</FieldDescription>}
</Field>
<Field>
<FieldLabel htmlFor="category">Category</FieldLabel>
{locked("category") || choices.length === 0 ? (
<p className="text-sm">{product.categories.length ? path(product.categories) : "None known"}</p>
) : (
<NativeSelect id="rating" name="rating" defaultValue="general" className="w-48">
<NativeSelectOption value="general">General</NativeSelectOption>
<NativeSelectOption value="adult">Adult</NativeSelectOption>
<NativeSelect
id="category"
name="category"
defaultValue={String(product.category?.at(-1)?.id ?? "")}
className="w-full max-w-md"
>
<NativeSelectOption value="">
{parent.length ? `Its parent's: ${path(parent)}` : "None"}
</NativeSelectOption>
{choices
.filter((c) => c.at(-1)!.id !== parent.at(-1)?.id)
.map((c) => (
<NativeSelectOption key={c.at(-1)!.id} value={String(c.at(-1)!.id)}>
{path(c)}
</NativeSelectOption>
))}
</NativeSelect>
)}
<FieldDescription>Raising it to adult is immediate; lowering it needs review.</FieldDescription>
{locked("category") ? (
<LockedNote />
) : (
<FieldDescription>
Where it&apos;s filed in the shop and inventory: any category T5DE has seen, within its parent&apos;s
kind of product.
</FieldDescription>
)}
</Field>
<div className="grid gap-6 sm:grid-cols-2">
<Field>
<FieldLabel htmlFor="rating">Rating</FieldLabel>
{locked("rating") ? (
<p className="text-sm capitalize">{product.rating}</p>
) : (
<NativeSelect id="rating" name="rating" defaultValue={product.rating} className="w-48">
<NativeSelectOption value="general">General</NativeSelectOption>
<NativeSelectOption value="adult">Adult</NativeSelectOption>
</NativeSelect>
)}
{locked("rating") ? (
<LockedNote />
) : (
<FieldDescription>
Raising it to adult is immediate; {can("product:rate-lower") ? "lowering it is too." : "lowering it asks moderators."}
</FieldDescription>
)}
</Field>
<Field>
<FieldLabel htmlFor="listed">Listing</FieldLabel>
{locked("listed") ? (
<p className="text-sm">{product.listed ? "Listed" : "Unlisted"}</p>
) : (
<NativeSelect id="listed" name="listed" defaultValue={product.listed ? "yes" : "no"} className="w-48">
<NativeSelectOption value="yes">Listed</NativeSelectOption>
<NativeSelectOption value="no">Unlisted</NativeSelectOption>
</NativeSelect>
)}
{locked("listed") ? (
<LockedNote />
) : (
<FieldDescription>Unlisted: left out of search and lists; its link still works.</FieldDescription>
)}
</Field>
</div>
{!mine && (
<Field>
<FieldLabel htmlFor="reason">Reason</FieldLabel>
<Input id="reason" name="reason" required maxLength={500} className="max-w-md" />
<FieldDescription>Shown to the creator in the product&apos;s history.</FieldDescription>
</Field>
)}
<div>
<SubmitButton pendingLabel="Saving…">Save</SubmitButton>
</div>
@@ -73,7 +210,122 @@ export default async function EditProduct({ params }: { params: Promise<{ id: st
</CardContent>
</Card>
<UploadCard title="Upload a new revision" product={id} />
{can("product:lock") && (
<Card>
<CardHeader>
<CardTitle>Locks</CardTitle>
<CardDescription>Locked fields can only be changed by moderators.</CardDescription>
</CardHeader>
<CardContent>
<ActionForm action={saveLocks} fields={{ id }}>
<div className="flex flex-wrap gap-4">
{(["name", "description", "rating", "tags", "listed", "category"] as const).map((f) => (
<label key={f} className="flex items-center gap-2 text-sm">
<input
type="checkbox"
name="locked"
value={f}
defaultChecked={product.locked.includes(f)}
className="size-4 accent-foreground"
/>
{fieldNames[f]}
</label>
))}
</div>
<div className="flex flex-wrap gap-2">
<Input name="reason" required maxLength={500} placeholder="Reason" aria-label="Reason" className="max-w-sm" />
<SubmitButton variant="outline" pendingLabel="Saving…">
Save locks
</SubmitButton>
</div>
</ActionForm>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>History</CardTitle>
<CardDescription>Every change to its info, with who made it and why.</CardDescription>
</CardHeader>
<CardContent>
{entries.length === 0 ? (
<p className="text-sm text-muted-foreground">No changes yet.</p>
) : (
<ul className="divide-y">
{entries.map((e) => (
<HistoryRow key={e.id} id={id} entry={e} mine={mine} canRevert={can("product:edit")} />
))}
</ul>
)}
</CardContent>
</Card>
{mine && <UploadCard title="Upload a new revision" product={id} />}
</div>
);
}
function LockedNote() {
return <FieldDescription>Locked by a moderator.</FieldDescription>;
}
/** A value as the history shows it. */
function shown(field: string, v: unknown): string {
if (field === "listed") return v ? "listed" : "unlisted";
if (field === "category")
return Array.isArray(v) ? v.map((c: { name?: string }) => c.name ?? "").join(" › ") : "its parent's";
if (Array.isArray(v)) return v.length ? v.join(", ") : "none";
if (typeof v === "string") return v || "empty";
return String(v);
}
function HistoryRow({ id, entry: e, mine, canRevert }: { id: string; entry: InfoEntry; mine: boolean; canRevert: boolean }) {
const what =
e.kind === "publish" ? "published it" : e.kind === "lock" ? "changed the locks" : e.kind === "revert" ? "undid a change" : "edited";
return (
<li className="space-y-2 py-4 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="font-medium">{e.by || "Someone"}</span>
{!e.byCreator && <Tag>Moderator</Tag>}
<span className="text-muted-foreground">{what}</span>
<span className="text-muted-foreground">
<DateTime iso={e.at} />
</span>
</div>
{e.reason && <p className="text-sm">Reason: {e.reason}</p>}
{e.kind !== "publish" && (
<ul className="space-y-1 text-sm text-muted-foreground">
{Object.entries(e.changes).map(([field, c]) => (
<li key={field}>
<span className="text-foreground">{fieldNames[field] ?? field}</span>
{field === "description" ? (
<details className="mt-1">
<summary className="cursor-pointer hover:text-foreground">Before and after</summary>
<pre className="mt-1 max-h-48 overflow-auto rounded-md bg-muted p-2 text-xs whitespace-pre-wrap">
{shown(field, c.from)}
</pre>
<pre className="mt-1 max-h-48 overflow-auto rounded-md bg-muted p-2 text-xs whitespace-pre-wrap">
{shown(field, c.to)}
</pre>
</details>
) : (
<>
: {shown(field, c.from)} → {shown(field, c.to)}
</>
)}
</li>
))}
</ul>
)}
{canRevert && (e.kind === "edit" || e.kind === "revert") && (
<ActionForm action={revertInfo} fields={{ id, entry: e.id }} className="flex flex-wrap items-center gap-2 space-y-0">
{!mine && <Input name="reason" required maxLength={500} placeholder="Reason" aria-label="Reason" className="h-8 max-w-xs" />}
<SubmitButton size="sm" variant="outline" pendingLabel="Undoing…">
Undo
</SubmitButton>
</ActionForm>
)}
</li>
);
}
+69 -8
View File
@@ -1,7 +1,8 @@
import type { Metadata } from "next";
import Link from "next/link";
import { ActionForm, SubmitButton } from "@/components/forms";
import { formatSize, ProductImage, RatingTag } from "@/components/products";
import { ReportForm } from "@/components/cases";
import { formatSize, ProductImage, RatingTag, StateTags } from "@/components/products";
import { PageHeader, Tag } from "@/components/status";
import { DateTime } from "@/components/time";
import { buttonVariants } from "@/components/ui/button";
@@ -19,8 +20,9 @@ export async function generateMetadata({ params }: { params: Promise<{ id: strin
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const [me, data] = await Promise.all([getMe(), loadProduct(id)]);
const { product, revisions, inLibrary, stayOn, mine } = data;
const { product, revisions, inLibrary, stayOn, mine, available, catalogs, permissions } = data;
const using = inLibrary ? inUse(revisions, stayOn ?? product.latest) : undefined;
const draft = product.status === "draft";
return (
<div className="space-y-6">
@@ -28,10 +30,30 @@ export default async function ProductPage({ params }: { params: Promise<{ id: st
<span className="flex flex-wrap items-center gap-2">
{product.creator && <span>by {product.creator}</span>}
<RatingTag rating={product.rating} />
{product.deleted && <Tag tone="danger">deleted</Tag>}
{/* Its state (draft, unlisted, locks) is for those who manage it; anyone may see that it's deleted. */}
{permissions.includes("product:edit") ? (
<StateTags product={product} />
) : (
product.deleted && <Tag tone="danger">Deleted</Tag>
)}
</span>
</PageHeader>
{draft && (
<p className="text-sm text-muted-foreground">
A draft: only {mine ? "you" : "its creator"} and moderators see it, and nobody can get it until it&apos;s
published.{" "}
{permissions.includes("product:publish") && (
<Link href={`/products/${id}/edit`} className="font-medium text-foreground underline-offset-4 hover:underline">
Review and publish
</Link>
)}
</p>
)}
{!draft && !product.listed && mine && (
<p className="text-sm text-muted-foreground">Unlisted: it&apos;s not in search or lists, but anyone with its link can get it.</p>
)}
{product.deleted && (
<p className="text-sm text-muted-foreground">
{mine ? "You deleted this product." : "Its creator deleted this product."} People who have it keep it.
@@ -51,8 +73,20 @@ export default async function ProductPage({ params }: { params: Promise<{ id: st
</div>
)}
{product.tags.length > 0 && (
<ul className="flex flex-wrap gap-1.5" aria-label="Tags">
{product.tags.map((t) => (
<li key={t}>
<Link href={`/products?tag=${encodeURIComponent(t)}`} className="hover:opacity-80">
<Tag>{t}</Tag>
</Link>
</li>
))}
</ul>
)}
<div className="flex flex-wrap items-center gap-2">
{product.deleted && !inLibrary ? null : me ? (
{draft || (product.deleted && !inLibrary) ? null : me ? (
<ActionForm action={libraryAction} fields={{ id }} className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
{inLibrary ? (
@@ -62,10 +96,24 @@ export default async function ProductPage({ params }: { params: Promise<{ id: st
Remove
</SubmitButton>
</>
) : (
) : available ? (
<SubmitButton name="intent" value="get" pendingLabel="Getting…">
Get
</SubmitButton>
) : (
<span className="text-sm text-muted-foreground">
Members only. Join{" "}
{catalogs.map((c, i) => (
<span key={c.id}>
{i > 0 && (i === catalogs.length - 1 ? " or " : ", ")}
<Link href={`/catalogs/${c.id}`} className="font-medium text-foreground underline-offset-4 hover:underline">
{c.name}
</Link>
{c.joined === "requested" && " (asked)"}
</span>
))}{" "}
to get it.
</span>
)}
</div>
</ActionForm>
@@ -74,11 +122,13 @@ export default async function ProductPage({ params }: { params: Promise<{ id: st
Sign in to get it
</Link>
)}
{permissions.includes("product:edit") && !(mine && product.deleted) && (
<Link href={`/products/${id}/edit`} className={buttonVariants({ variant: "outline" })}>
{mine ? "Edit" : "Edit info"}
</Link>
)}
{mine && !product.deleted && (
<>
<Link href={`/products/${id}/edit`} className={buttonVariants({ variant: "outline" })}>
Edit
</Link>
<ActionForm action={deleteProduct} fields={{ id }}>
<SubmitButton
variant="outline"
@@ -101,6 +151,8 @@ export default async function ProductPage({ params }: { params: Promise<{ id: st
</Card>
)}
{me && !mine && !draft && <ReportForm about="product" id={id} />}
{isModerator(me) && (
<Card>
<CardHeader>
@@ -137,6 +189,7 @@ export default async function ProductPage({ params }: { params: Promise<{ id: st
stayOn={stayOn}
using={using === r.number}
mine={mine}
canBlock={permissions.includes("product:remove")}
/>
))}
</ul>
@@ -160,6 +213,7 @@ function RevisionRow({
stayOn,
using,
mine,
canBlock,
}: {
id: string;
revision: Revision;
@@ -168,6 +222,8 @@ function RevisionRow({
stayOn: number | null;
using: boolean;
mine: boolean;
/** Moderators: each file links to blocking it. */
canBlock: boolean;
}) {
const facts = [
formatSize(r.size),
@@ -195,6 +251,11 @@ function RevisionRow({
<li key={f.name} className="flex gap-3">
<span className="min-w-0 flex-1 truncate">{f.name}</span>
<span className="text-muted-foreground tabular-nums">{formatSize(f.size)}</span>
{canBlock && (
<Link href={`/console/blocks/${f.sha256}`} className="text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
Block
</Link>
)}
</li>
))}
</ul>
+77 -5
View File
@@ -56,6 +56,18 @@ export async function removeProduct(_: ActionState, form: FormData): Promise<Act
redirect("/products");
}
/** Moderation restores a removed product. */
export async function restoreProduct(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
unwrap(await api.products({ id }).unremove.post({ reason: field(form, "reason") }));
done(id);
revalidatePath("/products");
revalidatePath("/console/products");
return "Restored.";
});
}
export async function retract(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
@@ -64,24 +76,84 @@ export async function retract(_: ActionState, form: FormData): Promise<ActionSta
});
}
/** Saves a product's info. Fields left out of the form (locked ones are disabled) aren't changed. */
export async function saveProduct(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
const has = (name: string) => form.has(name);
const rating = field(form, "rating");
const state = await attempt(async () => {
unwrap(
const listed = field(form, "listed");
return attempt(async () => {
const { fields, review } = unwrap(
await api.products({ id }).patch({
name: field(form, "name"),
description: typeof form.get("description") === "string" ? String(form.get("description")) : "",
...(rating === "adult" ? { rating: "adult" as const } : {}),
...(has("name") ? { name: field(form, "name") } : {}),
...(has("description") ? { description: String(form.get("description") ?? "") } : {}),
...(rating === "adult" || rating === "general" ? { rating } : {}),
...(has("tags")
? {
tags: field(form, "tags")
.split(",")
.map((t) => t.trim())
.filter(Boolean),
}
: {}),
...(listed === "yes" || listed === "no" ? { listed: listed === "yes" } : {}),
...(has("category") ? { category: Number(field(form, "category")) || null } : {}),
...(field(form, "reason") ? { reason: field(form, "reason") } : {}),
}),
);
done(id);
revalidatePath("/products");
revalidatePath(`/products/${id}/edit`);
if (review) return `${fields.length ? "Saved. " : ""}Moderators will review lowering the rating (case #${review}).`;
return fields.length ? "Saved." : "Nothing changed.";
});
}
export async function publishProduct(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
const state = await attempt(async () => {
unwrap(await api.products({ id }).publish.post());
done(id);
revalidatePath("/products");
revalidatePath("/console/products");
});
if (state?.error) return state;
redirect(`/products/${id}`);
}
/** Moderators lock fields: the checked ones are locked, the rest unlocked. */
export async function saveLocks(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
const fields = form
.getAll("locked")
.filter((v): v is "name" | "description" | "rating" | "tags" | "listed" | "category" =>
["name", "description", "rating", "tags", "listed", "category"].includes(String(v)),
);
return attempt(async () => {
unwrap(await api.products({ id }).locks.put({ fields, reason: field(form, "reason") }));
done(id);
revalidatePath(`/products/${id}/edit`);
return "Locks saved.";
});
}
/** Puts back what a history entry changed. */
export async function revertInfo(_: ActionState, form: FormData): Promise<ActionState> {
const id = field(form, "id");
return attempt(async () => {
const reason = field(form, "reason");
unwrap(
await api
.products({ id })
.history({ entry: Number(field(form, "entry")) })
.revert.post(reason ? { reason } : {}),
);
done(id);
revalidatePath(`/products/${id}/edit`);
return "Undone.";
});
}
/** An upload token and the catalog's upload address, for the browser to send the file there itself. */
export async function startUpload(
catalog: string,
+1 -1
View File
@@ -13,7 +13,7 @@ export default async function NewProduct() {
return (
<div className="space-y-6">
<PageHeader title="New product">
Upload it to a catalog. You can edit its info after.{" "}
Upload it to a catalog. Then check its info and publish it.{" "}
<Link href="/products" className="underline-offset-4 hover:underline">
Back to products
</Link>
+22 -6
View File
@@ -8,15 +8,29 @@ import { api, getMe, unwrap } from "@/lib/api";
export const metadata: Metadata = { title: "Products" };
export default async function Products({ searchParams }: { searchParams: Promise<{ q?: string | string[] }> }) {
const raw = (await searchParams).q;
const q = typeof raw === "string" ? raw.trim().slice(0, 100) : "";
const [me, { products }] = await Promise.all([getMe(), api.products.get({ query: q ? { q } : {} }).then(unwrap)]);
export default async function Products({
searchParams,
}: {
searchParams: Promise<{ q?: string | string[]; creator?: string | string[]; tag?: string | string[] }>;
}) {
const params = await searchParams;
const one = (v: string | string[] | undefined, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
const q = one(params.q, 100);
const creator = one(params.creator, 64);
const tag = one(params.tag, 24);
const [me, { products }] = await Promise.all([
getMe(),
api.products
.get({ query: { ...(q ? { q } : {}), ...(creator ? { creator } : {}), ...(tag ? { tag } : {}) } })
.then(unwrap),
]);
return (
<>
<div className="flex flex-wrap items-start justify-between gap-4">
<PageHeader title="Products">Community products for T5DE.</PageHeader>
<PageHeader title="Products">
{[creator && `By ${creator}.`, tag && `Tagged “${tag}”.`].filter(Boolean).join(" ") || "Community products for T5DE."}
</PageHeader>
{me && (
<Link href="/products/new" className={buttonVariants({ className: "px-4" })}>
New product
@@ -25,12 +39,14 @@ export default async function Products({ searchParams }: { searchParams: Promise
</div>
<form action="/products" className="mb-6 flex w-full max-w-md gap-2">
<Input type="search" name="q" defaultValue={q} placeholder="Search products" aria-label="Search" />
{creator && <input type="hidden" name="creator" value={creator} />}
{tag && <input type="hidden" name="tag" value={tag} />}
<Button type="submit" variant="outline">
Search
</Button>
</form>
{products.length === 0 ? (
<Empty>{q ? "Nothing found." : "No products yet."}</Empty>
<Empty>{q || tag || creator ? "Nothing found." : "No products yet."}</Empty>
) : (
<ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{products.map((p) => (
+36 -5
View File
@@ -1,18 +1,49 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { DiscordButton } from "@/components/discord-button";
import { ErrorText } from "@/components/forms";
import { NarrowCard } from "@/components/narrow-card";
import { getMe } from "@/lib/api";
import { Separator } from "@/components/ui/separator";
import { api, getMe, unwrap } from "@/lib/api";
import { discordError } from "@/lib/discord";
import { continueURL, requestedProvider, requestingClient } from "@/lib/oauth";
import { safeNext } from "@/lib/paths";
import { SignInForm } from "./signin-form";
export const metadata: Metadata = { title: "Sign in" };
export default async function SignIn({ searchParams }: { searchParams: Promise<{ next?: string | string[] }> }) {
const next = safeNext((await searchParams).next);
export default async function SignIn({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const params = await searchParams;
// Opened for another T5DE site (Music): back to it once signed in.
const forSite = continueURL(params);
const next = forSite ?? safeNext(params.next);
if (await getMe()) redirect(next);
const { discord } = unwrap(await api.hub.get());
const clientId = requestingClient(params);
const site = forSite && clientId ? (await api.oauth.clients({ clientId }).get()).data : undefined;
const siteName = site && "client" in site ? site.client.name : undefined;
const error = discordError(params.error);
// The site asked for Discord (its "Sign in with Discord" button): go straight there, unless that just failed.
const autoDiscord = discord && forSite !== undefined && requestedProvider(params) === "discord" && !error;
return (
<NarrowCard title="Sign in" description="to your T5DE account.">
<SignInForm next={next} />
<NarrowCard
title="Sign in"
description={siteName ? `with your T5DE account to continue to ${siteName}.` : "to your T5DE account."}
>
<div className="space-y-6">
{error && <ErrorText>{error}</ErrorText>}
{discord && (
<>
<DiscordButton mode="sign-in" next={next} auto={autoDiscord} />
<div className="flex items-center gap-3 text-xs text-muted-foreground">
<Separator className="flex-1" />
or with your username
<Separator className="flex-1" />
</div>
</>
)}
<SignInForm next={next} />
</div>
</NarrowCard>
);
}
+95 -31
View File
@@ -8,26 +8,47 @@ import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui
import { Input } from "@/components/ui/input";
import { authClient } from "@/lib/auth-client";
/** Signs in with Better Auth, then goes to next (already checked to be a path on this site). */
/** Signs in with Better Auth (then a code, if two-factor sign-in is on), then goes to next (already checked to be a
* path on this site). */
export function SignInForm({ next }: { next: string }) {
const router = useRouter();
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
// After the password, when two-factor sign-in is on: a code from the app, or a backup code.
const [step, setStep] = useState<"password" | "code" | "backup">("password");
const done = () => {
// Back to the hub's authorize endpoint (signing in for another T5DE site): a full page load, it's the API's.
if (next.startsWith("/api/")) return window.location.assign(next);
router.push(next);
router.refresh();
};
async function signIn(form: FormData) {
const { data, error } = await authClient.signIn.username({
username: String(form.get("username")),
password: String(form.get("password")),
});
if (error) return setError(error.message ?? "That didn't work. Try again.");
if (data && "twoFactorRedirect" in data && data.twoFactorRedirect) return setStep("code");
done();
}
async function verify(form: FormData) {
const code = String(form.get("code")).replace(/\s+/g, "");
const { error } =
step === "code"
? await authClient.twoFactor.verifyTotp({ code })
: await authClient.twoFactor.verifyBackupCode({ code });
if (error) return setError(error.message ?? "That code didn't work. Try again.");
done();
}
async function submit(form: FormData) {
setError("");
setPending(true);
const { error } = await authClient.signIn.username({
username: String(form.get("username")),
password: String(form.get("password")),
});
if (error) {
setError(error.message ?? "That didn't work. Try again.");
setPending(false);
return;
}
router.push(next);
router.refresh();
await (step === "password" ? signIn(form) : verify(form));
setPending(false);
}
return (
@@ -37,25 +58,68 @@ export function SignInForm({ next }: { next: string }) {
void submit(new FormData(e.currentTarget));
}}
>
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" name="username" autoComplete="username" required autoFocus />
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input id="password" name="password" type="password" autoComplete="current-password" required />
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
<Button type="submit" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</Button>
<FieldDescription className="text-center">
No account? <Link href="/signup">Create one</Link>
</FieldDescription>
</Field>
</FieldGroup>
{step === "password" ? (
<FieldGroup>
<Field>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input id="username" name="username" autoComplete="username" required autoFocus />
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input id="password" name="password" type="password" autoComplete="current-password" required />
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
<Button type="submit" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</Button>
<FieldDescription className="text-center">
No account? <Link href="/signup">Create one</Link>
</FieldDescription>
</Field>
</FieldGroup>
) : (
<FieldGroup key={step}>
<Field>
<FieldLabel htmlFor="code">
{step === "code" ? "Code from your authenticator app" : "Backup code"}
</FieldLabel>
<Input
id="code"
name="code"
required
autoFocus
autoComplete="one-time-code"
{...(step === "code"
? {
inputMode: "numeric",
pattern: "\\s*[0-9]{6}\\s*",
maxLength: 8,
}
: { maxLength: 32 })}
className="font-mono"
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Field>
<Button type="submit" disabled={pending}>
{pending ? "Checking…" : "Sign in"}
</Button>
<FieldDescription className="text-center">
<button
type="button"
className="underline underline-offset-4"
onClick={() => {
setError("");
setStep(step === "code" ? "backup" : "code");
}}
>
{step === "code" ? "Use a backup code instead" : "Use your authenticator app instead"}
</button>
</FieldDescription>
</Field>
</FieldGroup>
)}
</form>
);
}
+7 -2
View File
@@ -1,15 +1,20 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { NarrowCard } from "@/components/narrow-card";
import { getMe } from "@/lib/api";
import { api, getMe, unwrap } from "@/lib/api";
import { SignUpForm } from "./signup-form";
export const metadata: Metadata = { title: "Create account" };
export default async function SignUp() {
if (await getMe()) redirect("/account");
const { registration } = unwrap(await api.hub.get());
const description =
registration === "closed"
? "One T5DE account for all your IMVU accounts. New accounts need a moderator's approval."
: "One T5DE account for all your IMVU accounts.";
return (
<NarrowCard title="Create account" description="One T5DE account for all your IMVU accounts.">
<NarrowCard title="Create account" description={description}>
<SignUpForm />
</NarrowCard>
);
+76
View File
@@ -0,0 +1,76 @@
// Pieces shared by the case pages and the places people open cases from.
import Link from "next/link";
import { ActionForm, SubmitButton } from "@/components/forms";
import { Tag } from "@/components/status";
import { Input } from "@/components/ui/input";
import { report } from "@/app/console/cases/actions";
export const caseKinds: Record<string, string> = {
report: "Report",
"rating-review": "Rating review",
"removal-request": "Removal request",
"catalog-deletion": "Catalog deletion",
appeal: "Appeal",
};
/** What resolving each kind of case does (its button). */
export const resolveLabel: Record<string, string> = {
report: "Resolve",
"rating-review": "Lower to general",
"removal-request": "Remove the product",
"catalog-deletion": "Delete the catalog",
appeal: "Uphold the appeal",
};
export function CaseStatus({ status }: { status: string }) {
if (status === "open") return <Tag tone="strong">Open</Tag>;
if (status === "resolved") return <Tag>Resolved</Tag>;
return <Tag>Declined</Tag>;
}
const tagLinks: Record<string, (id: string) => string> = {
catalog: (id) => `/catalogs/${id}`,
product: (id) => `/products/${id}`,
};
/** What a case is about, linked. */
export function CaseAbout({ tags, names }: { tags: Record<string, string | undefined>; names: Record<string, string> }) {
const parts = Object.entries(tags).filter((e): e is [string, string] => !!e[1]);
if (parts.length === 0) return <span className="text-muted-foreground">nothing</span>;
return (
<span className="space-x-2">
{parts.map(([kind, id]) => {
const href = tagLinks[kind]?.(id);
return (
<span key={kind}>
<span className="text-muted-foreground">{kind} </span>
{href ? (
<Link href={href} className="underline-offset-4 hover:underline">
{names[id] ?? id}
</Link>
) : (
(names[id] ?? id)
)}
</span>
);
})}
</span>
);
}
/** "Report": a reason, sent to moderators (and the hosting catalogs' teams, for products). */
export function ReportForm({ about, id, label = "Report" }: { about: "product" | "catalog" | "room" | "person"; id: string; label?: string }) {
return (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">{label}</summary>
<ActionForm action={report} fields={{ about, id }} className="mt-2">
<div className="flex max-w-xl flex-wrap gap-2">
<Input name="reason" required maxLength={2000} placeholder="What's wrong?" aria-label="What's wrong" className="min-w-60 flex-1" />
<SubmitButton variant="outline" pendingLabel="Sending…">
Send report
</SubmitButton>
</div>
</ActionForm>
</details>
);
}
+2 -2
View File
@@ -2,9 +2,9 @@ import { Tag } from "@/components/status";
export const membership: Record<string, string> = { open: "Open", approval: "By approval", invite: "Invite only" };
/** A catalog's review status: approved, pending or rejected. */
/** A catalog's status: approved, pending, rejected, suspended or deleted. */
export function CatalogStatus({ status }: { status: string }) {
if (status === "approved") return <Tag tone="strong">approved</Tag>;
if (status === "rejected") return <Tag tone="danger">rejected</Tag>;
if (status === "rejected" || status === "suspended" || status === "deleted") return <Tag tone="danger">{status}</Tag>;
return <Tag>{status}</Tag>;
}
+49
View File
@@ -0,0 +1,49 @@
"use client";
// Discord sign-in (a basic account the first time, docs/music.md) and, from the account page, linking Discord to a
// member's account. Discord sends people back to the API, which sends them on to these addresses on this site.
import { useEffect, useRef, useState } from "react";
import { ErrorText } from "@/components/forms";
import { Button } from "@/components/ui/button";
import { authClient } from "@/lib/auth-client";
/** auto: start at once (a T5DE site asked for Discord sign-in). */
export function DiscordButton({ mode, next = "/", auto = false }: { mode: "sign-in" | "link"; next?: string; auto?: boolean }) {
const [pending, setPending] = useState(false);
const [error, setError] = useState("");
async function go() {
setPending(true);
setError("");
const origin = window.location.origin;
const back =
mode === "link"
? { callbackURL: `${origin}/account`, errorCallbackURL: `${origin}/account` }
: { callbackURL: origin + next, errorCallbackURL: `${origin}/signin?next=${encodeURIComponent(next)}` };
const { error } =
mode === "link"
? await authClient.linkSocial({ provider: "discord", ...back })
: await authClient.signIn.social({ provider: "discord", ...back });
// On success the browser is already on its way to Discord.
if (error) {
setError(error.message ?? "That didn't work. Try again.");
setPending(false);
}
}
const started = useRef(false);
useEffect(() => {
if (!auto || started.current) return;
started.current = true;
void go();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [auto]);
return (
<div className="space-y-2">
<Button type="button" variant={mode === "link" ? "outline" : "default"} className={mode === "link" ? undefined : "w-full"} disabled={pending} onClick={() => void go()}>
{pending ? "Going to Discord…" : mode === "link" ? "Link Discord" : "Sign in with Discord"}
</Button>
{error && <ErrorText>{error}</ErrorText>}
</div>
);
}
+20 -2
View File
@@ -1,6 +1,7 @@
import Image from "next/image";
import { Bell } from "lucide-react";
import Link from "next/link";
import { getMe, isModerator } from "@/lib/api";
import { getMe } from "@/lib/api";
import { buttonVariants } from "@/components/ui/button";
import { NavLink, ProfileMenu } from "./header-client";
import logo from "./t5de.png";
@@ -24,8 +25,25 @@ export async function Header() {
<NavLink href="/catalogs">Catalogs</NavLink>
</nav>
<div className="ml-auto flex items-center gap-2 text-sm">
<a href="https://t5de.dev/download" className={buttonVariants({ variant: "ghost" })}>
Download
</a>
{me ? (
<ProfileMenu username={me.username} picture={me.picture} console={isModerator(me)} />
<>
<Link
href="/notifications"
aria-label={me.unread ? `Notifications, ${me.unread} unread` : "Notifications"}
className={buttonVariants({ variant: "ghost", size: "icon", className: "relative" })}
>
<Bell className="size-4" />
{me.unread > 0 && (
<span className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-foreground px-1 text-[10px] font-semibold text-background tabular-nums">
{me.unread > 99 ? "99+" : me.unread}
</span>
)}
</Link>
<ProfileMenu username={me.username} picture={me.picture} console={me.console} />
</>
) : (
<>
<Link href="/signin" className={buttonVariants({ variant: "ghost" })}>
+22 -2
View File
@@ -8,6 +8,23 @@ export function RatingTag({ rating }: { rating: string }) {
return rating === "adult" ? <Tag tone="adult">Adult</Tag> : null;
}
/** A product's state, where it isn't plainly published and listed: draft, unlisted, deleted, removed, locked. */
export function StateTags({
product: p,
}: {
product: Pick<ProductSummary, "status" | "listed" | "deleted" | "removed" | "locked">;
}) {
return (
<>
{p.status === "draft" && <Tag tone="strong">Draft</Tag>}
{p.status === "published" && !p.listed && <Tag>Unlisted</Tag>}
{p.deleted && <Tag tone="danger">Deleted</Tag>}
{p.removed && <Tag tone="danger">Removed</Tag>}
{p.locked.length > 0 && <Tag>Locked: {p.locked.join(", ")}</Tag>}
</>
);
}
/** 1536 → "1.5 KB". */
export function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
@@ -39,7 +56,7 @@ export function ProductCard({
product,
children,
}: {
product: Pick<ProductSummary, "id" | "name" | "creator" | "rating" | "latest" | "image" | "categories">;
product: Pick<ProductSummary, "id" | "name" | "creator" | "rating" | "latest" | "image" | "categories" | "listed">;
children?: React.ReactNode;
}) {
const category = product.categories.at(-1)?.name;
@@ -51,7 +68,10 @@ export function ProductCard({
<Link href={`/products/${product.id}`} className="font-medium underline-offset-4 hover:underline">
{product.name}
</Link>
<RatingTag rating={product.rating} />
<span className="flex gap-1">
{!product.listed && <Tag>Unlisted</Tag>}
<RatingTag rating={product.rating} />
</span>
</div>
<p className="text-xs text-muted-foreground">
{[product.creator && `by ${product.creator}`, category, `revision ${product.latest}`].filter(Boolean).join(" · ")}
+25
View File
@@ -0,0 +1,25 @@
import { DateTime } from "@/components/time";
/** For an active whole-shop grant: how many products IMVU lists in the shop, and when the hub last looked. */
export function ShopListing({
grant: g,
}: {
grant: {
scope: string;
status: string;
shopListedAt: string | null;
shopListed: number;
shopListedSignedIn: boolean;
};
}) {
if (g.scope !== "shop" || g.status !== "active") return null;
if (!g.shopListedAt) return <> Not checked on IMVU yet.</>;
return (
<>
{" "}
On IMVU: {g.shopListed} {g.shopListedSignedIn ? "" : "general-rated "}product{g.shopListed === 1 ? "" : "s"}{" "}
(checked <DateTime iso={g.shopListedAt} />
{g.shopListedSignedIn ? " by the importer, with Access Pass" : ""}).
</>
);
}
+2 -2
View File
@@ -75,8 +75,8 @@ export function PageHeader({ title, children }: { title: React.ReactNode; childr
}
/** An IMVU account's age status: blue when it can see adult community products. */
export function AgeTag({ link }: { link: Pick<Link, "ageVerified" | "accessPass"> }) {
if (link.ageVerified) return <Tag tone="adult">Age verified</Tag>;
export function AgeTag({ link }: { link: Pick<Link, "ageVerified" | "accessPass" | "adult"> }) {
if (link.ageVerified || (link.adult && !link.accessPass)) return <Tag tone="adult">Age verified</Tag>;
if (link.accessPass) return <Tag tone="adult">Access Pass</Tag>;
return <Tag>Not age verified</Tag>;
}
+72
View File
@@ -0,0 +1,72 @@
"use client"
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "cn"
function Dialog(props: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogContent({
className,
children,
...props
}: DialogPrimitive.Popup.Props) {
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Backdrop
data-slot="dialog-backdrop"
className="fixed inset-0 z-50 bg-black/40 transition-opacity duration-150 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-xs"
/>
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-5 text-sm text-popover-foreground ring-1 ring-foreground/10 outline-none transition-all duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0 sm:max-w-md",
className
)}
{...props}
>
{children}
</DialogPrimitive.Popup>
</DialogPrimitive.Portal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return <div data-slot="dialog-header" className={cn("flex flex-col gap-1.5", className)} {...props} />
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...props}
/>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-base leading-none font-medium", className)}
{...props}
/>
)
}
function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
const DialogClose = DialogPrimitive.Close
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle }
+2 -1
View File
@@ -53,7 +53,8 @@ export function UploadForm({ catalogs, product }: { catalogs: Option[]; product?
const answer = await send(start.url, start.token, body, setProgress);
const value = answer.body as { product?: unknown; message?: unknown } | null;
if (answer.status === 201 && typeof value?.product === "string") {
router.push(`/products/${value.product}`);
// A new product is a draft: on to reviewing its info and publishing it.
router.push(product ? `/products/${value.product}` : `/products/${value.product}/edit`);
router.refresh();
return;
}
+18
View File
@@ -37,12 +37,30 @@ export type Person = Data<V1["me"]["get"]>["person"];
export type Account = Data<V1["account"]["get"]>;
export type Link = Account["links"][number];
export type Challenge = Account["challenges"][number];
export type AgeInfo = Data<V1["age"]["get"]>;
export type OnlineEntry = Data<V1["online"]["get"]>["online"][number];
export type ConsoleData = Data<V1["console"]["get"]>;
export type AuditEntry = ConsoleData["audit"][number];
export type CaseSummary = Data<V1["cases"]["get"]>["cases"][number];
export type CasePage = Data<ReturnType<V1["cases"]>["get"]>;
export type NotificationEntry = Data<V1["notifications"]["get"]>["notifications"][number];
export type TokenList = Data<V1["account"]["tokens"]["get"]>;
export type TokenEntry = TokenList["tokens"][number];
export type TokenScope = TokenList["scopes"][number];
export type CatalogPage = Data<ReturnType<V1["catalogs"]>["get"]>;
export type ImportCatalogs = Data<V1["imports"]["catalogs"]["get"]>;
export type ImportGrant = Data<V1["imports"]["grants"]["get"]>["grants"][number];
export type ImporterPage = Data<ReturnType<V1["catalogs"]>["importer"]["get"]>;
export type ImportJob = ImporterPage["jobs"][number];
export type CatalogMember = Data<ReturnType<V1["catalogs"]>["members"]["get"]>["members"][number];
export type CatalogInvite = Data<ReturnType<V1["catalogs"]>["invites"]["get"]>["invites"][number];
export type HostedProduct = Data<ReturnType<V1["catalogs"]>["products"]["get"]>["products"][number];
export type CatalogTeam = Data<ReturnType<V1["catalogs"]>["team"]["get"]>;
export type ProductSummary = Data<V1["products"]["get"]>["products"][number];
export type ProductPage = Data<ReturnType<V1["products"]>["get"]>;
export type Revision = ProductPage["revisions"][number];
export type InfoEntry = Data<ReturnType<V1["products"]>["history"]["get"]>["entries"][number];
export type ManagedProduct = Data<V1["console"]["products"]["get"]>["products"][number];
export type Catalog = Data<V1["catalogs"]["get"]>["catalogs"][number];
export type LibraryEntry = Data<V1["library"]["get"]>["library"][number];
export type HostedRoom = Data<V1["hosted-rooms"]["get"]>["rooms"][number];
+4 -4
View File
@@ -1,10 +1,10 @@
// Better Auth in the browser: sign-up, sign-in and sign-out. Its requests go to /api/auth on this site, which Next
// rewrites to the API, so the session cookie is set for this site.
// Better Auth in the browser: sign-up, sign-in (with a two-factor code when it's on), sign-out, and two-factor setup.
// Its requests go to /api/auth on this site, which Next rewrites to the API, so the session cookie is set for this site.
"use client";
import { createAuthClient } from "better-auth/react";
import { usernameClient } from "better-auth/client/plugins";
import { twoFactorClient, usernameClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({
baseURL: typeof window === "undefined" ? undefined : window.location.origin,
plugins: [usernameClient()],
plugins: [usernameClient(), twoFactorClient()],
});
+15
View File
@@ -0,0 +1,15 @@
// What went wrong with Discord sign-in or linking, as a sentence. Better Auth sends people back with ?error=<code>.
const messages: Record<string, string> = {
email_not_verified: "Your Discord account's email isn't verified. Verify it in Discord, then try again.",
email_not_found: "Your Discord account has no email. Add one in Discord and verify it, then try again.",
account_not_linked:
"This email belongs to a T5DE account. Sign in to it with your username and password, then link Discord from your account page.",
account_already_linked_to_different_user: "That Discord account already signs in to another T5DE account.",
access_denied: "Discord sign-in was cancelled.",
};
/** The sentence for an error Discord sign-in came back with (undefined if there's none). */
export function discordError(code: string | string[] | undefined): string | undefined {
if (typeof code !== "string" || !code) return undefined;
return messages[code] ?? "Signing in with Discord didn't work. Try again.";
}
+6
View File
@@ -0,0 +1,6 @@
// Shared by the console's importer page and its client parts.
/** The start of a key's fingerprint, for people to compare: "1a2b 3c4d 5e6f 7a8b". */
export function shortFingerprint(hex: string): string {
return (hex.slice(0, 16).match(/.{4}/g) ?? []).join(" ");
}
+13
View File
@@ -0,0 +1,13 @@
// IMVU product IDs in what people type or paste.
/** IMVU product IDs: numbers, or shop links (`products_id=123`, `product-123`), separated by spaces, commas or lines. */
export function productIDs(text: string): number[] | undefined {
const out = new Set<number>();
for (const part of text.split(/[\s,]+/).filter(Boolean)) {
const m = part.match(/(?:products_id=|product-)(\d+)/) ?? part.match(/^(\d+)$/);
const n = m ? Number(m[1]) : NaN;
if (!Number.isSafeInteger(n) || n <= 0) return undefined;
out.add(n);
}
return [...out];
}
+25
View File
@@ -0,0 +1,25 @@
// Signing in for another T5DE site (OpenID Connect, docs/music.md). The hub's authorize endpoint sends people who
// aren't signed in to /signin with the site's request and a signature; once they're signed in, this sends them back
// to the authorize endpoint with the same request, which then returns them to the site.
type Params = Record<string, string | string[] | undefined>;
/** The provider's own parameters on the sign-in page, not part of the site's request. */
const internal = new Set(["sig", "exp", "ba_iat", "ba_param", "next", "error"]);
/** Where to go once signed in, if the sign-in page was opened for a site's request (else undefined). */
export function continueURL(params: Params): string | undefined {
if (typeof params.sig !== "string" || typeof params.client_id !== "string") return undefined;
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params)) {
if (internal.has(k) || v === undefined) continue;
for (const one of Array.isArray(v) ? v : [v]) q.append(k, one);
}
return `/api/auth/oauth2/authorize?${q}`;
}
/** The site's client ID, if the page was opened for one. */
export const requestingClient = (params: Params) => (typeof params.client_id === "string" ? params.client_id : undefined);
/** Whether the site asked to go straight to a sign-in provider (Music's "Sign in with Discord"). */
export const requestedProvider = (params: Params) => (typeof params.t5de_provider === "string" ? params.t5de_provider : undefined);
+4 -2
View File
@@ -10,16 +10,18 @@
},
"dependencies": {
"@base-ui/react": "^1.9.0",
"@better-auth/oauth-provider": "1.7.26",
"@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*",
"better-auth": "1.7.14",
"better-auth": "1.7.26",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.0",
"lucide-react": "^1.64.0",
"next": "16.4.3",
"react": "19.3.1",
"react-dom": "19.3.1",
"server-only": "^0.0.1"
"server-only": "^0.0.1",
"uqr": "^0.1.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.3",
+126 -127
View File
@@ -1,5 +1,5 @@
{
"lockfileVersion": 2,
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
@@ -11,11 +11,12 @@
"apps/api": {
"name": "@t5de/api",
"dependencies": {
"@better-auth/oauth-provider": "1.7.26",
"@t5de/db": "workspace:*",
"better-auth": "1.7.14",
"better-auth": "1.7.26",
"elysia": "1.4.30",
"jose": "^6.2.14",
"sanitize-html": "^2.18.1",
"jose": "6.2.14",
"sanitize-html": "2.18.1",
},
"devDependencies": {
"@types/bun": "^1.4.4",
@@ -27,9 +28,10 @@
"name": "@t5de/web",
"dependencies": {
"@base-ui/react": "^1.9.0",
"@better-auth/oauth-provider": "1.7.26",
"@elysiajs/eden": "1.4.9",
"@t5de/api": "workspace:*",
"better-auth": "1.7.14",
"better-auth": "1.7.26",
"class-variance-authority": "^0.7.1",
"cn": "^0.5.0",
"lucide-react": "^1.64.0",
@@ -37,6 +39,7 @@
"react": "19.3.1",
"react-dom": "19.3.1",
"server-only": "^0.0.1",
"uqr": "^0.1.3",
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.3",
@@ -70,23 +73,23 @@
"@babel/compat-data": ["@babel/[email protected]", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="],
"@babel/core": ["@babel/[email protected].7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="],
"@babel/core": ["@babel/[email protected].13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.13", "@babel/helpers": "^7.29.13", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw=="],
"@babel/generator": ["@babel/[email protected].8", "", { "dependencies": { "@babel/parser": "^7.29.8", "@babel/types": "^7.29.8", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg=="],
"@babel/generator": ["@babel/[email protected].14", "", { "dependencies": { "@babel/parser": "^7.29.14", "@babel/types": "^7.29.14", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g=="],
"@babel/helper-annotate-as-pure": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw=="],
"@babel/helper-compilation-targets": ["@babel/[email protected].7", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="],
"@babel/helper-compilation-targets": ["@babel/[email protected].13", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w=="],
"@babel/helper-create-class-features-plugin": ["@babel/[email protected].7", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/traverse": "^7.29.7", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg=="],
"@babel/helper-create-class-features-plugin": ["@babel/[email protected].13", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", "@babel/traverse": "^7.29.13", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-fo8/Fr44/DMV71FQjk/HA0Npmu3bo5DFoWTCW1dhUR8Vx3NFfAVeEy0TbcBpt4e+hd2QhdmWgmspHo/9iWj8RA=="],
"@babel/helper-globals": ["@babel/[email protected]", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="],
"@babel/helper-member-expression-to-functions": ["@babel/[email protected].7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg=="],
"@babel/helper-member-expression-to-functions": ["@babel/[email protected].14", "", { "dependencies": { "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", "@babel/traverse": "^7.29.14", "@babel/types": "^7.29.14" } }, "sha512-FuTSn8mXKAP+aHXnbkCYQsQAdlEIJptEutwc2NaPd28hyVqsjRDmBnI2EPJX6HCodKIqOHfayQHqtxQCkqwthA=="],
"@babel/helper-module-imports": ["@babel/[email protected]", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="],
"@babel/helper-module-transforms": ["@babel/[email protected].7", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="],
"@babel/helper-module-transforms": ["@babel/[email protected].14", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.14" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA=="],
"@babel/helper-optimise-call-expression": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong=="],
@@ -94,53 +97,55 @@
"@babel/helper-replace-supers": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ=="],
"@babel/helper-skip-transparent-expression-wrappers": ["@babel/[email protected].7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ=="],
"@babel/helper-skip-transparent-expression-wrappers": ["@babel/[email protected].13", "", { "dependencies": { "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11" } }, "sha512-Abm4rKIH0tmCayJLwcoeOkdzpYUphTbO52fHhyEBHn7S0R+ni4epNLI/8nq1L0DN2Bl0u5qmgWm2Og/z4fBb+Q=="],
"@babel/helper-string-parser": ["@babel/[email protected]1", "", {}, "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g=="],
"@babel/helper-string-parser": ["@babel/[email protected]4", "", {}, "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ=="],
"@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
"@babel/helper-validator-option": ["@babel/[email protected]", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="],
"@babel/helpers": ["@babel/[email protected]0", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.8" } }, "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg=="],
"@babel/helpers": ["@babel/[email protected]4", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.14" } }, "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ=="],
"@babel/parser": ["@babel/[email protected]1", "", { "dependencies": { "@babel/types": "^7.29.11" }, "bin": "./bin/babel-parser.js" }, "sha512-OZ6+oaK7GMyg3IfCpj8JOmn8n+w2rJbDT0LLfVDTLb1ZFeKDh3AiNELgCMUw175IJHSkLl74hG0M0VLsvx+gag=="],
"@babel/parser": ["@babel/[email protected]4", "", { "dependencies": { "@babel/types": "^7.29.14" }, "bin": "./bin/babel-parser.js" }, "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w=="],
"@babel/plugin-syntax-jsx": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A=="],
"@babel/plugin-syntax-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="],
"@babel/plugin-transform-modules-commonjs": ["@babel/[email protected].7", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ=="],
"@babel/plugin-transform-modules-commonjs": ["@babel/[email protected].14", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.14", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-mbv2yy5dqP6e3DbusCx+5AypXkFbyJD/JhG4/XhA+BIADOw5o7W+X0ewSp/h3w7gRL3oR5yny2/K8ljiydj4uA=="],
"@babel/plugin-transform-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/plugin-syntax-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-FFwIwzU+7SCOuxxV4YtJql6T9981ZVTm+FHO5GhVsRqCTdy0WwrEZh3l42ARpXruJUDGOptdduHW6Zr7pNPLNg=="],
"@babel/preset-typescript": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "@babel/plugin-syntax-jsx": "^7.29.7", "@babel/plugin-transform-modules-commonjs": "^7.29.7", "@babel/plugin-transform-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ=="],
"@babel/runtime": ["@babel/runtime@8.0.8", "", {}, "sha512-dEu8nGlRqjsJsvviUUoSMfcRHpwomCiRlXsc2mPfJ79+ffTpDm+JtfUtTMzUrqCApHQnCsVPD3gT1ZT8RgBRCQ=="],
"@babel/runtime": ["@babel/runtime@8.1.2", "", {}, "sha512-Ay6HdEKZJAeGs6KKJ/ezCK5ssjFmkvUiR0TEGv/B1abyjLWrQ2RU+M507Ppk0NikhvVFhlEFC1/rHfCiYqSUcw=="],
"@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="],
"@babel/traverse": ["@babel/[email protected]0", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.8", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.9", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "debug": "^4.3.1" } }, "sha512-B3lYAs2nkKskbgQ1nfy8Ma9ao9Q1rntTAQHrzzyDuj+TSO+X3le6PfWwqDvodsb+OumE10eMFfuMCTQSQ5iuIQ=="],
"@babel/traverse": ["@babel/[email protected]4", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.14", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.14", "@babel/template": "^7.29.7", "@babel/types": "^7.29.14", "debug": "^4.3.1" } }, "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA=="],
"@babel/types": ["@babel/[email protected]1", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.11", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ=="],
"@babel/types": ["@babel/[email protected]4", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.14", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w=="],
"@base-ui/react": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@base-ui/utils": "0.5.0", "@floating-ui/react-dom": "^2.1.9", "@floating-ui/utils": "^0.2.12", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@date-fns/tz": "^1.2.0", "@types/react": "^17 || ^18 || ^19", "date-fns": "^4.0.0", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@date-fns/tz", "@types/react", "date-fns"] }, "sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ=="],
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@floating-ui/utils": "^0.2.12", "reselect": "^5.3.0", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A=="],
"@better-auth/core": ["@better-auth/[email protected].14", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "@opentelemetry/api": "^1.9.0", "better-call": "1.4.4", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-ByhdrGVwp/el+hoTYKSVOHIH23/lQj9TQ1txdGcWOg22tnfr3hJ6ukzySooeYj/R36XsQgBhkJqIp8mKsNeErA=="],
"@better-auth/core": ["@better-auth/[email protected].26", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "@opentelemetry/api": "^1.9.0", "better-call": "~1.4.5", "jose": "^6.1.0", "kysely": "^0.28.5 || ^0.29.0", "nanostores": "^1.0.1" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-k9tECegh1/MZmAQ9tD+4fjF2zYCzMcy0Xhu3nASp8bj48NrK1E0yV2BAeWnprMVRqh62ka07xc0MZuqmvlXNDQ=="],
"@better-auth/drizzle-adapter": ["@better-auth/[email protected].14", "", { "peerDependencies": { "@better-auth/core": "^1.7.14", "@better-auth/utils": "^0.4.2 || ^0.5.0", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-5RC8Ec5Ur15FWsS4As9/VrlRbB3+9EfShxIpA5A1FcD6IgPxFvzQNkAm2+FYx9LUSqx47NPf9hBTG2GUCMP9Ig=="],
"@better-auth/drizzle-adapter": ["@better-auth/[email protected].26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0" }, "optionalPeers": ["drizzle-orm"] }, "sha512-3OOQPZkAFVo63jbjkQTVjM7SyNbKxmM5sb9BKflaJOT+ld6mxM6yItm5NMKNd1xn/wA4X/+kAmT/KjFL0mRW/Q=="],
"@better-auth/kysely-adapter": ["@better-auth/[email protected].14", "", { "peerDependencies": { "@better-auth/core": "^1.7.14", "@better-auth/utils": "^0.4.2 || ^0.5.0", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-4wkqj8a8JVpWDYLlgzfbk7eOaWCFkL6HHQd6CLamFKaC8vNsXew1x4v5dE5O6dGr8j4g5qMISS+BAvOuIvBevg=="],
"@better-auth/kysely-adapter": ["@better-auth/[email protected].26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "kysely": "^0.28.17 || ^0.29.0" }, "optionalPeers": ["kysely"] }, "sha512-8kImf5aRi5cFC3fYO7fqszSAUC5vU8ya7yHxuCovTJNz7ow4pItRshU319aEPBdgABRFU53kI0v+SE5NI8UJtQ=="],
"@better-auth/memory-adapter": ["@better-auth/[email protected].14", "", { "peerDependencies": { "@better-auth/core": "^1.7.14", "@better-auth/utils": "^0.4.2 || ^0.5.0" } }, "sha512-Ojv9BcmFyHuTHha9ZM/NUW1ut9J84wLngta+07Es0Ejn8kekqP5aHBpZd5Z8AvADs5iJUOWvQGFmGlPWAKJgBg=="],
"@better-auth/memory-adapter": ["@better-auth/[email protected].26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0" } }, "sha512-ttV2Q06uoJBJzp9J8zYwYwMY60jvlhziumyqUZ1gJKltvsOasbGfoGPYThypyydTVu8iApP9O4xI9jYXJ08syg=="],
"@better-auth/mongo-adapter": ["@better-auth/[email protected].14", "", { "peerDependencies": { "@better-auth/core": "^1.7.14", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-6IA0RSPZFMdRwwnLZ9oWnDIiD0y0o0azTHUfa01BNU2AFJgMDkeiASUV3bKcJBskzQoyQrff74eFYTsTSeeVUQ=="],
"@better-auth/mongo-adapter": ["@better-auth/[email protected].26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-mGVJ0UIL1hjrp5aCuv4hFinZhpB7vvpu1c/fSa40Ktk4GugXcXguVwHI4hiDqGCttslTz0LOa5gqT+BfzgdJWw=="],
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapt[email protected].14", "", { "peerDependencies": { "@better-auth/core": "^1.7.14", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-mF6t5xqeZNWzUe0ErmrSdzQmtslJscmu9X8Mp5QmROlpnnAzvSc70RILu8lHms8CePt7N34+KRH1QvYjGFrVGQ=="],
"@better-auth/oauth-provider": ["@better-auth/oauth-provid[email protected].26", "", { "dependencies": { "jose": "^6.2.3", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3", "better-auth": "^1.7.26", "better-call": "~1.4.5" } }, "sha512-wzeIJ2Yogsd8HN5QLm3avpEubJmwo/hg00qZf6c7Ivu/doJlg0PENJOxgK2oRdjbl787i9GOKp1pAzTCQpMGDg=="],
"@better-auth/telemetry": ["@better-auth/telemetry@1.7.14", "", { "peerDependencies": { "@better-auth/core": "^1.7.14", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3" } }, "sha512-PtKFzsH7gje/WJuUPDjckOoNFazsq8NMt3AdiXIPzHl7tZULcNGTKAX8K7+yn0rG6cO/4mtMgpOjhtilElOnmg=="],
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.7.26", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-rXc6dI6HBhD4uXh1gMJU0ScQjojt3wIS4+DziIm/j8ujoTBEG96hFVN0vFVIq/D7SnimXIsPu5rqJ7GYSDbDtw=="],
"@better-auth/telemetry": ["@better-auth/[email protected]", "", { "peerDependencies": { "@better-auth/core": "^1.7.26", "@better-auth/utils": "^0.4.2 || ^0.5.0", "@better-fetch/fetch": "1.3.3" } }, "sha512-XSxQWg+guJ4X9KrcsdJCUPcXk/GaKxPNSXrhuDRhoWhk3ommioRB2Y6/to6ROy1fGP8JtXqRN4ZPiyKZnfy4Sw=="],
"@better-auth/utils": ["@better-auth/[email protected]", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-WETqw5vQ52uQ/xwWR4E8rTgT6fDEr/wnS+otDNkBCa/69281FCF32OKDdQUcahMCnjsvqXBNiEvAQHFB0EVRRg=="],
@@ -236,37 +241,37 @@
"@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ=="],
"@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="],
"@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="],
"@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="],
"@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="],
"@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="],
"@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="],
"@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="],
"@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="],
"@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="],
"@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="],
"@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="],
"@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="],
"@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="],
"@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="],
"@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="],
"@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="],
"@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="],
"@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="],
"@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="],
"@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="],
"@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="],
"@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="],
"@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="],
"@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="],
"@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="],
"@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="],
"@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="],
"@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="],
"@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="],
"@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="],
"@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="],
"@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="],
"@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="],
@@ -282,7 +287,7 @@
"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
"@jridgewell/resolve-uri": ["@jridgewell/[email protected].2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
"@jridgewell/resolve-uri": ["@jridgewell/[email protected].3", "", {}, "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="],
@@ -298,13 +303,13 @@
"@next/swc-darwin-x64": ["@next/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A=="],
"@next/swc-linux-arm64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg=="],
"@next/swc-linux-arm64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg=="],
"@next/swc-linux-arm64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw=="],
"@next/swc-linux-arm64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw=="],
"@next/swc-linux-x64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA=="],
"@next/swc-linux-x64-gnu": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA=="],
"@next/swc-linux-x64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw=="],
"@next/swc-linux-x64-musl": ["@next/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw=="],
"@next/swc-win32-arm64-msvc": ["@next/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow=="],
@@ -338,37 +343,37 @@
"@t5de/web": ["@t5de/web@workspace:apps/web"],
"@tailwindcss/node": ["@tailwindcss/[email protected].3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],
"@tailwindcss/node": ["@tailwindcss/[email protected].5", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.5", "jiti": "^2.7.0", "lightningcss": "1.33.0", "magic-string": "^1.1.0", "source-map-js": "^1.2.1", "tailwindcss": "4.3.5" } }, "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g=="],
"@tailwindcss/oxide": ["@tailwindcss/[email protected].3", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="],
"@tailwindcss/oxide": ["@tailwindcss/[email protected].5", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.5", "@tailwindcss/oxide-darwin-arm64": "4.3.5", "@tailwindcss/oxide-darwin-x64": "4.3.5", "@tailwindcss/oxide-freebsd-x64": "4.3.5", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", "@tailwindcss/oxide-linux-x64-musl": "4.3.5", "@tailwindcss/oxide-wasm32-wasi": "4.3.5", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" } }, "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg=="],
"@tailwindcss/oxide-android-arm64": ["@tailwindcss/[email protected].3", "", { "os": "android", "cpu": "arm64" }, "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw=="],
"@tailwindcss/oxide-android-arm64": ["@tailwindcss/[email protected].5", "", { "os": "android", "cpu": "arm64" }, "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q=="],
"@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/[email protected].3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw=="],
"@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/[email protected].5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ=="],
"@tailwindcss/oxide-darwin-x64": ["@tailwindcss/[email protected].3", "", { "os": "darwin", "cpu": "x64" }, "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw=="],
"@tailwindcss/oxide-darwin-x64": ["@tailwindcss/[email protected].5", "", { "os": "darwin", "cpu": "x64" }, "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ=="],
"@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/[email protected].3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw=="],
"@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/[email protected].5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg=="],
"@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/[email protected].3", "", { "os": "linux", "cpu": "arm" }, "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ=="],
"@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/[email protected].5", "", { "os": "linux", "cpu": "arm" }, "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA=="],
"@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/[email protected].3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w=="],
"@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/[email protected].5", "", { "os": "linux", "cpu": "arm64" }, "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ=="],
"@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/[email protected].3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA=="],
"@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/[email protected].5", "", { "os": "linux", "cpu": "arm64" }, "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw=="],
"@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/[email protected].3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w=="],
"@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/[email protected].5", "", { "os": "linux", "cpu": "x64" }, "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g=="],
"@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/[email protected].3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img=="],
"@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/[email protected].5", "", { "os": "linux", "cpu": "x64" }, "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg=="],
"@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/[email protected].3", "", { "dependencies": { "@emnapi/core": "^1.11.1", "@emnapi/runtime": "^1.11.1", "@emnapi/wasi-threads": "^1.2.2", "@napi-rs/wasm-runtime": "^1.1.4", "@tybys/wasm-util": "^0.10.2", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ=="],
"@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/[email protected].5", "", { "dependencies": { "@emnapi/core": "^1.11.3", "@emnapi/runtime": "^1.11.3", "@emnapi/wasi-threads": "^1.2.3", "@napi-rs/wasm-runtime": "^1.2.2", "@tybys/wasm-util": "^0.10.3", "tslib": "^2.8.1" } }, "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw=="],
"@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/[email protected].3", "", { "os": "win32", "cpu": "arm64" }, "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ=="],
"@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/[email protected].5", "", { "os": "win32", "cpu": "arm64" }, "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg=="],
"@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/[email protected].3", "", { "os": "win32", "cpu": "x64" }, "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw=="],
"@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/[email protected].5", "", { "os": "win32", "cpu": "x64" }, "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg=="],
"@tailwindcss/postcss": ["@tailwindcss/[email protected].3", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "postcss": "^8.5.16", "tailwindcss": "4.3.3" } }, "sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg=="],
"@tailwindcss/postcss": ["@tailwindcss/[email protected].5", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.5", "@tailwindcss/oxide": "4.3.5", "postcss": "^8.5.25", "tailwindcss": "4.3.5" } }, "sha512-FAV37Tlx9wBiT/hkfgVD0Q6CWsP2oUX3lf28nrfjW8+ksILjnpuFulUqWDfNR4/ZiEHHDRBX8DUTzD1Rys687A=="],
"@tokenizer/inflate": ["@tokenizer/[email protected].0", "", { "dependencies": { "debug": "^4.4.3", "strtok3": "^10.6.2", "token-types": "^6.1.2" } }, "sha512-+0RDxhBkyT9xMnGdJAwmats9yxRLR8ypJrQgrnLqOu4Gv/aHlnxYgdGVy2QTwvBl6IF/w2Hr+ZNirH+iMUbVZA=="],
"@tokenizer/inflate": ["@tokenizer/[email protected].1", "", { "dependencies": { "debug": "^4.4.3", "strtok3": "^10.8.0", "token-types": "^6.2.0" } }, "sha512-EuqSyHdOXN61cc5/rsW6uUn1TJZJGZr56jlkUbsLwVJ6uHgvwQyFkYfOCf+zzPFAYjftPk1WeJnEhpLVvzbm1A=="],
"@tokenizer/token": ["@tokenizer/[email protected]", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="],
@@ -444,7 +449,7 @@
"ansi-colors": ["[email protected]", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="],
"ansi-regex": ["ansi-regex@6.4.0", "", {}, "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw=="],
"ansi-regex": ["ansi-regex@6.6.0", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="],
"ast-types": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA=="],
@@ -452,17 +457,17 @@
"balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"baseline-browser-mapping": ["[email protected]4", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA=="],
"baseline-browser-mapping": ["[email protected]8", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-rMgy5YW7x28SMfXHLlVZDBqlWzYZ0x2rVR/6FWrNBF0chjigARK1H6nM0hKA1Um3kPOlkQFVtjJs00d2N1ezuw=="],
"better-auth": ["[email protected].14", "", { "dependencies": { "@better-auth/core": "1.7.14", "@better-auth/drizzle-adapter": "1.7.14", "@better-auth/kysely-adapter": "1.7.14", "@better-auth/memory-adapter": "1.7.14", "@better-auth/mongo-adapter": "1.7.14", "@better-auth/prisma-adapter": "1.7.14", "@better-auth/telemetry": "1.7.14", "@better-auth/utils": "0.5.1", "@better-fetch/fetch": "1.3.3", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.4", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0 || ^3.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-QxDCI0pOCCHDYmruisKhKyrvOJ6Icv9xg0RA6ZUysfKFXENYwhNNpwUlkE/NmViH2nDMgkKcymmLr55pnpR9vw=="],
"better-auth": ["[email protected].26", "", { "dependencies": { "@better-auth/core": "1.7.26", "@better-auth/drizzle-adapter": "1.7.26", "@better-auth/kysely-adapter": "1.7.26", "@better-auth/memory-adapter": "1.7.26", "@better-auth/mongo-adapter": "1.7.26", "@better-auth/prisma-adapter": "1.7.26", "@better-auth/telemetry": "1.7.26", "@better-auth/utils": "0.5.1", "@better-fetch/fetch": "1.3.3", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.6", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0 || ^3.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-8TLA60CxEnhcmGceHIFlheonqrFFcVJ1Yfr3gOJEet3xyMfN6qAVN0N1GRcpe0g9KNzqhe1EM2smbk9DCylaAA=="],
"better-call": ["[email protected].4", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-Gq4XdGFy4dmUxFEAX2nj0ycFcFbD9ZWh8YROouZoyXeF1M11TpYbplk0pDByTFF8Wz+MYa6W9052c9m7dD+mfw=="],
"better-call": ["[email protected].6", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-tJ3lkMFeQProwiuZiQApwgVmYmBfXM4sAP7HxMsnAFtl4NWZhamG+RGoMNgHwGYkmcB+3eWyo3vgt4sWUUSdQA=="],
"brace-expansion": ["[email protected]2", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="],
"brace-expansion": ["[email protected]3", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ=="],
"braces": ["[email protected]", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
"browserslist": ["[email protected].5", "", { "dependencies": { "baseline-browser-mapping": "^2.11.33", "caniuse-lite": "^1.0.30001819", "electron-to-chromium": "^1.5.464", "node-releases": "^2.0.60", "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" } }, "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ=="],
"browserslist": ["[email protected].6", "", { "dependencies": { "baseline-browser-mapping": "^2.11.37", "caniuse-lite": "^1.0.30001826", "electron-to-chromium": "^1.5.486", "node-releases": "^2.0.64", "update-browserslist-db": "^1.4.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w=="],
"buffer-from": ["[email protected]", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
@@ -470,7 +475,7 @@
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA=="],
"caniuse-lite": ["[email protected]0", "", {}, "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w=="],
"caniuse-lite": ["[email protected]6", "", {}, "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA=="],
"chalk": ["[email protected]", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="],
@@ -484,7 +489,7 @@
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
"cn": ["[email protected].0", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-JGEixZEpfFXm1P5uXwvEobOFLlHwIWi5v4tjd1ZwfiYmcEilkuD2l+054rvJcYCR1B+uVThHeUbgmNz1FwuxuA=="],
"cn": ["[email protected].2", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-wm10E6iuJ37rALOw3D+3cfaXXZSLNMh2uxpQn3dNICqfJM59yXqgbA9/9Iiz155j5kYNLdK6WreNdW3NQtx3OQ=="],
"code-block-writer": ["[email protected]", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="],
@@ -498,15 +503,13 @@
"cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"cssesc": ["css[email protected]", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"csstype": ["css[email protected]", "", {}, "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ=="],
"dayjs": ["[email protected]", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="],
"debounce-fn": ["[email protected]", "", { "dependencies": { "mimic-fn": "^3.0.0" } }, "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"dedent": ["[email protected]", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA=="],
@@ -538,15 +541,15 @@
"drizzle-kit": ["[email protected]", "", { "dependencies": { "@drizzle-team/brocli": "^0.10.2", "@esbuild-kit/esm-loader": "^2.5.5", "esbuild": "^0.25.4", "tsx": "^4.21.0" }, "bin": { "drizzle-kit": "bin.cjs" } }, "sha512-YCYqxTLIB2OCqf6w9/Vef13baBVbwQIPcbT4Y56AfO6B9ajZhDhD8Jkveg/hJvT/iuMloKD/IYYkyMMNhr7Kqg=="],
"drizzle-orm": ["[email protected]", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@netlify/db": ">=0.4.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "prisma": "*", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@netlify/db", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "prisma", "sql.js", "sqlite3"] }, "sha512-NiM1YZpJ2UxyeE67DpDDZ+Tsw4YLX3trSlkNT7Tm9eKoUNb1LvaAaQzXgYQsWs+AQ9TUmmwMmBOCXuqqxUWKKQ=="],
"drizzle-orm": ["[email protected]", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@netlify/db": ">=0.4.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@netlify/db", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "sql.js", "sqlite3"] }, "sha512-NiM1YZpJ2UxyeE67DpDDZ+Tsw4YLX3trSlkNT7Tm9eKoUNb1LvaAaQzXgYQsWs+AQ9TUmmwMmBOCXuqqxUWKKQ=="],
"electron-to-chromium": ["[email protected]67", "", {}, "sha512-Nw9X371rtZmYcBSnEijnCDONILjs93biCZO34juC7MBOmK8E+GFnyD4T/WvyrlJkppul7oxg6TwvtKst9SODTw=="],
"electron-to-chromium": ["[email protected]91", "", {}, "sha512-zMOQrvaTekJMwENqx1Rnyl3qieqGxIui5CRu9g6ktKzQ/T54fq0Qfr3V/SEhGrkStWI3eYMSzMN4rbyFwfQSzA=="],
"elysia": ["[email protected]", "", { "dependencies": { "cookie": "^1.1.1", "exact-mirror": "^0.2.7", "fast-decode-uri-component": "^1.0.1", "memoirist": "^0.4.0" }, "peerDependencies": { "@sinclair/typebox": ">= 0.34.0 < 1", "@types/bun": ">= 1.2.0", "file-type": ">= 20.0.0", "openapi-types": ">= 12.0.0", "typescript": ">= 5.0.0" }, "optionalPeers": ["@types/bun", "typescript"] }, "sha512-S2qqV0CbM4faB1hQQ5IYoeYnAUinjHlzRduxaBc4OoNqh0GjOc8k6tt3hv5ozWcG6Svr6hugw6JL4zNke4jwfA=="],
"emoji-regex": ["[email protected]", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
"enhanced-resolve": ["[email protected]6.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw=="],
"enhanced-resolve": ["[email protected]7.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ=="],
"enquirer": ["[email protected]", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="],
@@ -554,7 +557,7 @@
"env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
"esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
"esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
"escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
@@ -562,7 +565,7 @@
"esprima": ["[email protected]", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
"exact-mirror": ["[email protected].7", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-+MeEmDcLA4o/vjK2zujgk+1VTxPR4hdp23qLqkWfStbECtAq9gmsvQa3LW6z/0GXZyHJobrCnmy1cdeE7BjsYg=="],
"exact-mirror": ["[email protected].9", "", { "peerDependencies": { "@sinclair/typebox": "^0.34.15" }, "optionalPeers": ["@sinclair/typebox"] }, "sha512-7+ecLdWdlY0Br1E1Fax2Pss5VU3b1WQwJ8bdyt5azPNdhKHuivjQlV8baXF9NkQwlvnyOwaM6ITBiuK43PQ4wg=="],
"execa": ["[email protected]", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "cross-spawn": "^7.0.6", "figures": "^6.1.0", "get-stream": "^9.0.0", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "yoctocolors": "^2.1.1" } }, "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA=="],
@@ -588,7 +591,7 @@
"fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA=="],
"fsevents": ["[email protected]", "", { "os": "darwin", "hasInstallScript": true }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"fsevents": ["[email protected]", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"fuzzysort": ["[email protected]", "", {}, "sha512-sR9BNCjBg6LNgwvxlBd0sBABvQitkLzoVY9MYYROQVX/FvfJ4Mai9LsGhDgd8qYdds0bY77VzYd5iuB+v5rwQQ=="],
@@ -604,7 +607,7 @@
"glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
"graceful-fs": ["[email protected]1", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"graceful-fs": ["[email protected]2", "", {}, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="],
"htmlparser2": ["[email protected]", "", { "dependencies": { "domelementtype": "^3.0.0", "domhandler": "^6.0.0", "domutils": "^4.0.2", "entities": "^8.0.0" } }, "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw=="],
@@ -614,7 +617,7 @@
"ignore": ["[email protected]", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="],
"ip-address": ["[email protected].5", "", {}, "sha512-t2v0rkILYv9WXmSL7TpAaU3HXgaFYOPUcH3QHgwQ++gpJuH3bqyMy4Fvt/DJCTKwzH3Cf+bAp5W/mFL39KPLzA=="],
"ip-address": ["[email protected].6", "", {}, "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg=="],
"is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="],
@@ -664,33 +667,33 @@
"kleur": ["[email protected]", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
"kysely": ["[email protected].7", "", {}, "sha512-fmIq+7kv4WbFm2tcfznRzikqB4cuNpgZ40PSU2fAJ2/OO5XhojqnTPrmgrCjYSRJVwBln03XcRXJGnw9H099IQ=="],
"kysely": ["[email protected].9", "", {}, "sha512-K48ErswC3MlIcBqR0pYIIEl+n9rIgwxgzaM1FxKHMXn7egxr1NHj7bCeF98mXl9A3/QoL5I7mo5S/mLXgeDgGA=="],
"launder": ["[email protected]", "", { "dependencies": { "dayjs": "^1.11.23" } }, "sha512-DLg3HPnHUfBi5/MxMLmJD12dmlMpFEC2HgMW6vkZ/9JR0RU00kXoRGvDxAvFmdO0o610OA77i4FgNTLucmhDVg=="],
"lightningcss": ["[email protected]2.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
"lightningcss": ["[email protected]3.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
"lightningcss-android-arm64": ["[email protected]2.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
"lightningcss-android-arm64": ["[email protected]3.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
"lightningcss-darwin-arm64": ["[email protected]2.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],
"lightningcss-darwin-arm64": ["[email protected]3.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
"lightningcss-darwin-x64": ["[email protected]2.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="],
"lightningcss-darwin-x64": ["[email protected]3.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
"lightningcss-freebsd-x64": ["[email protected]2.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="],
"lightningcss-freebsd-x64": ["[email protected]3.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
"lightningcss-linux-arm-gnueabihf": ["[email protected]2.0", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="],
"lightningcss-linux-arm-gnueabihf": ["[email protected]3.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
"lightningcss-linux-arm64-gnu": ["[email protected]2.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="],
"lightningcss-linux-arm64-gnu": ["[email protected]3.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
"lightningcss-linux-arm64-musl": ["[email protected]2.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="],
"lightningcss-linux-arm64-musl": ["[email protected]3.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
"lightningcss-linux-x64-gnu": ["[email protected]2.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="],
"lightningcss-linux-x64-gnu": ["[email protected]3.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
"lightningcss-linux-x64-musl": ["[email protected]2.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="],
"lightningcss-linux-x64-musl": ["[email protected]3.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
"lightningcss-win32-arm64-msvc": ["[email protected]2.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="],
"lightningcss-win32-arm64-msvc": ["[email protected]3.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
"lightningcss-win32-x64-msvc": ["[email protected]2.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
"lightningcss-win32-x64-msvc": ["[email protected]3.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
"locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="],
@@ -698,9 +701,9 @@
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
"lucide-react": ["[email protected]4.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-v626F/bcLNvFom6vzztHILtG9tUgXXbgA5AGkd82YkV401+Ko/NHyrWafbPwGofa+6p/EgDJcvEkIwsMH9098w=="],
"lucide-react": ["lucide-react@1.76.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-wRVHt2Xf64GXndB4rQOY9+3Wy9oJ59HDMYv6vwhT0hpSwUxQhG/RM9YijnOmvmIQ+VI/n+1V/FKd6gP4XL2aBQ=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="],
"memoirist": ["[email protected]", "", {}, "sha512-zxTgA0mSYELa66DimuNQDvyLq36AwDlTuVRbnQtB+VuTcKWm5Qc4z3WkSpgsFWHNhexqkIooqpv4hdcqrX5Nmg=="],
@@ -726,7 +729,7 @@
"next": ["[email protected]", "", { "dependencies": { "@next/env": "16.4.3", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", "postcss": "8.5.23", "styled-jsx": "5.1.6" }, "optionalDependencies": { "@next/swc-darwin-arm64": "16.4.3", "@next/swc-darwin-x64": "16.4.3", "@next/swc-linux-arm64-gnu": "16.4.3", "@next/swc-linux-arm64-musl": "16.4.3", "@next/swc-linux-x64-gnu": "16.4.3", "@next/swc-linux-x64-musl": "16.4.3", "@next/swc-win32-arm64-msvc": "16.4.3", "@next/swc-win32-x64-msvc": "16.4.3", "sharp": "^0.35.5" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", "@playwright/test": "^1.51.1", "babel-plugin-react-compiler": "*", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "sass": "^1.3.0" }, "optionalPeers": ["@opentelemetry/api", "@playwright/test", "babel-plugin-react-compiler", "sass"], "bin": { "next": "dist/bin/next" } }, "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA=="],
"node-releases": ["[email protected]1", "", {}, "sha512-5NUN6QCxNFrS9oEA9RPS+d0AP+ooGBzzovY2JhIpDRHacPvOhHjXjUsUMX9qp4nLHZ+5jVgXB2jj/P4arGOE/g=="],
"node-releases": ["[email protected]5", "", {}, "sha512-PfvofsGQ+MiOQIPkX9fU8ELUWmy5zL74CdQaph/ismKszfFkfwXaw0cGiwbwym2hT9k5+mdyl8O5WQ1MD8EHmA=="],
"npm-run-path": ["[email protected]", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
@@ -762,9 +765,9 @@
"pkg-up": ["[email protected]", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="],
"postcss": ["[email protected]2", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g=="],
"postcss": ["[email protected]3", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="],
"postcss-selector-parser": ["postcss-selector-parser@7.1.7", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-wWBro/7hJ40ye6TPiXkUQoXKCw23xSsjriUvqd7Uls9Sso3oLiON1flc18cCdnjgCRXw4fBVqUJJeOdDTh3P3g=="],
"postcss-selector-parser": ["postcss-selector-parser@7.2.1", "", { "dependencies": { "util-deprecate": "^1.0.2" } }, "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ=="],
"powershell-utils": ["[email protected]", "", {}, "sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A=="],
@@ -800,15 +803,15 @@
"scheduler": ["[email protected]", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],
"semver": ["[email protected].1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"semver": ["[email protected].2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="],
"server-only": ["[email protected]", "", {}, "sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA=="],
"set-cookie-parser": ["[email protected].1", "", {}, "sha512-Npd1Pt+4zb3BrSZDPd2qFwRpS6b1EUEasRrO8xS0zMJi0fApXXK5YuzP0minyJnxwnFHoVoJwA55q0A0cu63gQ=="],
"set-cookie-parser": ["[email protected].3", "", {}, "sha512-bDO7NdAkLprNt3BNl3LAh0oVnOS5+WspzxOxiboo7vRIyTqj2pvFmNWYEFynSGQgpJ+7yG/9nc/aSG20UDBUpg=="],
"shadcn": ["[email protected]", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "@modelcontextprotocol/server": "^2.3.1", "@shadcn/registry": "0.2.1", "@types/validate-npm-package-name": "^4.0.2", "browserslist": "^4.29.3", "cn": "^0.2.4", "commander": "^14.0.0", "dedent": "^1.6.0", "deepmerge": "^4.3.1", "diff": "^8.0.2", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "open": "^11.0.4", "ora": "^8.2.0", "postcss": "^8.5.23", "postcss-selector-parser": "^7.1.6", "prompts": "^2.4.2", "recast": "^0.23.11", "socks": "^2.8.8", "stringify-object": "^5.0.0", "ts-morph": "^26.0.0", "tsconfig-paths": "^4.2.0", "undici": "^7.30.1", "validate-npm-package-name": "^7.0.1", "zod": "^4.2.0" }, "bin": { "shadcn": "dist/index.js" } }, "sha512-lKgq7QPFgkV/6EOrMCwvEn7ZAw/YnM/grhxzJmK4cZdw3E4F3Ut2EmWvrn2E+vzJp1y/76mxU185OSkXo9Ff+Q=="],
"sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="],
"sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" } }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="],
"shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
@@ -824,7 +827,7 @@
"source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
"source-map-js": ["[email protected].2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
"source-map-js": ["[email protected].3", "", {}, "sha512-xj+WrAkyv5Qp+t7r9N5HvCBu7g1qOe6CKRNpq22X1GGcPEQADFU54v5qsPVs3/vrUFQ7XivFrcAVKA2stI0kWA=="],
"source-map-support": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="],
@@ -840,27 +843,27 @@
"strip-final-newline": ["[email protected]", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="],
"strtok3": ["strtok3@10.6.3", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-MD8mENgyXMr2mDaDfzP3RWYDSyYQxIIou7HhCiCJiBekrsoDtUG0id3vYnjDfY9ndOEbazFXe13Qw6u/1AB8ew=="],
"strtok3": ["strtok3@10.8.0", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-e6bW3fD6V01DPmcbLfNtn0cjsiHvTKS/hivgbzqYMfHb/nLes4QQ0H5QBxlkPQayF4xv08AvlSgptGwN86Eemw=="],
"styled-jsx": ["[email protected]", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "@babel/core": "*", "babel-plugin-macros": "*", "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" }, "optionalPeers": ["@babel/core", "babel-plugin-macros"] }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="],
"styled-jsx": ["[email protected]", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="],
"systeminformation": ["[email protected].18", "", { "os": "!aix", "bin": { "systeminformation": "lib/cli.js" } }, "sha512-SF8DBQx3ypa8zDqZlezpHQ6M2g7TrqSEWpAtC4OsHCdLmi7J2WdxaSbA8/DJyEn2l/CHPrW0VFenoqoDccrw6g=="],
"systeminformation": ["[email protected].23", "", { "os": "!aix", "bin": { "systeminformation": "lib/cli.js" } }, "sha512-OBOvemo4WHf8bGMszwszn3JcFxkIMZt7adjhdgJh3eePo37EIBZovZbhJDQ2zfVYPEtXScHDJXGik8eYd3WMNw=="],
"tailwindcss": ["[email protected].3", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],
"tailwindcss": ["[email protected].5", "", {}, "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ=="],
"tapable": ["[email protected].3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
"tapable": ["[email protected].4", "", {}, "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg=="],
"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
"token-types": ["token-types@6.1.2", "", { "dependencies": { "@borewit/text-codec": "^0.2.1", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww=="],
"token-types": ["token-types@6.2.0", "", { "dependencies": { "@borewit/text-codec": "^0.2.3", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg=="],
"ts-morph": ["[email protected]", "", { "dependencies": { "@ts-morph/common": "~0.27.0", "code-block-writer": "^13.0.3" } }, "sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug=="],
"tsconfig-paths": ["[email protected]", "", { "dependencies": { "json5": "^2.2.2", "minimist": "^1.2.6", "strip-bom": "^3.0.0" } }, "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg=="],
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="],
"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw=="],
@@ -874,7 +877,7 @@
"uint8array-extras": ["[email protected]", "", {}, "sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q=="],
"undici": ["[email protected].1", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="],
"undici": ["[email protected].2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="],
"undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
@@ -882,7 +885,9 @@
"universalify": ["[email protected]", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],
"update-browserslist-db": ["update-browserslist-db@1.3.4", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A=="],
"update-browserslist-db": ["update-browserslist-db@1.4.0", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-WPJuOnjI9FWDct4fB+ej4Mz8opLaw5CDcZ2t44tFZ0vIQVYWzBhWR3mkixuUj/A7+vY4V9+ApOZ2YYLwdgq46w=="],
"uqr": ["[email protected]", "", {}, "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA=="],
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
@@ -908,27 +913,23 @@
"@dotenvx/dotenvx/open": ["[email protected]", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="],
"@esbuild-kit/core-utils/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
"@esbuild-kit/core-utils/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
"@shadcn/registry/cn": ["[email protected]", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ=="],
"@shadcn/registry/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="],
"@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected].6", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" }, "bundled": true }, "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw=="],
"@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected].7", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" }, "bundled": true }, "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ=="],
"@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/[email protected].4", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="],
"@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/[email protected].5", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA=="],
"@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.9.1", "", { "bundled": true }, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="],
"@tailwindcss/postcss/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="],
"conf/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"conf/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="],
"cross-spawn/which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
@@ -954,11 +955,9 @@
"shadcn/cn": ["[email protected]", "", { "bin": { "cn": "bin/cn.mjs" } }, "sha512-+i4L0zUGgRcEnhsxueVrP7iBGxBx5iD0WOTYg1MwFEu2ZyCmH5Ov2V1cul2Ht5UchRQQgftCf4be/RxspuW6QQ=="],
"shadcn/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg=="],
"sharp/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="],
"sharp/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"tsx/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
"tsx/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
"wsl-utils/is-wsl": ["[email protected]", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw=="],
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more