From 6d0d4b92361b2ea9394107c4143e298be7815d18 Mon Sep 17 00:00:00 2001 From: Hyo Date: Fri, 20 Nov 2026 22:19:53 +0900 Subject: [PATCH 1/2] feat: move sign-in to @convex-dev/auth 2.0 Sign-in now runs on @convex-dev/auth 2.0 components: sessions and refresh tokens in the core component, GitHub accounts in authGithub, tokens signed by the deployment. - Gitdog keeps the GitHub account id on its own users table; every lookup that read authAccounts now reads users.githubAccountId. - createUserFromGithub returns the existing user for a known GitHub id, and until migrateToAuthV2 has run it also links users from the 0.0.x authAccounts table, so nobody gets a second, empty account. - users/migrations:migrateToAuthV2 copies each GitHub account onto its user and deletes the 0.0.x auth rows; the legacy tables stay defined until it has run in production. - One-hour access tokens, as before, so GITDOG_TOKEN automation still works. - The OpenID discovery and JWKS paths 0.0.x served stay, backed by the workload keys Anthropic federation verifies. - Web: the consent page signs in with useSignInWithGithub. - CLI 0.5.0: start/complete sign-in, refreshSession and signOut; the login listener uses one of five fixed loopback ports the server allows. - Tests sign in through real 2.0 sessions (test/helpers/auth.ts); new tests cover the user callbacks and the migration, including a sign-in before it. --- .github/copilot-instructions.md | 2 +- bun.lock | 85 ++++-- convex/_generated/api.d.ts | 15 +- convex/_generated/server.d.ts | 2 + convex/_utils/auth.ts | 17 ++ convex/_utils/authRedirect.ts | 40 +-- convex/admin/mutation.ts | 2 +- convex/admin/query.ts | 2 +- convex/admin/utils.ts | 2 +- convex/apiKeys/action.ts | 2 +- convex/apiKeys/internalMutation.ts | 2 +- convex/apiKeys/mutation.ts | 2 +- convex/apiKeys/query.ts | 2 +- convex/auth.config.ts | 9 +- convex/auth.ts | 64 ++-- convex/convex.config.ts | 21 +- convex/github/action.ts | 2 +- convex/github/internalMutation.ts | 6 +- convex/github/internalQuery.ts | 76 ++--- convex/github/oauthInstallationAttestation.ts | 99 +----- convex/github/query.ts | 2 +- convex/http.ts | 39 ++- convex/invitations/action.ts | 2 +- convex/invitations/internalMutation.ts | 16 +- convex/invitations/mutation.ts | 2 +- convex/invitations/query.ts | 2 +- convex/notifications/mutation.ts | 2 +- convex/notifications/query.ts | 2 +- convex/providerApiKeys/action.ts | 2 +- convex/providerApiKeys/mutation.ts | 2 +- convex/providerApiKeys/query.ts | 2 +- convex/pullRequests/action.ts | 2 +- convex/repoIndexing/mutation.ts | 2 +- convex/repoIndexing/query.ts | 2 +- convex/repoLearnings/query.ts | 2 +- convex/repositories/action.ts | 2 +- convex/repositories/mutation.ts | 2 +- convex/repositories/query.ts | 2 +- convex/repositoryMembers/mutation.ts | 2 +- convex/repositoryMembers/query.ts | 2 +- convex/schema.ts | 5 +- convex/subscriptions/action.ts | 2 +- convex/subscriptions/mutation.ts | 2 +- convex/subscriptions/query.ts | 2 +- convex/ticketActions/action.ts | 2 +- convex/ticketActions/query.ts | 2 +- convex/tickets/mutation.ts | 2 +- convex/tickets/query.ts | 2 +- convex/tokenUsage/query.ts | 2 +- convex/users/action.ts | 2 +- convex/users/githubAccount.ts | 46 +++ convex/users/internalMutation.ts | 64 ++++ convex/users/migrations.ts | 87 ++++++ convex/users/mutation.ts | 2 +- convex/users/query.ts | 2 +- convex/users/tables.ts | 72 +++++ docs/convention.md | 4 +- docs/github-app-setup.md | 13 +- package.json | 3 +- packages/cli/README.md | 4 +- packages/cli/package.json | 2 +- packages/cli/scripts/test-dev.mjs | 32 +- packages/cli/src/auth.ts | 113 +++---- packages/cli/src/client.ts | 18 +- packages/cli/src/storage.ts | 11 +- packages/cli/src/ui.ts | 2 +- packages/cli/test/auth.test.mjs | 110 ++++--- src/main.tsx | 3 +- src/pages/legal/consent.tsx | 14 +- test/convex/admin/paymentPrivacy.test.ts | 32 +- test/convex/github/accessVerification.test.ts | 9 +- .../github/duplicateInstallations.test.ts | 17 +- .../github/installationOwnership.test.ts | 284 ++++++++---------- .../oauthInstallationAttestation.test.ts | 164 +++------- .../convex/invitations/createIdentity.test.ts | 141 ++++----- test/convex/invitations/identity.test.ts | 31 +- test/convex/invitations/queryAccess.test.ts | 31 +- .../invitations/teamEntitlementAccess.test.ts | 31 +- .../lemonSqueezy/billingSettlement.test.ts | 13 +- .../providerApiKeys/providerApiKeys.test.ts | 10 +- test/convex/pullRequests/lifecycle.test.ts | 59 ++-- .../convex/repoIndexing/fileListBound.test.ts | 29 +- .../convex/repoLearnings/trustedCount.test.ts | 7 +- .../repositories/connectIdentity.test.ts | 67 ++--- .../repositories/createScheduling.test.ts | 97 +++--- .../repositories/disconnectLifecycle.test.ts | 21 +- test/convex/repositories/queryAccess.test.ts | 46 +-- .../repositories/syncInstallation.test.ts | 45 +-- .../entitlementProvenance.test.ts | 13 +- .../subscriptions/mutationSecurity.test.ts | 36 +-- test/convex/subscriptions/trialCredit.test.ts | 5 +- .../publicRecoveryRedaction.test.ts | 5 +- test/convex/tokenUsage/chatUsage.test.ts | 7 +- test/convex/tokenUsage/numericSafety.test.ts | 5 +- test/convex/tokenUsage/periodTotals.test.ts | 17 +- .../tokenUsage/purchasedTokenBalance.test.ts | 7 +- test/convex/tokenUsage/userKeyUsage.test.ts | 15 +- test/convex/users/authRedirect.test.ts | 58 ++-- test/convex/users/authV2.test.ts | 166 ++++++++++ test/convex/users/legalAttestation.test.ts | 32 +- test/convex/users/projectApiKeys.test.ts | 5 +- test/helpers/auth.ts | 39 +++ test/pages/legalAgeCompliance.test.ts | 2 +- test/pages/legalConsentPage.test.ts | 9 +- 104 files changed, 1492 insertions(+), 1231 deletions(-) create mode 100644 convex/_utils/auth.ts create mode 100644 convex/users/githubAccount.ts create mode 100644 convex/users/internalMutation.ts create mode 100644 convex/users/migrations.ts create mode 100644 convex/users/tables.ts create mode 100644 test/convex/users/authV2.test.ts create mode 100644 test/helpers/auth.ts diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index d2ebd90..942e2b3 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -70,7 +70,7 @@ - Always use `getAuthUserId(ctx)` to check authentication: ```typescript - import { getAuthUserId } from "@convex-dev/auth/server"; + import { getAuthUserId } from "../_utils/auth"; export const myFunction = query({ args: {}, diff --git a/bun.lock b/bun.lock index ff44a9f..7d354d1 100644 --- a/bun.lock +++ b/bun.lock @@ -5,8 +5,7 @@ "": { "name": "gitdog", "dependencies": { - "@auth/core": "^0.41.3", - "@convex-dev/auth": "^0.0.98", + "@convex-dev/auth": "2.0.0", "@icons-pack/react-simple-icons": "^13.15.1", "@lemonsqueezy/lemonsqueezy.js": "^4.0.0", "@preact/signals-react": "^3.12.0", @@ -83,8 +82,6 @@ "packages": { "@alloc/quick-lru": ["@alloc/quick-lru@5.3.0", "", {}, "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA=="], - "@auth/core": ["@auth/core@0.41.3", "", { "dependencies": { "@panva/hkdf": "^1.2.1", "jose": "^6.0.6", "oauth4webapi": "^3.3.0", "preact": "10.24.3", "preact-render-to-string": "6.5.11" }, "peerDependencies": { "@simplewebauthn/browser": "^9.0.1", "@simplewebauthn/server": "^9.0.2", "nodemailer": "^7.0.7 || ^8.0.5" }, "optionalPeers": ["@simplewebauthn/browser", "@simplewebauthn/server", "nodemailer"] }, "sha512-sJ3JMHHkXMD3aOjopv7mOBTO1Ocw4b0fAEXJBz6k7YHLpYQI6C40jCUPc5fNvUKxXRXNE1/sRISA15UrwWJBTw=="], - "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], @@ -123,7 +120,11 @@ "@cacheable/utils": ["@cacheable/utils@2.5.0", "", { "dependencies": { "hashery": "^1.5.1", "keyv": "^5.6.0" } }, "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA=="], - "@convex-dev/auth": ["@convex-dev/auth@0.0.98", "", { "dependencies": { "@oslojs/crypto": "^1.0.1", "@oslojs/encoding": "^1.1.0", "cookie": "^1.0.1", "is-network-error": "^1.1.0", "jose": "^5.2.2", "jwt-decode": "^4.0.0", "lucia": "^3.2.0", "oauth4webapi": "^3.1.2", "path-to-regexp": "^6.3.0", "server-only": "^0.0.1" }, "peerDependencies": { "@auth/core": "^0.41.1", "convex": "^1.17.0", "react": "^18.2.0 || ^19.0.0-0" }, "optionalPeers": ["react"], "bin": { "auth": "dist/bin.cjs" } }, "sha512-lcgZ0V7z6bcvqTFsXjFa/ZsZclanmltGBaJMJtcdp+x7VeFv7h3+CWE+JGv402C+71itMBkQXONZxBaMe/7ocQ=="], + "@convex-dev/auth": ["@convex-dev/auth@2.0.0", "", { "dependencies": { "@convex-dev/batch-worker": "^0.3.2", "@convex-dev/rate-limiter": "^0.3.2", "@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/server": "^14.0.0", "cookie": "1.1.1", "jose": "^5.2.2", "password-hash-wasm": "0.0.0" }, "peerDependencies": { "@convex-dev/resend": "^0.2.8", "convex": "^1.48.0", "next": "^16.0.0", "react": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@convex-dev/resend", "next", "react"] }, "sha512-x8tj4BeEkm9R/SlrrVvGS4jvHle4okGM2Ldni7q0KK1lKTpX0QCMDrULagqLUVTepyik23T+TXzcAurNXL1EEg=="], + + "@convex-dev/batch-worker": ["@convex-dev/batch-worker@0.3.6", "", { "dependencies": { "convex-helpers": "^0.1.127" }, "peerDependencies": { "convex": "^1.43.0" } }, "sha512-tR+9DaHR3jG3oqkIFX0ok/6944h7UHEQgT6HTmiuxU+lERYuYMsxA2IWwFD5yTFbCpO3YJhqXU4QdGY90sgUqQ=="], + + "@convex-dev/rate-limiter": ["@convex-dev/rate-limiter@0.3.2", "", { "peerDependencies": { "convex": "^1.24.8", "react": "^18.2.0 || ^19.0.0" }, "optionalPeers": ["react"] }, "sha512-+oBPsBfFbzdxiF/9XaaTQmVnvDlvEfg/c69/v8LxTbw4VLuiflIKlfnPQL8OS0azXQQ11hcPWHmU8ytFmHKDXA=="], "@emnapi/core": ["@emnapi/core@2.0.0-beta.2", "", { "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A=="], @@ -199,6 +200,8 @@ "@eslint/plugin-kit": ["@eslint/plugin-kit@0.7.3", "", { "dependencies": { "@eslint/core": "^1.2.1", "levn": "^0.4.1" } }, "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q=="], + "@hexagon/base64": ["@hexagon/base64@1.1.28", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="], + "@humanfs/core": ["@humanfs/core@0.19.2", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="], "@humanfs/node": ["@humanfs/node@0.16.8", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="], @@ -229,19 +232,41 @@ "@lemonsqueezy/lemonsqueezy.js": ["@lemonsqueezy/lemonsqueezy.js@4.0.0", "", {}, "sha512-xcY1/lDrY7CpIF98WKiL1ElsfoVhddP7FT0fw7ssOzrFqQsr44HgolKrQZxd9SywsCPn12OTOUieqDIokI3mFg=="], + "@levischuck/tiny-cbor": ["@levischuck/tiny-cbor@0.2.11", "", {}, "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow=="], + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.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" } }, "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw=="], - "@oslojs/asn1": ["@oslojs/asn1@1.0.0", "", { "dependencies": { "@oslojs/binary": "1.0.0" } }, "sha512-zw/wn0sj0j0QKbIXfIlnEcTviaCzYOY3V5rAyjR6YtOByFtJiT574+8p9Wlach0lZH9fddD4yb9laEAIl4vXQA=="], + "@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="], - "@oslojs/binary": ["@oslojs/binary@1.0.0", "", {}, "sha512-9RCU6OwXU6p67H4NODbuxv2S3eenuQ4/WFLrsq+K/k682xrznH5EVWA7N4VFk9VYVcbFtKqur5YQQZc0ySGhsQ=="], + "@peculiar/asn1-android": ["@peculiar/asn1-android@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-AuUBRDNdWrgtnuJGXARa0Xdtq6OAD8GqezDQz6Qka7kyynMo9fzkcrtpBEHuX984uEB570BrhMZfJfkUDfpQfw=="], - "@oslojs/crypto": ["@oslojs/crypto@1.0.1", "", { "dependencies": { "@oslojs/asn1": "1.0.0", "@oslojs/binary": "1.0.0" } }, "sha512-7n08G8nWjAr/Yu3vu9zzrd0L9XnrJfpMioQcvCMxBIiF5orECHe5/3J0jmXRVvgfqMm/+4oxlQ+Sq39COYLcNQ=="], + "@peculiar/asn1-asym-key": ["@peculiar/asn1-asym-key@2.11.1", "", { "dependencies": { "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-YtXR0FbDtjHuNGvWXD4HFE7th5xYwG67O+ApDH/FZsjj5MOrWHzDvqwZ1vm6uFUJtMAkUDcF6VMPGOJ5gnLyUA=="], - "@oslojs/encoding": ["@oslojs/encoding@1.1.0", "", {}, "sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ=="], + "@peculiar/asn1-cms": ["@peculiar/asn1-cms@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "@peculiar/asn1-x509-attr": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-Bk+oatE62dW0Tzzpfk6vdQxfGGEfvuGdWgmijnKjcv7HqZCJISs85z4zw2uDArrk+R1Oel1wts/BBl7HHrtAcA=="], - "@oxc-project/types": ["@oxc-project/types@0.156.0", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="], + "@peculiar/asn1-csr": ["@peculiar/asn1-csr@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-KVfbXaKng8886/tOPG55t5K1XkTkGbR4amjIJzytXWobFU5nZgw/sKnSpa1hxP17nUSsrOF/7Mt9WUYeyLsi6Q=="], + + "@peculiar/asn1-ecc": ["@peculiar/asn1-ecc@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-7MSNji77fQa/oN3WAfwagMy8EoJFg50sW4hZ1dtr0zU1BSugit0I2DGpIdPhvkNplopQhz5bogxpn1077eaamA=="], + + "@peculiar/asn1-pfx": ["@peculiar/asn1-pfx@2.11.1", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.1", "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-rsa": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-2SN2z8qkc2hk/GgTYA8RN54wtsCDZShg9gI2Mq1vLhdj1adcv5fhTbiEmExZUaAMqlizxiEpULQDfHM5iYtn1g=="], - "@panva/hkdf": ["@panva/hkdf@1.2.1", "", {}, "sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw=="], + "@peculiar/asn1-pkcs8": ["@peculiar/asn1-pkcs8@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-HqsSrnpQghRp9SM9QSmR6fa4z/BNktnKq7928+oq4qF0VAnuHZ4cyePKvcxh9fP4taBCP/WHNItlVNsYaQm2qw=="], + + "@peculiar/asn1-pkcs9": ["@peculiar/asn1-pkcs9@2.11.1", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.1", "@peculiar/asn1-pfx": "^2.11.1", "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "@peculiar/asn1-x509-attr": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-OHFkTg8D2zYafILqFE4KPbqX8srpvd3diGDc2h2cduumawc765mOHGcuFMGvLWlL2bbCMWMmMSCtlXptsOuiPA=="], + + "@peculiar/asn1-rsa": ["@peculiar/asn1-rsa@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-6KwKGjulF489CpidZqkogNgLj6oGzgC4BL2FClM8PuJQ4t5NqT4q4a6A4vrSxBIBhMnL8hGYkLOpbVw0Vq38Tw=="], + + "@peculiar/asn1-schema": ["@peculiar/asn1-schema@2.11.1", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g=="], + + "@peculiar/asn1-x509": ["@peculiar/asn1-x509@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SXU4/X6B3FquqQAN6ARI0bFDUV7+L1WlvPEPMKzEMkstd2D7UyM0r93fv241+OjdhqAKYGx5MvV3gzZMAp0APA=="], + + "@peculiar/asn1-x509-attr": ["@peculiar/asn1-x509-attr@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-n7RKFrbTzt8pGBlZ90kmKEn1qsLTTyw7lrvHMK0xsA42kQugPk/GXYpNbEcl7DkkdVsU/one5UX7KQPfxLj8vQ=="], + + "@peculiar/asn1-x509-post-quantum": ["@peculiar/asn1-x509-post-quantum@2.11.1", "", { "dependencies": { "@peculiar/asn1-asym-key": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-yD/pxCQ97nzwF7MGAW4kRd1WVLiMPhD39HxOnAr38DfGFwbpVhPnMbq+r6WX0XUrxn4w8ulsTdUafwVl46igLA=="], + + "@peculiar/utils": ["@peculiar/utils@2.0.3", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="], + + "@peculiar/x509": ["@peculiar/x509@2.2.0", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.0", "@peculiar/asn1-csr": "^2.11.0", "@peculiar/asn1-ecc": "^2.11.0", "@peculiar/asn1-pkcs9": "^2.11.0", "@peculiar/asn1-rsa": "^2.11.0", "@peculiar/asn1-schema": "^2.11.0", "@peculiar/asn1-x509": "^2.11.0", "@peculiar/asn1-x509-post-quantum": "^2.11.0", "pvtsutils": "^1.3.6", "tslib": "^2.8.1", "tsyringe": "^4.10.0" } }, "sha512-adpW58ySPQMOUPv8pTKT3RIyCFqfUFt8X05ukPdtkQToXDVr8dMtxuenik1yx8tNFTbpApWsM/Hi5SzlIx48+Q=="], "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], @@ -285,6 +310,10 @@ "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], + "@simplewebauthn/browser": ["@simplewebauthn/browser@14.0.0", "", {}, "sha512-1odWVqeEBTl7lJ9zMKLEsmTlnyrDO5iRcTvfMKKk1WThUnp/i8JJdffdj2icP+tty159s4PgwE3BiMoEW9NFow=="], + + "@simplewebauthn/server": ["@simplewebauthn/server@14.1.0", "", { "dependencies": { "@hexagon/base64": "^1.1.27", "@levischuck/tiny-cbor": "^0.2.2", "@peculiar/asn1-android": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.1", "@peculiar/asn1-rsa": "^2.6.1", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.1", "@peculiar/asn1-x509-post-quantum": "^2.9.4", "@peculiar/x509": "^2.1.0", "reflect-metadata": "^0.2.2" } }, "sha512-HPRRBR4Vzr45+RVvbmf6JuCfGdYYcSs4Pnnnp9YSY2IABa4JKnG+wxybczoB7rmdLCOMS/mbBa2ZL/Bcz58UlA=="], + "@tailwindcss/node": ["@tailwindcss/node@4.3.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/oxide@4.3.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=="], @@ -387,6 +416,8 @@ "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], + "asn1js": ["asn1js@3.1.0", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.2.0", "tslib": "^2.8.1" } }, "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA=="], + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], @@ -425,6 +456,8 @@ "convex": ["convex@1.50.0", "", { "dependencies": { "esbuild": "0.27.0", "prettier": "^3.0.0", "ws": "8.21.0" }, "peerDependencies": { "@auth0/auth0-react": "^2.0.1", "@clerk/clerk-react": "^4.12.8 || ^5.0.0", "@clerk/react": "^6.4.3", "react": "^18.0.0 || ^19.0.0-0 || ^19.0.0" }, "optionalPeers": ["@auth0/auth0-react", "@clerk/clerk-react", "@clerk/react", "react"], "bin": { "convex": "bin/main.js" } }, "sha512-WzzCad5hyzU4zzW0ChyUGB3Mil4LgRYMYii9cyQtC24WQnfaRgkZB0IKyhIIgRm1a2IXiGJoZnVYYSfttiap3Q=="], + "convex-helpers": ["convex-helpers@0.1.136", "", { "peerDependencies": { "@standard-schema/spec": "^1.0.0", "convex": "^1.46.0", "hono": "^4.0.5", "prettier": "^3.0.0", "react": "^17.0.2 || ^18.0.0 || ^19.0.0", "typescript": "^5.5 || ^6.0.0 || ^7.0.0", "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["@standard-schema/spec", "hono", "prettier", "react", "typescript", "zod"], "bin": { "convex-helpers": "dist/bin.cjs" } }, "sha512-GoveeoUdEyg0hpCNNAjAimgn4P3mx7f8Yy5oSISck9AquxfL3NbtQesUwhZLrDkCWasK2i1COjb7ZjQseonovA=="], + "convex-test": ["convex-test@0.0.71", "", { "peerDependencies": { "convex": "^1.43.0" } }, "sha512-sHptDSWL0b2Og6to5R9/GoCHF7XGNXIAxQDJnA8UYYZa8yym9mfC03h3C47LS3Bj2BIO9lD0pKIv2H7dP+VKPA=="], "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], @@ -577,8 +610,6 @@ "is-hexadecimal": ["is-hexadecimal@2.0.1", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="], - "is-network-error": ["is-network-error@1.3.2", "", {}, "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA=="], - "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], @@ -597,8 +628,6 @@ "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], - "jwt-decode": ["jwt-decode@4.0.0", "", {}, "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA=="], - "keyv": ["keyv@5.6.0", "", { "dependencies": { "@keyv/serialize": "^1.1.1" } }, "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw=="], "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], @@ -635,8 +664,6 @@ "lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], - "lucia": ["lucia@3.2.2", "", { "dependencies": { "@oslojs/crypto": "^1.0.1", "@oslojs/encoding": "^1.1.0" } }, "sha512-P1FlFBGCMPMXu+EGdVD9W4Mjm0DqsusmKgO7Xc33mI5X1bklmsQb0hfzPhXomQr9waWIBDsiOjvr1e6BTaUqpA=="], - "lucide-react": ["lucide-react@1.73.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-fVOzGviL9mTfHenG1PbCfIceavyGlnpYNSYr+aGZHLRymAJ7DTP6KHuqt0uBkCKAoenr1UVkwSbDIYt2xIesEQ=="], "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=="], @@ -745,8 +772,6 @@ "node-releases": ["node-releases@2.0.63", "", {}, "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q=="], - "oauth4webapi": ["oauth4webapi@3.8.8", "", {}, "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng=="], - "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], @@ -759,14 +784,14 @@ "parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], + "password-hash-wasm": ["password-hash-wasm@0.0.0", "", {}, "sha512-SpVGWB4mMf8VuHM1LqrZWLPtH7B4K2vVqAZ6pAnL/eeTLtPqewwnt0DD7428xUPSDrEWd2SDoLoU4z61gj9sYw=="], + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], "path-scurry": ["path-scurry@3.0.0", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg=="], - "path-to-regexp": ["path-to-regexp@6.3.0", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="], - "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], @@ -777,10 +802,6 @@ "postcss-selector-parser": ["postcss-selector-parser@6.1.5", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-TEHFzb5KRDKaOgJ4TYE+0jyJtFbjLvkdVOu0fZ2b6MTWzoqZd4Le+61aEppWkvTlYePgOX4ATL1wsAIPMLTw6Q=="], - "preact": ["preact@10.24.3", "", {}, "sha512-Z2dPnBnMUfyQfSQ+GBdsGa16hz35YmLmtTLhM169uW944hYL6xzTYkJjC07j+Wosz733pMWx0fgON3JNw1jJQA=="], - - "preact-render-to-string": ["preact-render-to-string@6.5.11", "", { "peerDependencies": { "preact": ">=10" } }, "sha512-ubnauqoGczeGISiOh6RjX0/cdaF8v/oDXIjO85XALCQjwQP+SB4RDXXtvZ6yTYSjG+PC1QRP2AhPgCEsM2EvUw=="], - "prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="], "prettier": ["prettier@3.10.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg=="], @@ -789,6 +810,10 @@ "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + "pvtsutils": ["pvtsutils@1.3.6", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="], + + "pvutils": ["pvutils@1.2.0", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="], + "qified": ["qified@0.10.1", "", { "dependencies": { "hookified": "^2.1.1" } }, "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA=="], "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], @@ -805,6 +830,8 @@ "react-router": ["react-router@8.5.1", "", { "dependencies": { "@remix-run/route-pattern": "^0.22.1", "cookie-es": "^3.1.1" }, "peerDependencies": { "@types/react": ">=19.2.0", "@types/react-dom": ">=19.2.0", "react": ">=19.2.7", "react-dom": ">=19.2.7" }, "optionalPeers": ["@types/react", "@types/react-dom", "react-dom"] }, "sha512-5u1eQ46QjuXjNfEnLwzrnou1Bm5dquO3xjVYkkMYCudtkicD2AQHtx+fvXzPATtPJx8TW6DR1x1TDRqsfHyZBw=="], + "reflect-metadata": ["reflect-metadata@0.2.2", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="], + "rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="], "rehype-sanitize": ["rehype-sanitize@6.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="], @@ -823,8 +850,6 @@ "semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], - "server-only": ["server-only@0.0.1", "", {}, "sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA=="], - "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], @@ -867,6 +892,8 @@ "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + "tsyringe": ["tsyringe@4.10.0", "", { "dependencies": { "tslib": "^1.9.3" } }, "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw=="], + "type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="], "typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="], @@ -927,8 +954,6 @@ "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], - "@auth/core/jose": ["jose@6.2.15", "", {}, "sha512-qdF6ewcZARtef63fJ9AKKZPgxw+t7USH6HLXYcD4CrdmSvDp79rpJSPFEKc90QBeGS63u1KQtN2MZQHC0yDIzA=="], - "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], "@convex-dev/auth/jose": ["jose@5.10.0", "", {}, "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg=="], @@ -959,6 +984,8 @@ "qified/hookified": ["hookified@2.2.0", "", {}, "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA=="], + "tsyringe/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="], + "gitdog/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], } } diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index 722320f..c4054db 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -41,6 +41,7 @@ import type * as _ai_tools_executors from "../_ai/tools/executors.js"; import type * as _ai_utils from "../_ai/utils.js"; import type * as _ai_workflow from "../_ai/workflow.js"; import type * as _utils_accessControl from "../_utils/accessControl.js"; +import type * as _utils_auth from "../_utils/auth.js"; import type * as _utils_authRedirect from "../_utils/authRedirect.js"; import type * as _utils_environment from "../_utils/environment.js"; import type * as _utils_gitdogFormat from "../_utils/gitdogFormat.js"; @@ -171,10 +172,14 @@ import type * as tokenUsage_quota from "../tokenUsage/quota.js"; import type * as tokenUsage_totals from "../tokenUsage/totals.js"; import type * as tokenUsage_usageSummary from "../tokenUsage/usageSummary.js"; import type * as users_action from "../users/action.js"; +import type * as users_githubAccount from "../users/githubAccount.js"; +import type * as users_internalMutation from "../users/internalMutation.js"; import type * as users_internalQuery from "../users/internalQuery.js"; import type * as users_legal from "../users/legal.js"; +import type * as users_migrations from "../users/migrations.js"; import type * as users_mutation from "../users/mutation.js"; import type * as users_query from "../users/query.js"; +import type * as users_tables from "../users/tables.js"; import type { ApiFromModules, @@ -216,6 +221,7 @@ declare const fullApi: ApiFromModules<{ "_ai/utils": typeof _ai_utils; "_ai/workflow": typeof _ai_workflow; "_utils/accessControl": typeof _utils_accessControl; + "_utils/auth": typeof _utils_auth; "_utils/authRedirect": typeof _utils_authRedirect; "_utils/environment": typeof _utils_environment; "_utils/gitdogFormat": typeof _utils_gitdogFormat; @@ -346,10 +352,14 @@ declare const fullApi: ApiFromModules<{ "tokenUsage/totals": typeof tokenUsage_totals; "tokenUsage/usageSummary": typeof tokenUsage_usageSummary; "users/action": typeof users_action; + "users/githubAccount": typeof users_githubAccount; + "users/internalMutation": typeof users_internalMutation; "users/internalQuery": typeof users_internalQuery; "users/legal": typeof users_legal; + "users/migrations": typeof users_migrations; "users/mutation": typeof users_mutation; "users/query": typeof users_query; + "users/tables": typeof users_tables; }>; /** @@ -378,4 +388,7 @@ export declare const internal: FilterApi< FunctionReference >; -export declare const components: {}; +export declare const components: { + auth: import("@convex-dev/auth/_generated/component.js").ComponentApi<"auth">; + authGithub: import("@convex-dev/auth/components/github/_generated/component.js").ComponentApi<"authGithub">; +}; diff --git a/convex/_generated/server.d.ts b/convex/_generated/server.d.ts index f235db4..ee2c49e 100644 --- a/convex/_generated/server.d.ts +++ b/convex/_generated/server.d.ts @@ -30,6 +30,8 @@ import type { DataModel } from "./dataModel.js"; type Env = { readonly CONVEX_CLOUD_URL: string; readonly CONVEX_SITE_URL: string; + readonly GITHUB_APP_CLIENT_ID: string; + readonly GITHUB_APP_CLIENT_SECRET: string; }; /** diff --git a/convex/_utils/auth.ts b/convex/_utils/auth.ts new file mode 100644 index 0000000..95a719d --- /dev/null +++ b/convex/_utils/auth.ts @@ -0,0 +1,17 @@ +import { getAuthUserId as getSessionUserId } from "@convex-dev/auth/server"; +import type { Auth } from "convex/server"; +import type { Id } from "../_generated/dataModel"; + +type SessionLookupCtx = Parameters[0]; + +/** + * The signed-in user, from the caller's session in the auth component, or + * null. Works in queries, mutations and actions: @convex-dev/auth types its + * context after a query's runQuery, which an action's does not match. + */ +export async function getAuthUserId(ctx: { + auth: Auth; + runQuery: unknown; +}): Promise | null> { + return await getSessionUserId<"users">(ctx as SessionLookupCtx); +} diff --git a/convex/_utils/authRedirect.ts b/convex/_utils/authRedirect.ts index 6a3d3c5..6ac79e4 100644 --- a/convex/_utils/authRedirect.ts +++ b/convex/_utils/authRedirect.ts @@ -1,30 +1,14 @@ -/** Keep web redirects same-origin and allow the CLI's exact loopback URL. */ -export function resolveAuthRedirect( - redirectTo: string, - siteUrl: string, -): string { - const loopback = - /^http:\/\/127\.0\.0\.1:([1-9]\d{3,4})\/gitdog\/callback\?state=[a-f0-9]{64}$/.exec( - redirectTo, - ); - if ( - loopback && - loopback[0] === redirectTo && - Number(loopback[1]) >= 1024 && - Number(loopback[1]) <= 65535 - ) { - return redirectTo; - } +/** + * Local ports the CLI listens on for its sign-in callback, tried in order. + * @convex-dev/auth 2.0 returns only to exact origins, so the CLI cannot pick + * a random port. packages/cli/src/auth.ts lists the same ports. + */ +export const CLI_LOGIN_PORTS = [41721, 41722, 41723, 41724, 41725] as const; - const base = new URL(siteUrl); - const target = new URL(redirectTo, base); - if ( - (base.protocol === "https:" || base.protocol === "http:") && - target.origin === base.origin && - target.username === "" && - target.password === "" - ) { - return target.toString(); - } - throw new Error("Invalid authentication redirect destination"); +/** Where a sign-in may return: Gitdog's site or the CLI's loopback listener. */ +export function allowedSignInOrigins(siteUrl: string): string[] { + return [ + new URL(siteUrl).origin, + ...CLI_LOGIN_PORTS.map((port) => `http://127.0.0.1:${port}`), + ]; } diff --git a/convex/admin/mutation.ts b/convex/admin/mutation.ts index 7b0f980..34b1b72 100644 --- a/convex/admin/mutation.ts +++ b/convex/admin/mutation.ts @@ -1,5 +1,5 @@ import { mutation, type MutationCtx } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import type { Id } from "../_generated/dataModel"; diff --git a/convex/admin/query.ts b/convex/admin/query.ts index c841ec4..dc13eee 100644 --- a/convex/admin/query.ts +++ b/convex/admin/query.ts @@ -1,5 +1,5 @@ import { query, type QueryCtx } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import type { Id } from "../_generated/dataModel"; diff --git a/convex/admin/utils.ts b/convex/admin/utils.ts index 3cfd888..988ccb6 100644 --- a/convex/admin/utils.ts +++ b/convex/admin/utils.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import type { Id } from "../_generated/dataModel"; import type { MutationCtx, QueryCtx } from "../_generated/server"; diff --git a/convex/apiKeys/action.ts b/convex/apiKeys/action.ts index e92bcd0..8a231cd 100644 --- a/convex/apiKeys/action.ts +++ b/convex/apiKeys/action.ts @@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto"; import { action } from "../_generated/server"; import { internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { apiError, hashApiKey } from "./security"; diff --git a/convex/apiKeys/internalMutation.ts b/convex/apiKeys/internalMutation.ts index 45980a9..fae616f 100644 --- a/convex/apiKeys/internalMutation.ts +++ b/convex/apiKeys/internalMutation.ts @@ -1,5 +1,5 @@ import { internalMutation } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { apiError, diff --git a/convex/apiKeys/mutation.ts b/convex/apiKeys/mutation.ts index c8def11..1d4a3bf 100644 --- a/convex/apiKeys/mutation.ts +++ b/convex/apiKeys/mutation.ts @@ -1,5 +1,5 @@ import { mutation } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { apiError, ownedRepository } from "./security"; diff --git a/convex/apiKeys/query.ts b/convex/apiKeys/query.ts index 436dd53..f17b103 100644 --- a/convex/apiKeys/query.ts +++ b/convex/apiKeys/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { paginationOptsValidator } from "convex/server"; import { v } from "convex/values"; import { apiError, ownedRepository, publicKey } from "./security"; diff --git a/convex/auth.config.ts b/convex/auth.config.ts index f4eb564..991b741 100644 --- a/convex/auth.config.ts +++ b/convex/auth.config.ts @@ -1,8 +1,5 @@ +import { convexAuthProvider } from "@convex-dev/auth/server"; + export default { - providers: [ - { - domain: process.env.CONVEX_SITE_URL, - applicationID: "convex", - }, - ], + providers: [convexAuthProvider()], }; diff --git a/convex/auth.ts b/convex/auth.ts index c97deaf..5b087cc 100644 --- a/convex/auth.ts +++ b/convex/auth.ts @@ -1,43 +1,27 @@ -import { convexAuth } from "@convex-dev/auth/server"; -import GitHub from "@auth/core/providers/github"; -import type { MutationCtx } from "./_generated/server"; -import { resolveAuthRedirect } from "./_utils/authRedirect"; -import { - fetchAccessibleGitHubInstallationIds, - persistGitHubInstallationAttestation, -} from "./github/oauthInstallationAttestation"; +import { setupConvexAuth } from "@convex-dev/auth/server"; +import { setupGithub } from "@convex-dev/auth/methods/github/server"; +import { components, internal } from "./_generated/api"; +import { allowedSignInOrigins } from "./_utils/authRedirect"; -export const { auth, signIn, signOut, store } = convexAuth({ - providers: [ - GitHub({ - clientId: process.env.GITHUB_APP_CLIENT_ID, - clientSecret: process.env.GITHUB_APP_CLIENT_SECRET, - async profile(profile, tokens) { - const githubAccountId = profile.id.toString(); - const accessToken = tokens.access_token; - if (typeof accessToken !== "string" || accessToken.trim() === "") { - throw new Error("GitHub user authorization is unavailable"); - } - const githubInstallationIds = - await fetchAccessibleGitHubInstallationIds(accessToken); - return { - id: githubAccountId, - name: profile.login, // Use login (username) instead of display name - email: typeof profile.email === "string" ? profile.email : undefined, - image: profile.avatar_url, - githubAccountId, - githubInstallationIds, - }; - }, - }), - ], - callbacks: { - redirect: async ({ redirectTo }) => { - const siteUrl = process.env.SITE_URL; - if (!siteUrl) throw new Error("SITE_URL is not configured"); - return resolveAuthRedirect(redirectTo, siteUrl); - }, - createOrUpdateUser: async (ctx, args) => - await persistGitHubInstallationAttestation(ctx as MutationCtx, args), +const siteUrl = process.env.SITE_URL; +if (!siteUrl) throw new Error("SITE_URL is not configured"); + +// One-hour access tokens, as before 2.0: GITDOG_TOKEN automation sends one +// without refreshing it. +const core = setupConvexAuth({ + component: components.auth, + accessTokenTtlSeconds: 60 * 60, +}); + +export const { signOut, refreshSession, isAuthenticated } = core; + +export const { startSignInWithGithub, completeSignInWithGithub } = setupGithub( + core, + { + component: components.authGithub, + allowedRedirectOrigins: allowedSignInOrigins(siteUrl), }, +).attachUserCallbacks({ + createUser: internal.users.internalMutation.createUserFromGithub, + onSignIn: internal.users.internalMutation.updateUserFromGithub, }); diff --git a/convex/convex.config.ts b/convex/convex.config.ts index f130b16..67efac2 100644 --- a/convex/convex.config.ts +++ b/convex/convex.config.ts @@ -1,5 +1,24 @@ import { defineApp } from "convex/server"; +import { v } from "convex/values"; +import auth from "@convex-dev/auth/convex.config"; +import authGithub from "@convex-dev/auth/components/github/convex.config"; -const app = defineApp(); +const app = defineApp({ + env: { + GITHUB_APP_CLIENT_ID: v.string(), + GITHUB_APP_CLIENT_SECRET: v.string(), + }, +}); + +// Sessions and tokens live in the core; GitHub accounts in authGithub, whose +// OAuth callback is served at /oauth/github/callback. +app.use(auth); +app.use(authGithub, { + httpPrefix: "/oauth/github", + env: { + CLIENT_ID: app.env.GITHUB_APP_CLIENT_ID, + CLIENT_SECRET: app.env.GITHUB_APP_CLIENT_SECRET, + }, +}); export default app; diff --git a/convex/github/action.ts b/convex/github/action.ts index f276574..b585f42 100644 --- a/convex/github/action.ts +++ b/convex/github/action.ts @@ -1,5 +1,5 @@ import { action, internalAction, type ActionCtx } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { api, internal } from "../_generated/api"; import { v } from "convex/values"; import { diff --git a/convex/github/internalMutation.ts b/convex/github/internalMutation.ts index ccbfa17..176594b 100644 --- a/convex/github/internalMutation.ts +++ b/convex/github/internalMutation.ts @@ -2,10 +2,8 @@ import { internalMutation, type MutationCtx } from "../_generated/server"; import { v } from "convex/values"; import { internal } from "../_generated/api"; import { getExactGitHubInstallation } from "./installationAccess"; -import { - readLinkedGitHubAccountId, - saveInstallationAttestation, -} from "./oauthInstallationAttestation"; +import { saveInstallationAttestation } from "./oauthInstallationAttestation"; +import { readLinkedGitHubAccountId } from "../users/githubAccount"; import { getInstallationWebhookStateRetryDelayMs, INSTALLATION_WEBHOOK_STATE_ATTEMPT_LEASE_MS, diff --git a/convex/github/internalQuery.ts b/convex/github/internalQuery.ts index 058b40e..639eac6 100644 --- a/convex/github/internalQuery.ts +++ b/convex/github/internalQuery.ts @@ -12,6 +12,10 @@ import { GITHUB_INSTALLATION_ATTESTATION_MAX_INSTALLATIONS, GITHUB_INSTALLATION_ATTESTATION_TTL_MS, } from "./oauthInstallationAttestation"; +import { + readLinkedGitHubAccountId, + readUserIdByGitHubAccountId, +} from "../users/githubAccount"; type StaleRepositoryAccessReconciliation = | { @@ -64,51 +68,29 @@ async function readFreshOAuthInstallationAttestation( return null; } - const [user, accounts, attestations] = await Promise.all([ - ctx.db.get(userId), - ctx.db - .query("authAccounts") - .withIndex("userIdAndProvider", (q) => - q.eq("userId", userId).eq("provider", "github"), - ) - .take(2), + const [githubAccountId, attestations] = await Promise.all([ + readLinkedGitHubAccountId(ctx, userId), ctx.db .query("githubOAuthInstallationAttestations") .withIndex("by_user", (q) => q.eq("userId", userId)) .take(2), ]); - if (!user || accounts.length !== 1 || attestations.length !== 1) { + if (githubAccountId === null || attestations.length !== 1) { return null; } - const account = accounts[0]; const attestation = attestations[0]; - if (!/^[1-9]\d*$/.test(account.providerAccountId)) { - return null; - } - const [matchingAccounts, matchingAttestations] = await Promise.all([ - ctx.db - .query("authAccounts") - .withIndex("providerAndAccountId", (q) => - q - .eq("provider", "github") - .eq("providerAccountId", account.providerAccountId), - ) - .take(2), - ctx.db - .query("githubOAuthInstallationAttestations") - .withIndex("by_github_account", (q) => - q.eq("githubAccountId", account.providerAccountId), - ) - .take(2), - ]); + const matchingAttestations = await ctx.db + .query("githubOAuthInstallationAttestations") + .withIndex("by_github_account", (q) => + q.eq("githubAccountId", githubAccountId), + ) + .take(2); if ( - matchingAccounts.length !== 1 || - matchingAccounts[0]._id !== account._id || matchingAttestations.length !== 1 || matchingAttestations[0]._id !== attestation._id || attestation.userId !== userId || - attestation.githubAccountId !== account.providerAccountId || + attestation.githubAccountId !== githubAccountId || !Number.isSafeInteger(attestation.attestedAt) || attestation.attestedAt <= 0 || !Number.isSafeInteger(attestation.expiresAt) || @@ -130,7 +112,7 @@ async function readFreshOAuthInstallationAttestation( } return { - githubAccountId: account.providerAccountId, + githubAccountId, installationIds: attestation.installationIds, attestedAt: attestation.attestedAt, expiresAt: attestation.expiresAt, @@ -218,19 +200,7 @@ export const getUserIdByGithubAccountId = internalQuery({ githubAccountId: v.string(), }, handler: async (ctx, args) => { - const accounts = await ctx.db - .query("authAccounts") - .withIndex("providerAndAccountId", (q) => - q - .eq("provider", "github") - .eq("providerAccountId", args.githubAccountId), - ) - .take(2); - if (accounts.length !== 1) { - return null; - } - - return (await ctx.db.get(accounts[0].userId)) ? accounts[0].userId : null; + return await readUserIdByGitHubAccountId(ctx, args.githubAccountId); }, }); @@ -371,18 +341,8 @@ export const getLegallyEligibleUserIdByGithubAccountId = internalQuery({ githubAccountId: v.string(), }, handler: async (ctx, args) => { - if (!/^[1-9]\d*$/.test(args.githubAccountId)) return null; - const accounts = await ctx.db - .query("authAccounts") - .withIndex("providerAndAccountId", (q) => - q - .eq("provider", "github") - .eq("providerAccountId", args.githubAccountId), - ) - .take(2); - if (accounts.length !== 1) return null; - const userId = accounts[0].userId; - if (!(await ctx.db.get(userId))) return null; + const userId = await readUserIdByGitHubAccountId(ctx, args.githubAccountId); + if (userId === null) return null; const profiles = await ctx.db .query("userProfiles") .withIndex("by_user", (q) => q.eq("userId", userId)) diff --git a/convex/github/oauthInstallationAttestation.ts b/convex/github/oauthInstallationAttestation.ts index 20da29d..b1709c4 100644 --- a/convex/github/oauthInstallationAttestation.ts +++ b/convex/github/oauthInstallationAttestation.ts @@ -1,23 +1,12 @@ import type { Id } from "../_generated/dataModel"; import type { MutationCtx } from "../_generated/server"; +import { readGitHubAccountId } from "../users/githubAccount"; export const GITHUB_INSTALLATION_ATTESTATION_TTL_MS = 15 * 60 * 1_000; export const GITHUB_INSTALLATION_ATTESTATION_PAGE_SIZE = 100; export const GITHUB_INSTALLATION_ATTESTATION_MAX_INSTALLATIONS = 500; export const GITHUB_INSTALLATION_ATTESTATION_REQUEST_TIMEOUT_MS = 10_000; -type GitHubOAuthProfile = Record & { - githubAccountId?: unknown; - githubInstallationIds?: unknown; -}; - -type GitHubOAuthUserArgs = { - existingUserId: Id<"users"> | null; - type: "oauth" | "credentials" | "email" | "phone" | "verification"; - provider: { id: string; type: string }; - profile: GitHubOAuthProfile; -}; - function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } @@ -28,12 +17,6 @@ function readPositiveSafeInteger(value: unknown): number | null { : null; } -function readGitHubAccountId(value: unknown): string | null { - if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) return null; - const numericId = Number(value); - return Number.isSafeInteger(numericId) ? value : null; -} - function normalizeInstallationIds(value: unknown): number[] | null { if ( !Array.isArray(value) || @@ -52,12 +35,10 @@ function normalizeInstallationIds(value: unknown): number[] | null { return Array.from(installationIds).sort((left, right) => left - right); } -function readOptionalProfileString(value: unknown): string | undefined { - return typeof value === "string" && value.trim() !== "" ? value : undefined; -} - /** Headers for GitHub's REST API with the given Authorization value. */ -export function githubApiHeaders(authorization: string): HeadersInit { +export function githubApiHeaders( + authorization: string, +): Record { return { Accept: "application/vnd.github+json", Authorization: authorization, @@ -158,78 +139,6 @@ export async function fetchAccessibleGitHubInstallationIds( throw new Error("GitHub installation access exceeds the supported limit"); } -/** Persist only a short-lived installation snapshot, never the OAuth token. */ -export async function persistGitHubInstallationAttestation( - ctx: MutationCtx, - args: GitHubOAuthUserArgs, -): Promise> { - if ( - args.type !== "oauth" || - args.provider.id !== "github" || - args.provider.type !== "oauth" - ) { - throw new Error("Unsupported authentication provider"); - } - - const githubAccountId = readGitHubAccountId(args.profile.githubAccountId); - const installationIds = normalizeInstallationIds( - args.profile.githubInstallationIds, - ); - if (githubAccountId === null || installationIds === null) { - throw new Error("GitHub installation attestation is invalid"); - } - - const now = Date.now(); - const email = readOptionalProfileString(args.profile.email); - const userFields = { - name: readOptionalProfileString(args.profile.name), - image: readOptionalProfileString(args.profile.image), - email, - emailVerificationTime: email === undefined ? undefined : now, - }; - - let userId = args.existingUserId; - if (userId === null) { - userId = await ctx.db.insert("users", userFields); - } else { - const [user, linkedAccountId] = await Promise.all([ - ctx.db.get(userId), - readLinkedGitHubAccountId(ctx, userId), - ]); - if (!user || linkedAccountId !== githubAccountId) { - throw new Error("GitHub account identity changed during sign-in"); - } - await ctx.db.patch(userId, userFields); - } - - await saveInstallationAttestation(ctx, { - userId, - githubAccountId, - installationIds, - now, - }); - return userId; -} - -/** - * The GitHub account id linked to a Gitdog user, or null when the user has - * none or more than one. Installation access is attested against it. - */ -export async function readLinkedGitHubAccountId( - ctx: Pick, - userId: Id<"users">, -): Promise { - const accounts = await ctx.db - .query("authAccounts") - .withIndex("userIdAndProvider", (q) => - q.eq("userId", userId).eq("provider", "github"), - ) - .take(2); - return accounts.length === 1 - ? readGitHubAccountId(accounts[0].providerAccountId) - : null; -} - /** * Replace the user's short-lived installation snapshot. One snapshot exists * per user and per GitHub account, and they must be the same row. diff --git a/convex/github/query.ts b/convex/github/query.ts index b5c0e2e..f3cd159 100644 --- a/convex/github/query.ts +++ b/convex/github/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import type { Doc } from "../_generated/dataModel"; import { getExactGitHubInstallation } from "./installationAccess"; diff --git a/convex/http.ts b/convex/http.ts index a29dd3b..29bcffd 100644 --- a/convex/http.ts +++ b/convex/http.ts @@ -1,6 +1,5 @@ import { httpRouter } from "convex/server"; import { httpAction } from "./_generated/server"; -import { auth } from "./auth"; import { projectApi } from "./apiKeys/http"; import { verifyWebhookSignature, @@ -24,7 +23,6 @@ import { handlePullRequestEvent } from "./pullRequests/webhook"; const http = httpRouter(); -auth.addHttpRoutes(http); http.route({ path: "/v1/cli", method: "POST", handler: projectApi }); http.route({ path: ACCESS_VERIFICATION_CALLBACK_PATH, @@ -32,21 +30,34 @@ http.route({ handler: accessVerificationCallback, }); +// Public keys for the workload assertions Gitdog signs for Anthropic +// federation. @convex-dev/auth 0.0.x served the same keys at the OpenID +// discovery paths under CONVEX_SITE_URL, the assertions' issuer, so those +// stay too; 2.0 signs sign-in tokens with the deployment's own keys. +const workloadJwks = httpAction(async () => { + try { + const keys = await getWorkloadJwks(process.env.JWKS ?? ""); + return Response.json(keys, { + headers: { "Cache-Control": "public, max-age=60" }, + }); + } catch { + return Response.json( + { error: "Workload public keys unavailable" }, + { status: 503 }, + ); + } +}); +for (const path of [WORKLOAD_JWKS_PATH, "/.well-known/jwks.json"]) + http.route({ path, method: "GET", handler: workloadJwks }); http.route({ - path: WORKLOAD_JWKS_PATH, + path: "/.well-known/openid-configuration", method: "GET", handler: httpAction(async () => { - try { - const keys = await getWorkloadJwks(process.env.JWKS ?? ""); - return Response.json(keys, { - headers: { "Cache-Control": "public, max-age=60" }, - }); - } catch { - return Response.json( - { error: "Workload public keys unavailable" }, - { status: 503 }, - ); - } + const issuer = process.env.CONVEX_SITE_URL ?? ""; + return Response.json( + { issuer, jwks_uri: `${issuer}/.well-known/jwks.json` }, + { headers: { "Cache-Control": "public, max-age=60" } }, + ); }), }); diff --git a/convex/invitations/action.ts b/convex/invitations/action.ts index 7636eef..1c2ec27 100644 --- a/convex/invitations/action.ts +++ b/convex/invitations/action.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; diff --git a/convex/invitations/internalMutation.ts b/convex/invitations/internalMutation.ts index 88220ac..d7e82be 100644 --- a/convex/invitations/internalMutation.ts +++ b/convex/invitations/internalMutation.ts @@ -1,4 +1,5 @@ import { v } from "convex/values"; +import { readUserIdByGitHubAccountId } from "../users/githubAccount"; import { internalMutation } from "../_generated/server"; import { checkProSubscription } from "../_utils/accessControl"; import { @@ -59,18 +60,13 @@ export const create = internalMutation({ throw new Error("GitHub App installation is not ready"); } - const account = await ctx.db - .query("authAccounts") - .withIndex("providerAndAccountId", (q) => - q - .eq("provider", "github") - .eq("providerAccountId", args.githubAccountId.toString()), - ) - .unique(); - if (!account || !(await ctx.db.get(account.userId))) { + const inviteeUserId = await readUserIdByGitHubAccountId( + ctx, + args.githubAccountId.toString(), + ); + if (!inviteeUserId) { throw new Error("User not found. They must have a Gitdog account."); } - const inviteeUserId = account.userId; if (inviteeUserId === repository.userId) { throw new Error("User is already a member of this repository"); diff --git a/convex/invitations/mutation.ts b/convex/invitations/mutation.ts index d173695..56bbb11 100644 --- a/convex/invitations/mutation.ts +++ b/convex/invitations/mutation.ts @@ -1,5 +1,5 @@ import { mutation } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { hasLiveOwnerTeamEntitlement } from "../_utils/accessControl"; import { diff --git a/convex/invitations/query.ts b/convex/invitations/query.ts index f2484d6..ae3679a 100644 --- a/convex/invitations/query.ts +++ b/convex/invitations/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { checkRepositoryAccess } from "../_utils/accessControl"; import { getInvitationUnavailableReason } from "./availability"; diff --git a/convex/notifications/mutation.ts b/convex/notifications/mutation.ts index e3359bb..a26e8cc 100644 --- a/convex/notifications/mutation.ts +++ b/convex/notifications/mutation.ts @@ -1,5 +1,5 @@ import { mutation } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; export const markAsRead = mutation({ diff --git a/convex/notifications/query.ts b/convex/notifications/query.ts index 3437cea..a26cf8e 100644 --- a/convex/notifications/query.ts +++ b/convex/notifications/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; export const listUnread = query({ diff --git a/convex/providerApiKeys/action.ts b/convex/providerApiKeys/action.ts index e80cc19..51427c8 100644 --- a/convex/providerApiKeys/action.ts +++ b/convex/providerApiKeys/action.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { ConvexError, v } from "convex/values"; import { internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; diff --git a/convex/providerApiKeys/mutation.ts b/convex/providerApiKeys/mutation.ts index 54fa540..07c7c11 100644 --- a/convex/providerApiKeys/mutation.ts +++ b/convex/providerApiKeys/mutation.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { mutation } from "../_generated/server"; import { apiError } from "../apiKeys/security"; diff --git a/convex/providerApiKeys/query.ts b/convex/providerApiKeys/query.ts index 2b214ab..25a00f3 100644 --- a/convex/providerApiKeys/query.ts +++ b/convex/providerApiKeys/query.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { query } from "../_generated/server"; import { readEncryptionState } from "./encryptionState"; import { USER_KEY_MODELS, userKeyModel } from "../_ai/config"; diff --git a/convex/pullRequests/action.ts b/convex/pullRequests/action.ts index 745b051..4b346d9 100644 --- a/convex/pullRequests/action.ts +++ b/convex/pullRequests/action.ts @@ -1,6 +1,6 @@ import { action } from "../_generated/server"; import { internal } from "../_generated/api"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import type { Id } from "../_generated/dataModel"; import { resolveVerifiedRepositoryAccess } from "../github/repositoryIdentity"; diff --git a/convex/repoIndexing/mutation.ts b/convex/repoIndexing/mutation.ts index 86f8c12..e02597b 100644 --- a/convex/repoIndexing/mutation.ts +++ b/convex/repoIndexing/mutation.ts @@ -5,7 +5,7 @@ import { } from "../_generated/server"; import { internal } from "../_generated/api"; import type { Doc, Id } from "../_generated/dataModel"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { coalesceIndexSyncSource, diff --git a/convex/repoIndexing/query.ts b/convex/repoIndexing/query.ts index 7ce2123..66aec9a 100644 --- a/convex/repoIndexing/query.ts +++ b/convex/repoIndexing/query.ts @@ -1,6 +1,6 @@ import { query, type QueryCtx } from "../_generated/server"; import type { Doc, Id } from "../_generated/dataModel"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { checkRepositoryAccess } from "../_utils/accessControl"; import { diff --git a/convex/repoLearnings/query.ts b/convex/repoLearnings/query.ts index f4a27e3..8699dbc 100644 --- a/convex/repoLearnings/query.ts +++ b/convex/repoLearnings/query.ts @@ -1,6 +1,6 @@ import { query } from "../_generated/server"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { getTrustedLearningRepositoryKey } from "./trust"; /** diff --git a/convex/repositories/action.ts b/convex/repositories/action.ts index bcbd47b..5d8e68a 100644 --- a/convex/repositories/action.ts +++ b/convex/repositories/action.ts @@ -2,7 +2,7 @@ import { action, type ActionCtx } from "../_generated/server"; import { api, internal } from "../_generated/api"; import type { Id } from "../_generated/dataModel"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { fetchGitHubAppJsonWithRetry, getRepositoryInstallationToken, diff --git a/convex/repositories/mutation.ts b/convex/repositories/mutation.ts index e551380..921bd77 100644 --- a/convex/repositories/mutation.ts +++ b/convex/repositories/mutation.ts @@ -6,7 +6,7 @@ import { } from "../_generated/server"; import { internal } from "../_generated/api"; import type { Doc, Id } from "../_generated/dataModel"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { armIndexWatchdog, diff --git a/convex/repositories/query.ts b/convex/repositories/query.ts index 08fbee7..684853a 100644 --- a/convex/repositories/query.ts +++ b/convex/repositories/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { paginatedCollect } from "../_utils/pagination"; import { diff --git a/convex/repositoryMembers/mutation.ts b/convex/repositoryMembers/mutation.ts index 7349f20..b4f70d9 100644 --- a/convex/repositoryMembers/mutation.ts +++ b/convex/repositoryMembers/mutation.ts @@ -1,5 +1,5 @@ import { mutation } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { checkRepositoryAccess } from "../_utils/accessControl"; diff --git a/convex/repositoryMembers/query.ts b/convex/repositoryMembers/query.ts index 89ae413..e7d33f6 100644 --- a/convex/repositoryMembers/query.ts +++ b/convex/repositoryMembers/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { checkRepositoryAccess } from "../_utils/accessControl"; diff --git a/convex/schema.ts b/convex/schema.ts index 8733448..2f8c90e 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -1,6 +1,6 @@ import { defineSchema, defineTable } from "convex/server"; import { v } from "convex/values"; -import { authTables } from "@convex-dev/auth/server"; +import { legacyAuthTables, usersTable } from "./users/tables"; import { chatRecoveryTargetValidator } from "./_ai/chatRecovery"; import { reviewBatchResultValidator } from "./pullRequests/review"; import { reviewTraceStepValidator } from "./pullRequests/records"; @@ -1855,6 +1855,7 @@ const applicationTables = { }; export default defineSchema({ - ...authTables, + users: usersTable, + ...legacyAuthTables, ...applicationTables, }); diff --git a/convex/subscriptions/action.ts b/convex/subscriptions/action.ts index 509cb95..17e7fab 100644 --- a/convex/subscriptions/action.ts +++ b/convex/subscriptions/action.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { createCheckout, lemonSqueezySetup, diff --git a/convex/subscriptions/mutation.ts b/convex/subscriptions/mutation.ts index dfea92a..44fd366 100644 --- a/convex/subscriptions/mutation.ts +++ b/convex/subscriptions/mutation.ts @@ -1,4 +1,4 @@ -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { mutation } from "../_generated/server"; import { settleThenGrantTrialCredit } from "./credit"; diff --git a/convex/subscriptions/query.ts b/convex/subscriptions/query.ts index 36f8955..c061f30 100644 --- a/convex/subscriptions/query.ts +++ b/convex/subscriptions/query.ts @@ -1,7 +1,7 @@ // Matches the wallet row bound in wallet.ts. const MAX_WALLET_ROWS = 100; import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { PRICING, CHAT_MODELS, diff --git a/convex/ticketActions/action.ts b/convex/ticketActions/action.ts index 096ab31..5dcd456 100644 --- a/convex/ticketActions/action.ts +++ b/convex/ticketActions/action.ts @@ -1,7 +1,7 @@ import { action } from "../_generated/server"; import { v } from "convex/values"; import { internal } from "../_generated/api"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { updateIssue, addIssueComment, diff --git a/convex/ticketActions/query.ts b/convex/ticketActions/query.ts index 5cd0c8b..765c708 100644 --- a/convex/ticketActions/query.ts +++ b/convex/ticketActions/query.ts @@ -1,6 +1,6 @@ import { query } from "../_generated/server"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { paginatedCollect } from "../_utils/pagination"; import type { Doc } from "../_generated/dataModel"; diff --git a/convex/tickets/mutation.ts b/convex/tickets/mutation.ts index a52e329..db756c6 100644 --- a/convex/tickets/mutation.ts +++ b/convex/tickets/mutation.ts @@ -1,6 +1,6 @@ import { mutation } from "../_generated/server"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; /** * Soft delete a ticket diff --git a/convex/tickets/query.ts b/convex/tickets/query.ts index 8f30826..7bc1b44 100644 --- a/convex/tickets/query.ts +++ b/convex/tickets/query.ts @@ -1,6 +1,6 @@ import { query } from "../_generated/server"; import { v } from "convex/values"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { paginatedCollect } from "../_utils/pagination"; import type { Doc } from "../_generated/dataModel"; import { toPublicTicketAction } from "../ticketActions/query"; diff --git a/convex/tokenUsage/query.ts b/convex/tokenUsage/query.ts index afaa849..325da98 100644 --- a/convex/tokenUsage/query.ts +++ b/convex/tokenUsage/query.ts @@ -1,7 +1,7 @@ import { v } from "convex/values"; import { query, type QueryCtx } from "../_generated/server"; import type { Doc, Id } from "../_generated/dataModel"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { MAX_COLLECT_LIMIT } from "../_utils/pagination"; import { getSubscriptionForEntitlement } from "../subscriptions/entitlement"; import { readEffectiveSubscriptionQuota } from "../subscriptions/quotaEntitlement"; diff --git a/convex/users/action.ts b/convex/users/action.ts index ddf710b..36a0a33 100644 --- a/convex/users/action.ts +++ b/convex/users/action.ts @@ -1,5 +1,5 @@ import { action } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { api, internal } from "../_generated/api"; export const ensureProfile = action({ diff --git a/convex/users/githubAccount.ts b/convex/users/githubAccount.ts new file mode 100644 index 0000000..64284f7 --- /dev/null +++ b/convex/users/githubAccount.ts @@ -0,0 +1,46 @@ +import type { Id } from "../_generated/dataModel"; +import type { QueryCtx } from "../_generated/server"; + +type ReadCtx = Pick; + +/** A GitHub user id: a positive integer, as a string. */ +export function readGitHubAccountId(value: unknown): string | null { + if (typeof value !== "string" || !/^[1-9]\d*$/.test(value)) return null; + return Number.isSafeInteger(Number(value)) ? value : null; +} + +/** + * The one Gitdog user signed in with this GitHub account, or null when none + * or, against the invariant, more than one claims it. + */ +export async function readUserIdByGitHubAccountId( + ctx: ReadCtx, + value: string, +): Promise | null> { + const githubAccountId = readGitHubAccountId(value); + if (githubAccountId === null) return null; + const owners = await ctx.db + .query("users") + .withIndex("by_github_account_id", (q) => + q.eq("githubAccountId", githubAccountId), + ) + .take(2); + return owners.length === 1 ? owners[0]._id : null; +} + +/** + * The GitHub account a Gitdog user signs in with, or null when the user has + * none or another user claims the same account. Installation access is + * attested against it. + */ +export async function readLinkedGitHubAccountId( + ctx: ReadCtx, + userId: Id<"users">, +): Promise { + const user = await ctx.db.get(userId); + const githubAccountId = readGitHubAccountId(user?.githubAccountId); + if (githubAccountId === null) return null; + return (await readUserIdByGitHubAccountId(ctx, githubAccountId)) === userId + ? githubAccountId + : null; +} diff --git a/convex/users/internalMutation.ts b/convex/users/internalMutation.ts new file mode 100644 index 0000000..b9b3342 --- /dev/null +++ b/convex/users/internalMutation.ts @@ -0,0 +1,64 @@ +import { v } from "convex/values"; +import { vGithubProfile } from "@convex-dev/auth/methods/github/server"; +import type { GithubProfile } from "@convex-dev/auth/methods/github/server"; +import { internalMutation } from "../_generated/server"; +import { readLegacyGitHubUserId } from "./migrations"; + +const githubSignIn = v.object({ + name: v.literal("github"), + profile: vGithubProfile, +}); + +function profileFields(profile: GithubProfile, now: number) { + return { + name: profile.login, + image: profile.avatarUrl, + email: profile.email, + emailVerificationTime: profile.emailVerified ? now : undefined, + }; +} + +/** + * Create the Gitdog user for a GitHub account the GitHub auth component has + * not seen. A user who already has that GitHub account is returned instead: + * every user from before @convex-dev/auth 2.0 reaches this on their first + * 2.0 sign-in, so this is how they keep their account. + */ +export const createUserFromGithub = internalMutation({ + args: { method: githubSignIn }, + returns: v.id("users"), + handler: async (ctx, { method }) => { + const githubAccountId = method.profile.id; + const existing = await ctx.db + .query("users") + .withIndex("by_github_account_id", (q) => + q.eq("githubAccountId", githubAccountId), + ) + .unique(); + if (existing) return existing._id; + // Signed in after the 2.0 deploy but before migrateToAuthV2 linked them. + const legacy = await readLegacyGitHubUserId(ctx, githubAccountId); + if (legacy) { + await ctx.db.patch(legacy, { githubAccountId }); + return legacy; + } + return await ctx.db.insert("users", { + ...profileFields(method.profile, Date.now()), + githubAccountId: method.profile.id, + }); + }, +}); + +/** Refresh the user's GitHub profile on every sign-in. */ +export const updateUserFromGithub = internalMutation({ + args: { method: githubSignIn, userId: v.id("users") }, + returns: v.null(), + handler: async (ctx, { method, userId }) => { + const user = await ctx.db.get(userId); + if (!user) throw new Error("User not found"); + if (user.githubAccountId !== method.profile.id) + throw new Error("GitHub account identity changed during sign-in"); + await ctx.db.patch(userId, profileFields(method.profile, Date.now())); + return null; + }, +}); diff --git a/convex/users/migrations.ts b/convex/users/migrations.ts new file mode 100644 index 0000000..87c8f26 --- /dev/null +++ b/convex/users/migrations.ts @@ -0,0 +1,87 @@ +import { v } from "convex/values"; +import type { Id } from "../_generated/dataModel"; +import { internalMutation, type QueryCtx } from "../_generated/server"; + +// Everything here goes once production has run migrateToAuthV2 and the +// legacy tables are dropped from the schema. + +/** + * The user a GitHub account belonged to under @convex-dev/auth 0.0.x, for a + * sign-in that lands before migrateToAuthV2 has linked it. + */ +export async function readLegacyGitHubUserId( + ctx: Pick, + githubAccountId: string, +): Promise | null> { + const account = await ctx.db + .query("authAccounts") + .withIndex("providerAndAccountId", (q) => + q.eq("provider", "github").eq("providerAccountId", githubAccountId), + ) + .unique(); + return account && (await ctx.db.get(account.userId)) ? account.userId : null; +} + +const LEGACY_AUTH_TABLES = [ + "authAccounts", + "authSessions", + "authRefreshTokens", + "authVerificationCodes", + "authVerifiers", + "authRateLimits", +] as const; +const MIGRATION_BATCH = 1_000; + +/** + * One-off move from @convex-dev/auth 0.0.x to 2.0: copy each GitHub account + * onto its user, then delete the old auth rows. Deleting sessions and refresh + * tokens signs every client out. Run it until `done` is true; each run handles + * one bounded batch. + */ +export const migrateToAuthV2 = internalMutation({ + args: {}, + returns: v.object({ + linkedUsers: v.number(), + deletedRows: v.number(), + done: v.boolean(), + }), + handler: async (ctx) => { + const accounts = await ctx.db.query("authAccounts").take(MIGRATION_BATCH); + let linkedUsers = 0; + for (const account of accounts) { + if (account.provider !== "github") continue; + const user = await ctx.db.get(account.userId); + if (!user) continue; + if (user.githubAccountId === account.providerAccountId) continue; + const claimed = await ctx.db + .query("users") + .withIndex("by_github_account_id", (q) => + q.eq("githubAccountId", account.providerAccountId), + ) + .first(); + if (user.githubAccountId !== undefined || claimed) + throw new Error( + `GitHub account ${account.providerAccountId} conflicts with an existing link`, + ); + await ctx.db.patch(user._id, { + githubAccountId: account.providerAccountId, + }); + linkedUsers++; + } + + let deletedRows = 0; + for (const table of LEGACY_AUTH_TABLES) { + const rows = await ctx.db + .query(table) + .take(MIGRATION_BATCH - deletedRows); + for (const row of rows) await ctx.db.delete(row._id); + deletedRows += rows.length; + if (deletedRows >= MIGRATION_BATCH) break; + } + return { + linkedUsers, + deletedRows, + done: deletedRows < MIGRATION_BATCH, + }; + }, +}); diff --git a/convex/users/mutation.ts b/convex/users/mutation.ts index 6a3cc7e..abf3564 100644 --- a/convex/users/mutation.ts +++ b/convex/users/mutation.ts @@ -1,6 +1,6 @@ import { internal } from "../_generated/api"; import { internalMutation, mutation } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { canAcceptDisplayedLegalPolicyVersion, diff --git a/convex/users/query.ts b/convex/users/query.ts index 059eed0..be93dd5 100644 --- a/convex/users/query.ts +++ b/convex/users/query.ts @@ -1,5 +1,5 @@ import { query } from "../_generated/server"; -import { getAuthUserId } from "@convex-dev/auth/server"; +import { getAuthUserId } from "../_utils/auth"; import { v } from "convex/values"; import { hasCurrentLegalAttestation, diff --git a/convex/users/tables.ts b/convex/users/tables.ts new file mode 100644 index 0000000..ddafc0b --- /dev/null +++ b/convex/users/tables.ts @@ -0,0 +1,72 @@ +import { defineTable } from "convex/server"; +import { v } from "convex/values"; + +/** + * Gitdog's users. @convex-dev/auth 2.0 stores only the ids the sign-in + * callbacks return, so the GitHub account a user signs in with is kept here. + */ +export const usersTable = defineTable({ + name: v.optional(v.string()), + image: v.optional(v.string()), + email: v.optional(v.string()), + emailVerificationTime: v.optional(v.number()), + // The GitHub user id (numeric, as a string) the user signs in with. + githubAccountId: v.optional(v.string()), + // Written by @convex-dev/auth 0.0.x for methods Gitdog never enabled. + phone: v.optional(v.string()), + phoneVerificationTime: v.optional(v.number()), + isAnonymous: v.optional(v.boolean()), +}).index("by_github_account_id", ["githubAccountId"]); + +/** + * The tables of @convex-dev/auth 0.0.x. Kept only until migrateToAuthV2 has + * copied each GitHub account into users.githubAccountId, then removed. The + * GitHub auth component records each account on its first 2.0 sign-in. + */ +export const legacyAuthTables = { + authSessions: defineTable({ + userId: v.id("users"), + expirationTime: v.number(), + }).index("userId", ["userId"]), + authAccounts: defineTable({ + userId: v.id("users"), + provider: v.string(), + providerAccountId: v.string(), + secret: v.optional(v.string()), + emailVerified: v.optional(v.string()), + phoneVerified: v.optional(v.string()), + }) + .index("userIdAndProvider", ["userId", "provider"]) + .index("providerAndAccountId", ["provider", "providerAccountId"]), + authRefreshTokens: defineTable({ + sessionId: v.id("authSessions"), + expirationTime: v.number(), + firstUsedTime: v.optional(v.number()), + parentRefreshTokenId: v.optional(v.id("authRefreshTokens")), + }) + .index("sessionId", ["sessionId"]) + .index("sessionIdAndParentRefreshTokenId", [ + "sessionId", + "parentRefreshTokenId", + ]), + authVerificationCodes: defineTable({ + accountId: v.id("authAccounts"), + provider: v.string(), + code: v.string(), + expirationTime: v.number(), + verifier: v.optional(v.string()), + emailVerified: v.optional(v.string()), + phoneVerified: v.optional(v.string()), + }) + .index("accountId", ["accountId"]) + .index("code", ["code"]), + authVerifiers: defineTable({ + sessionId: v.optional(v.id("authSessions")), + signature: v.optional(v.string()), + }).index("signature", ["signature"]), + authRateLimits: defineTable({ + identifier: v.string(), + lastAttemptTime: v.number(), + attemptsLeft: v.number(), + }).index("identifier", ["identifier"]), +}; diff --git a/docs/convention.md b/docs/convention.md index 57ef3ad..6dbb308 100644 --- a/docs/convention.md +++ b/docs/convention.md @@ -86,11 +86,11 @@ ### Authentication in Convex Functions -- Always use `getAuthUserId(ctx)` from `@convex-dev/auth/server` to check authentication +- Always use `getAuthUserId(ctx)` from `convex/_utils/auth.ts` to check authentication - Example: ```typescript - import { getAuthUserId } from "@convex-dev/auth/server"; + import { getAuthUserId } from "../_utils/auth"; export const myFunction = query({ args: {}, diff --git a/docs/github-app-setup.md b/docs/github-app-setup.md index 8ba0dd6..ad17077 100644 --- a/docs/github-app-setup.md +++ b/docs/github-app-setup.md @@ -25,8 +25,8 @@ Go to: `VITE_GITHUB_APP_SLUG` (the local default slug is `gitdogbot-dev`) - **Homepage URL**: `http://localhost:5173` (production: `https://gitdog.dev`) - **Callback URLs** (add both): - - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/api/auth/callback/github`, the - sign-in callback + - `${CONVEX_SITE_URL}/oauth/github/callback`, the sign-in callback served + by the `authGithub` component of `@convex-dev/auth` - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/github/access/callback`, the "Verify GitHub access" callback that records which installations a signed-in user can reach @@ -236,11 +236,10 @@ For production deployment: 1. Update GitHub App settings: - Homepage URL: `https://gitdog.dev` - - Callback URL: - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/api/auth/callback/github` and - `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/github/access/callback`, - using the concrete production custom auth site URL when configured and the - concrete production Convex site URL otherwise + - Callback URLs: the concrete production + `${CONVEX_SITE_URL}/oauth/github/callback`, and + `${CUSTOM_AUTH_SITE_URL ?? CONVEX_SITE_URL}/github/access/callback` using + the production custom auth site URL when configured - Setup URL: `https://gitdog.dev/repositories/connect` - Redirect on update: ✅ Checked - Webhook URL: `https://your-production.convex.site/github/webhook` diff --git a/package.json b/package.json index d0c14bc..fa1b58a 100644 --- a/package.json +++ b/package.json @@ -41,8 +41,7 @@ ] }, "dependencies": { - "@auth/core": "^0.41.3", - "@convex-dev/auth": "^0.0.98", + "@convex-dev/auth": "2.0.0", "@icons-pack/react-simple-icons": "^13.15.1", "@lemonsqueezy/lemonsqueezy.js": "^4.0.0", "@preact/signals-react": "^3.12.0", diff --git a/packages/cli/README.md b/packages/cli/README.md index d14de75..3185e8d 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -20,7 +20,7 @@

- Gitdog terminal: connect a project, configure automation and review pending actions + Gitdog terminal: connect a project, configure automation and review pending actions

Connect repositories, configure issue, discussion and PR automation, review @@ -69,7 +69,7 @@ Use `npx gitdog@latest --help` to explore commands. Add `--json` for scripts. ```sh npx gitdog@latest keys create --name ci -npx --yes gitdog@0.4.2 --key-file /path/to/key.json projects list --json +npx --yes gitdog@0.5.0 --key-file /path/to/key.json projects list --json npx gitdog@latest keys revoke KEY_ID --yes ``` diff --git a/packages/cli/package.json b/packages/cli/package.json index e31cb1a..d71c53a 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "gitdog", - "version": "0.4.2", + "version": "0.5.0", "description": "Manage Gitdog projects, GitHub automation and API keys from your terminal", "type": "module", "bin": { diff --git a/packages/cli/scripts/test-dev.mjs b/packages/cli/scripts/test-dev.mjs index 9f64424..b8548df 100644 --- a/packages/cli/scripts/test-dev.mjs +++ b/packages/cli/scripts/test-dev.mjs @@ -146,11 +146,35 @@ async function insert(table, documents) { matches.forEach((row) => owned.add(row._id)); return matches; } +const SESSION_SECONDS = 30 * 24 * 60 * 60; +/** Mint a real @convex-dev/auth session for userId in the core component. */ async function session(role, userId) { - const result = await admin("auth:store", { - args: { type: "signIn", userId, generateTokens: true }, - }); - assert.equal(typeof result.tokens?.token, "string"); + const minted = await exec( + "bunx", + [ + "convex", + "run", + "--deployment", + deployment, + "--component", + "auth", + "public:_internal_dangerous_signIn", + JSON.stringify({ + claims: { method: "github", profile: {} }, + componentPath: "authGithub", + userId, + accessTokenTtlSeconds: 60 * 60, + refreshInactivityTimeoutSeconds: SESSION_SECONDS, + sessionMaxLifetimeSeconds: SESSION_SECONDS, + }), + ], + { cwd: web, env, timeout: 60000 }, + ); + const bundle = JSON.parse(minted.stdout); + assert.equal(typeof bundle.accessToken, "string"); + const result = { + tokens: { token: bundle.accessToken, refreshToken: bundle.refreshToken }, + }; const directory = join(privateRoot, role); const store = new SessionStore(); Object.defineProperty(store, "path", { diff --git a/packages/cli/src/auth.ts b/packages/cli/src/auth.ts index facf3a2..8c56a56 100644 --- a/packages/cli/src/auth.ts +++ b/packages/cli/src/auth.ts @@ -3,19 +3,18 @@ import { promisify } from "node:util"; import { createServer, type ServerResponse } from "node:http"; import { randomBytes } from "node:crypto"; import { httpClient, invoke } from "./client.js"; -import { - DEFAULT_API_URL, - DEFAULT_AUTH_SITE_URL, - DEFAULT_SITE_URL, - SessionStore, - validTokens, - tokenExpiresSoon, -} from "./storage.js"; +import { DEFAULT_SITE_URL, SessionStore, tokensFromBundle } from "./storage.js"; import { asRecord, type Ui } from "./ui.js"; const runFile = promisify(execFile); export const CALLBACK_PATH = "/gitdog/callback"; export const LOGIN_RESULT_PATH = "/cli/login"; +// Gitdog's sign-in returns only to exact origins, so the listener uses one of +// these ports. convex/_utils/authRedirect.ts allows the same list. +export const LOGIN_CALLBACK_PORTS = [41721, 41722, 41723, 41724, 41725]; +// The query parameters @convex-dev/auth adds when it returns to the CLI. +const CODE_PARAM = "convexAuthCode"; +const ERROR_PARAM = "convexAuthError"; type LoginOutcome = "success" | "failed"; @@ -100,6 +99,8 @@ export async function createLoginListener( (request, response) => { response.setHeader("Content-Type", "text/plain; charset=utf-8"); response.setHeader("Cache-Control", "no-store"); + // One-shot listener on a fixed port: never leave a reusable socket. + response.setHeader("Connection", "close"); response.setHeader("Referrer-Policy", "no-referrer"); response.setHeader( "Content-Security-Policy", @@ -134,14 +135,17 @@ export async function createLoginListener( response.writeHead(410).end("This sign-in has already completed."); return; } - if (url.searchParams.has("error") || !url.searchParams.has("code")) { + if ( + url.searchParams.has(ERROR_PARAM) || + !url.searchParams.has(CODE_PARAM) + ) { void sendToLoginResult(response, siteUrl, "failed"); finish(new Error("GitHub sign-in was declined or failed.")); return; } - const value = url.searchParams.get("code"); + const value = url.searchParams.get(CODE_PARAM); if ( - url.searchParams.getAll("code").length !== 1 || + url.searchParams.getAll(CODE_PARAM).length !== 1 || !value || value.length > 4096 ) { @@ -161,14 +165,25 @@ export async function createLoginListener( ), timeoutMs, ); - try { - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", () => { - server.off("error", reject); - resolve(); + const listenOn = (port: number) => + new Promise((resolve, reject) => { + const onError = (error: NodeJS.ErrnoException) => + error.code === "EADDRINUSE" ? resolve(false) : reject(error); + server.once("error", onError); + server.listen(port, "127.0.0.1", () => { + server.off("error", onError); + resolve(true); }); }); + try { + let listening = false; + for (const port of LOGIN_CALLBACK_PORTS) { + if ((listening = await listenOn(port))) break; + } + if (!listening) + throw new Error( + `Ports ${LOGIN_CALLBACK_PORTS.join(", ")} are all in use. Free one and run npx gitdog@latest login again.`, + ); } catch (error) { clearTimeout(timer); throw error; @@ -202,16 +217,12 @@ export async function createLoginListener( }; } -export function validateAuthRedirect(value: string, apiUrl: string): void { +/** GitHub's authorization page is the only place sign-in may send the user. */ +export function validateAuthRedirect(value: string): void { const url = new URL(value); - const api = new URL(apiUrl); - const siteOrigin = api.origin.replace(/\.convex\.cloud$/, ".convex.site"); - const allowedOrigins = [api.origin, siteOrigin]; - if (api.origin === new URL(DEFAULT_API_URL).origin) - allowedOrigins.push(new URL(DEFAULT_AUTH_SITE_URL).origin); if ( - !allowedOrigins.includes(url.origin) || - url.pathname !== "/api/auth/signin/github" || + url.origin !== "https://github.com" || + url.pathname !== "/login/oauth/authorize" || url.username || url.password || url.hash @@ -236,18 +247,17 @@ export async function login( try { ui.info("1 / 2 Sign in with your GitHub account"); const result = asRecord( - await invoke(client, "action", "auth:signIn", { - provider: "github", - params: { redirectTo: listener.redirectTo }, + await invoke(client, "mutation", "auth:startSignInWithGithub", { + redirectTo: listener.redirectTo, }), ); listener.signal.throwIfAborted(); if ( typeof result?.redirect !== "string" || - typeof result.verifier !== "string" + typeof result.state !== "string" ) throw new Error("The server did not start GitHub sign-in."); - validateAuthRedirect(result.redirect, apiUrl); + validateAuthRedirect(result.redirect); ui.info( `Open this URL in a browser on this computer:\n${result.redirect}\n`, ); @@ -259,18 +269,24 @@ export async function login( ui.info("2 / 2 Securely save your Gitdog session"); let exchange: unknown; try { - exchange = await invoke(client, "action", "auth:signIn", { - params: { code }, - verifier: result.verifier, - }); + exchange = await invoke( + client, + "mutation", + "auth:completeSignInWithGithub", + { code, state: result.state }, + ); } catch { listener.signal.throwIfAborted(); throw new Error( "Could not finish sign-in. Check that the CLI loopback callback is deployed, then run npx gitdog@latest login again.", ); } - const tokens = asRecord(exchange)?.tokens; - if (!validTokens(tokens)) + const completed = asRecord(exchange); + const tokens = + completed?.status === "complete" + ? tokensFromBundle(completed.tokens) + : null; + if (!tokens) throw new Error( "Sign-in did not return a session. Run npx gitdog@latest login again.", ); @@ -310,24 +326,15 @@ export async function logout( ); let revoked = false; await store.locked(async () => { - let session = localOnly ? undefined : await store.read(); + const session = localOnly ? undefined : await store.read(); if (session) { - const client = httpClient(session.apiUrl, 30_000); - if (tokenExpiresSoon(session.token)) { - const result = asRecord( - await invoke(client, "action", "auth:signIn", { - refreshToken: session.refreshToken, - }), - ); - if (!validTokens(result?.tokens)) - throw new Error( - "Could not refresh this session to revoke it. Run logout --local to remove only local credentials.", - ); - session = { ...session, ...result.tokens }; - await store.save(session); - } - client.setAuth(session.token); - await invoke(client, "action", "auth:signOut"); + // Signing out needs only the refresh token, not a fresh access token. + await invoke( + httpClient(session.apiUrl, 30_000), + "mutation", + "auth:signOut", + { refreshToken: session.refreshToken }, + ); revoked = true; } await store.clear(); diff --git a/packages/cli/src/client.ts b/packages/cli/src/client.ts index 646a9ea..95307cf 100644 --- a/packages/cli/src/client.ts +++ b/packages/cli/src/client.ts @@ -4,7 +4,7 @@ import type { Value } from "convex/values"; import { SessionStore, tokenExpiresSoon, - validTokens, + tokensFromBundle, type Session, } from "./storage.js"; import { asRecord } from "./ui.js"; @@ -116,19 +116,21 @@ export class GitdogApi implements Api { try { result = await invoke( httpClient(this.apiUrl, remainingTimeout(deadline)), - "action", - "auth:signIn", - { - refreshToken: current.refreshToken, - }, + "mutation", + "auth:refreshSession", + { refreshToken: current.refreshToken }, ); } catch { throw new Error( "Could not refresh your session. Check your connection or run npx gitdog@latest login again.", ); } - const tokens = asRecord(result)?.tokens; - if (!validTokens(tokens)) + const refreshed = asRecord(result); + const tokens = + refreshed?.kind === "rotated" + ? tokensFromBundle(refreshed.tokens) + : null; + if (!tokens) throw new Error( "Your session expired. Run npx gitdog@latest login again.", ); diff --git a/packages/cli/src/storage.ts b/packages/cli/src/storage.ts index e1b6116..5f7246c 100644 --- a/packages/cli/src/storage.ts +++ b/packages/cli/src/storage.ts @@ -15,7 +15,6 @@ import { asRecord } from "./ui.js"; export const DEFAULT_API_URL = "https://calm-hippopotamus-56.convex.cloud"; export const DEFAULT_SITE_URL = "https://gitdog.dev"; -export const DEFAULT_AUTH_SITE_URL = "https://auth.gitdog.dev"; export type Tokens = { token: string; refreshToken: string }; export type Session = Tokens & { apiUrl: string; siteUrl: string }; @@ -76,6 +75,16 @@ export function validTokens(value: unknown): value is Tokens { ); } +/** The session tokens in a @convex-dev/auth token bundle, if it has them. */ +export function tokensFromBundle(value: unknown): Tokens | null { + const bundle = asRecord(value); + const tokens = { + token: bundle?.accessToken, + refreshToken: bundle?.refreshToken, + }; + return validTokens(tokens) ? tokens : null; +} + export function validateUrl(value: string, label: string): string { let url: URL; try { diff --git a/packages/cli/src/ui.ts b/packages/cli/src/ui.ts index 063fd92..47216f4 100644 --- a/packages/cli/src/ui.ts +++ b/packages/cli/src/ui.ts @@ -1,7 +1,7 @@ import { createInterface } from "node:readline/promises"; import { stripVTControlCharacters } from "node:util"; -export const VERSION = "0.4.2"; +export const VERSION = "0.5.0"; export const DOG = String.raw` ▗██▄▄ ▄▄██▖ ██▀▜██▙▄ ▙▄ ▄▟██▛▀██ diff --git a/packages/cli/test/auth.test.mjs b/packages/cli/test/auth.test.mjs index a5e4ef3..74f987b 100644 --- a/packages/cli/test/auth.test.mjs +++ b/packages/cli/test/auth.test.mjs @@ -12,11 +12,19 @@ import { GitdogApi } from "../dist/client.js"; import { SessionStore, validateUrl } from "../dist/storage.js"; import { CaptureUi, fixture, jwt, mockServer } from "./helpers.mjs"; +/** The CLI's saved tokens as @convex-dev/auth returns them. */ +const bundle = ({ token, refreshToken }) => ({ + accessToken: token, + refreshToken, + refreshTokenExpiresAt: Date.now() + 86_400_000, + userId: "user-id", +}); + test("loopback listener rejects incorrect state, path, method and duplicate code", async (t) => { const listener = await createLoginListener(5000); t.after(listener.close); const correct = new URL(listener.redirectTo); - correct.searchParams.set("code", "one-time-code"); + correct.searchParams.set("convexAuthCode", "one-time-code"); const wrong = new URL(correct); wrong.searchParams.set("state", "bad"); assert.equal((await fetch(wrong)).status, 400); @@ -25,7 +33,7 @@ test("loopback listener rejects incorrect state, path, method and duplicate code assert.equal((await fetch(path)).status, 404); assert.equal((await fetch(correct, { method: "POST" })).status, 404); const duplicate = new URL(correct); - duplicate.searchParams.append("code", "second"); + duplicate.searchParams.append("convexAuthCode", "second"); assert.equal((await fetch(duplicate)).status, 400); const pending = fetch(correct, { redirect: "manual" }); assert.equal(await listener.code, "one-time-code"); @@ -44,7 +52,7 @@ test("loopback listener rejects incorrect state, path, method and duplicate code test("loopback listener reports a failed exchange when it closes", async () => { const listener = await createLoginListener(5000, "http://localhost:5173/"); const callback = new URL(listener.redirectTo); - callback.searchParams.set("code", "one-time-code"); + callback.searchParams.set("convexAuthCode", "one-time-code"); const pending = fetch(callback, { redirect: "manual" }); await listener.code; await listener.close(); @@ -57,7 +65,7 @@ test("loopback listener reports a failed exchange when it closes", async () => { test("loopback listener closes after the browser disconnects", async () => { const listener = await createLoginListener(5000); const callback = new URL(listener.redirectTo); - callback.searchParams.set("code", "one-time-code"); + callback.searchParams.set("convexAuthCode", "one-time-code"); const disconnect = new AbortController(); const pending = fetch(callback, { signal: disconnect.signal }); await listener.code; @@ -88,43 +96,20 @@ test("Convex OAuth cancellation without a code fails immediately", async (t) => await assert.rejects(listener.code, /declined or failed/); }); -test("auth redirects cannot send the browser to a third-party origin", () => { - assert.doesNotThrow(() => - validateAuthRedirect( - "https://my-app.convex.site/api/auth/signin/github?code=x", - "https://my-app.convex.cloud", - ), - ); +test("auth redirects cannot send the browser anywhere but GitHub's authorize page", () => { assert.doesNotThrow(() => validateAuthRedirect( - "https://auth.gitdog.dev/api/auth/signin/github?code=x", - "https://calm-hippopotamus-56.convex.cloud", + "https://github.com/login/oauth/authorize?client_id=x&state=y", ), ); - assert.throws( - () => - validateAuthRedirect( - "https://auth.gitdog.dev/api/auth/signin/github?code=x", - "https://my-app.convex.cloud", - ), - /unexpected/, - ); - assert.throws( - () => - validateAuthRedirect( - "https://evil.example/api/auth/signin/github", - "https://my-app.convex.cloud", - ), - /unexpected/, - ); - assert.throws( - () => - validateAuthRedirect( - "https://my-app.convex.site/other", - "https://my-app.convex.cloud", - ), - /unexpected/, - ); + for (const url of [ + "https://evil.example/login/oauth/authorize", + "https://github.com/other", + "https://user:pass@github.com/login/oauth/authorize", + "https://github.com/login/oauth/authorize#fragment", + "http://github.com/login/oauth/authorize", + ]) + assert.throws(() => validateAuthRedirect(url), /unexpected/); for (const url of [ "http://evil.example", "https://user:password@example.com", @@ -144,18 +129,18 @@ test("real HTTP login exchanges a verifier-bound code and stores private credent const tokens = { token: jwt(), refreshToken: "private-refresh-token" }; let callback; const server = await mockServer(t, (call) => { - if (call.path === "auth:signIn" && call.args.provider === "github") { - callback = new URL(call.args.params.redirectTo); - callback.searchParams.set("code", "exchanged-once"); + if (call.path === "auth:startSignInWithGithub") { + callback = new URL(call.args.redirectTo); + callback.searchParams.set("convexAuthCode", "exchanged-once"); return { - redirect: `${server.url}/api/auth/signin/github?code=verifier`, - verifier: "verifier", + redirect: "https://github.com/login/oauth/authorize?client_id=x", + state: "flow-state", }; } - if (call.path === "auth:signIn") { - assert.equal(call.args.verifier, "verifier"); - assert.equal(call.args.params.code, "exchanged-once"); - return { tokens }; + if (call.path === "auth:completeSignInWithGithub") { + assert.equal(call.args.state, "flow-state"); + assert.equal(call.args.code, "exchanged-once"); + return { status: "complete", tokens: bundle(tokens) }; } if (call.path === "users/query:getCurrentUser") { assert.equal(call.authorization, `Bearer ${tokens.token}`); @@ -194,11 +179,11 @@ test("concurrent expired clients rotate a refresh token only once", async (t) => const tokens = { token: jwt(), refreshToken: "rotated-refresh" }; let refreshes = 0; const server = await mockServer(t, async (call) => { - if (call.path === "auth:signIn") { + if (call.path === "auth:refreshSession") { refreshes++; assert.equal(call.args.refreshToken, "original-refresh"); await new Promise((resolve) => setTimeout(resolve, 30)); - return { tokens }; + return { kind: "rotated", tokens: bundle(tokens) }; } assert.equal(call.authorization, `Bearer ${tokens.token}`); return { name: "user" }; @@ -240,24 +225,24 @@ for (const phase of ["start", "exchange", "profile", "lock"]) { const tokens = { token: jwt(), refreshToken: "new-refresh" }; let callback; const server = await mockServer(t, async (call) => { - if (call.path === "auth:signIn" && call.args.provider === "github") { - callback = new URL(call.args.params.redirectTo); - callback.searchParams.set("code", "cancelled-code"); + if (call.path === "auth:startSignInWithGithub") { + callback = new URL(call.args.redirectTo); + callback.searchParams.set("convexAuthCode", "cancelled-code"); if (phase === "start") { process.emit("SIGINT"); await new Promise((resolve) => setTimeout(resolve, 20)); } return { - redirect: `${server.url}/api/auth/signin/github?code=verifier`, - verifier: "verifier", + redirect: "https://github.com/login/oauth/authorize?client_id=x", + state: "flow-state", }; } - if (call.path === "auth:signIn") { + if (call.path === "auth:completeSignInWithGithub") { if (phase === "exchange") { process.emit("SIGINT"); await new Promise((resolve) => setTimeout(resolve, 20)); } - return { tokens }; + return { status: "complete", tokens: bundle(tokens) }; } if (phase === "profile") { process.emit("SIGINT"); @@ -358,9 +343,12 @@ test("an already-authenticated client refreshes without sending its expired bear value: join(directory, "session.json"), }); const server = await mockServer(t, (call) => { - if (call.path === "auth:signIn") { + if (call.path === "auth:refreshSession") { assert.equal(call.authorization, undefined); - return { tokens: { token: jwt(), refreshToken: "new-refresh" } }; + return { + kind: "rotated", + tokens: bundle({ token: jwt(), refreshToken: "new-refresh" }), + }; } return { name: "user" }; }); @@ -384,9 +372,12 @@ test("a per-call deadline includes token refresh", async (t) => { value: join(directory, "session.json"), }); const server = await mockServer(t, async (call) => { - if (call.path === "auth:signIn") { + if (call.path === "auth:refreshSession") { await new Promise((resolve) => setTimeout(resolve, 150)); - return { tokens: { token: jwt(), refreshToken: "new-token" } }; + return { + kind: "rotated", + tokens: bundle({ token: jwt(), refreshToken: "new-token" }), + }; } throw new Error("The data query must not run after its deadline."); }); @@ -438,6 +429,7 @@ test("logout serializes revocation and clearing with a concurrent login", async }); const server = await mockServer(t, async (call) => { assert.equal(call.path, "auth:signOut"); + assert.equal(call.args.refreshToken, "first-refresh"); entered(); await proceed; return null; diff --git a/src/main.tsx b/src/main.tsx index 7603510..c6595e7 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -2,6 +2,7 @@ import React from "react"; import ReactDOM from "react-dom/client"; import { ConvexReactClient } from "convex/react"; import { ConvexAuthProvider } from "@convex-dev/auth/react"; +import { api } from "../convex/_generated/api"; import App from "./App"; import "./index.css"; import "./utils/signals/theme"; @@ -15,7 +16,7 @@ if (canonicalRedirect) { const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL!); ReactDOM.createRoot(document.getElementById("root")!).render( - + , diff --git a/src/pages/legal/consent.tsx b/src/pages/legal/consent.tsx index e70eaa9..8eb08d3 100644 --- a/src/pages/legal/consent.tsx +++ b/src/pages/legal/consent.tsx @@ -1,4 +1,5 @@ import { useAuthActions } from "@convex-dev/auth/react"; +import { useSignInWithGithub } from "@convex-dev/auth/methods/github/react"; import { SiGithub } from "@icons-pack/react-simple-icons"; import { useConvexAuth, useMutation, useQuery } from "convex/react"; import { FormEvent, useCallback, useEffect, useRef, useState } from "react"; @@ -31,7 +32,8 @@ export function LegalConsentPage() { const attestLegalEligibility = useMutation( api.users.mutation.attestLegalEligibility, ); - const { signIn, signOut } = useAuthActions(); + const { signOut } = useAuthActions(); + const { signIn } = useSignInWithGithub(api.auth); const { isAuthenticated, isLoading: isAuthResolving } = useConvexAuth(); // Captured once: the visitor already confirmed eligibility on this tab and is // coming back from the GitHub redirect, so the form must not restart empty. @@ -207,11 +209,11 @@ export function LegalConsentPage() { setIsSubmitting(true); setError(null); markPendingLegalConsent(); - try { - await signIn("github", { - redirectTo: `${location.pathname}${location.search}`, - }); - } catch { + // Success leaves the page for GitHub; only a failure comes back here. + const started = await signIn({ + redirectTo: `${window.location.origin}${location.pathname}${location.search}`, + }); + if (started.status === "error") { clearPendingLegalConsent(); setError(t("auth.legalConsent.signInError")); setIsSubmitting(false); diff --git a/test/convex/admin/paymentPrivacy.test.ts b/test/convex/admin/paymentPrivacy.test.ts index cda7b58..2b78b7d 100644 --- a/test/convex/admin/paymentPrivacy.test.ts +++ b/test/convex/admin/paymentPrivacy.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { api } from "../../../convex/_generated/api"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -97,17 +98,13 @@ describe("admin payment-log privacy", () => { ), ).rejects.toThrow("Unauthorized"); await expect( - t - .withIdentity({ subject: `${normalUserId}|session` }) - .mutation( - api.admin.paymentMutation.requeueSubscriptionInvoiceReview, - args, - ), + (await asUser(t, normalUserId)).mutation( + api.admin.paymentMutation.requeueSubscriptionInvoiceReview, + args, + ), ).rejects.toThrow("Unauthorized"); - const authenticated = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const authenticated = await asUser(t, adminUserId); const listed = await authenticated.query( api.admin.paymentQuery.listOpenSettlementReviews, { limit: 10 }, @@ -221,13 +218,14 @@ describe("admin payment-log privacy", () => { }); await expect( - t - .withIdentity({ subject: `${adminUserId}|admin-session` }) - .mutation(api.admin.paymentMutation.requeueSubscriptionInvoiceReview, { + (await asUser(t, adminUserId)).mutation( + api.admin.paymentMutation.requeueSubscriptionInvoiceReview, + { manualReviewId: reviewId, evidenceReference: "ls-support-case-conflict", confirmRetry: true, - }), + }, + ), ).rejects.toThrow("conflicts with durable inbox"); const state = await t.run(async (ctx) => ({ inbox: await ctx.db.get(inboxId), @@ -307,9 +305,7 @@ describe("admin payment-log privacy", () => { refund40LogId, }; }); - const authenticated = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const authenticated = await asUser(t, adminUserId); await expect( authenticated.mutation(api.admin.paymentMutation.refundTokens, { @@ -389,9 +385,7 @@ describe("admin payment-log privacy", () => { return { adminUserId, customerUserId, paymentLogId }; }, ); - const authenticated = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const authenticated = await asUser(t, adminUserId); const listed = await authenticated.query( api.admin.paymentQuery.listPaymentLogs, diff --git a/test/convex/github/accessVerification.test.ts b/test/convex/github/accessVerification.test.ts index 57a5754..9ade0e2 100644 --- a/test/convex/github/accessVerification.test.ts +++ b/test/convex/github/accessVerification.test.ts @@ -10,6 +10,7 @@ import { } from "../../../convex/github/accessVerification"; import { GITHUB_INSTALLATION_ATTESTATION_TTL_MS } from "../../../convex/github/oauthInstallationAttestation"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -50,14 +51,10 @@ async function setup(linkedAccountId = "654") { const t = convexTest(schema, modules); const userId = await t.run(async (ctx) => { const userId = await ctx.db.insert("users", { name: "octocat" }); - await ctx.db.insert("authAccounts", { - userId, - provider: "github", - providerAccountId: linkedAccountId, - }); + await ctx.db.patch(userId, { githubAccountId: linkedAccountId }); return userId; }); - const as = t.withIdentity({ subject: `${userId}|session` }); + const as = await asUser(t, userId); return { t, as, userId }; } diff --git a/test/convex/github/duplicateInstallations.test.ts b/test/convex/github/duplicateInstallations.test.ts index d22c02e..d292e43 100644 --- a/test/convex/github/duplicateInstallations.test.ts +++ b/test/convex/github/duplicateInstallations.test.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { api, internal } from "../../../convex/_generated/api"; import type { Id } from "../../../convex/_generated/dataModel"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -128,9 +129,9 @@ describe("duplicate GitHub installation fail-closed behavior", () => { const t = convexTest(schema, modules); const fixture = await insertDuplicateFixture(t, 901); - const installations = await t - .withIdentity({ subject: `${fixture.ownerId}|session` }) - .query(api.github.query.getUserInstallations, {}); + const installations = await ( + await asUser(t, fixture.ownerId) + ).query(api.github.query.getUserInstallations, {}); const access = await t.query( internal.repositories.internalQuery.getAiAccessSnapshot, { repositoryId: fixture.repositoryId, expectedIndexVersion: 3 }, @@ -154,11 +155,11 @@ describe("duplicate GitHub installation fail-closed behavior", () => { githubRepo: "owner/repo", }, ); - await t - .withIdentity({ subject: `${fixture.ownerId}|session` }) - .mutation(api.repoIndexing.mutation.initializeIndexing, { - repositoryId: fixture.repositoryId, - }); + await ( + await asUser(t, fixture.ownerId) + ).mutation(api.repoIndexing.mutation.initializeIndexing, { + repositoryId: fixture.repositoryId, + }); const repository = await t.run(async (ctx) => ctx.db.get(fixture.repositoryId), ); diff --git a/test/convex/github/installationOwnership.test.ts b/test/convex/github/installationOwnership.test.ts index 13e13bc..a2e1d31 100644 --- a/test/convex/github/installationOwnership.test.ts +++ b/test/convex/github/installationOwnership.test.ts @@ -16,6 +16,7 @@ import { } from "../../../convex/github/webhook"; import { GITHUB_INSTALLATION_ATTESTATION_MAX_INSTALLATIONS } from "../../../convex/github/oauthInstallationAttestation"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const noopIndexRepository = internalAction({ args: { @@ -122,11 +123,7 @@ async function insertOAuthInstallationAttestation( await t.run(async (ctx) => { const now = Date.now(); const githubAccountId = options.githubAccountId ?? "654"; - await ctx.db.insert("authAccounts", { - userId, - provider: "github", - providerAccountId: "654", - }); + await ctx.db.patch(userId, { githubAccountId: "654" }); await ctx.db.insert("githubOAuthInstallationAttestations", { userId, githubAccountId, @@ -614,9 +611,9 @@ describe("GitHub installation ownership persistence", () => { }), ) as typeof fetch; - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 456 }); + const result = await ( + await asUser(t, ownerId) + ).action(api.github.action.saveInstallation, { installationId: 456 }); const state = await t.run(async (ctx) => ({ installation: await ctx.db .query("githubInstallations") @@ -663,9 +660,9 @@ describe("authenticated installation refresh", () => { ) as typeof fetch; await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 901 }), + (await asUser(t, userId)).action(api.github.action.saveInstallation, { + installationId: 901, + }), ).resolves.toEqual({ status: "not_bound_yet" }); const state = await t.run(async (ctx) => ({ @@ -703,9 +700,9 @@ describe("authenticated installation refresh", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 902 }), + (await asUser(t, userId)).action(api.github.action.saveInstallation, { + installationId: 902, + }), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -718,9 +715,9 @@ describe("authenticated installation refresh", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 904 }), + (await asUser(t, userId)).action(api.github.action.saveInstallation, { + installationId: 904, + }), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -735,9 +732,9 @@ describe("authenticated installation refresh", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 905 }), + (await asUser(t, userId)).action(api.github.action.saveInstallation, { + installationId: 905, + }), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -757,9 +754,9 @@ describe("authenticated installation refresh", () => { ) as typeof fetch; await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 906 }), + (await asUser(t, userId)).action(api.github.action.saveInstallation, { + installationId: 906, + }), ).rejects.toThrow("GitHub installation owner does not match authorization"); const stored = await t.run(async (ctx) => ctx.db @@ -776,9 +773,9 @@ describe("authenticated installation refresh", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 999 }), + (await asUser(t, userId)).action(api.github.action.saveInstallation, { + installationId: 999, + }), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); @@ -795,9 +792,9 @@ describe("authenticated installation refresh", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${attackerId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 777 }), + (await asUser(t, attackerId)).action(api.github.action.saveInstallation, { + installationId: 777, + }), ).resolves.toEqual({ status: "not_bound_yet" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); @@ -812,9 +809,9 @@ describe("authenticated installation refresh", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 778 }), + (await asUser(t, ownerId)).action(api.github.action.saveInstallation, { + installationId: 778, + }), ).rejects.toThrow("GitHub App credentials not configured"); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -831,11 +828,9 @@ describe("authenticated installation refresh", () => { ) as typeof fetch; await expect( - t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.saveInstallation, { - installationId: 779 + status, - }), + (await asUser(t, ownerId)).action(api.github.action.saveInstallation, { + installationId: 779 + status, + }), ).rejects.toThrow("Failed to refresh GitHub installation details"); expect(globalThis.fetch).toHaveBeenCalledOnce(); }, @@ -850,9 +845,9 @@ describe("authenticated installation refresh", () => { }) as typeof fetch; await expect( - t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.saveInstallation, { installationId: 780 }), + (await asUser(t, ownerId)).action(api.github.action.saveInstallation, { + installationId: 780, + }), ).rejects.toThrow("Failed to refresh GitHub installation details"); expect(globalThis.fetch).toHaveBeenCalledOnce(); }); @@ -892,9 +887,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = fetchMock as typeof fetch; await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "recovered", installationId: 104575964, @@ -945,9 +941,7 @@ describe("authenticated OAuth installation recovery", () => { }); }); globalThis.fetch = fetchMock as typeof fetch; - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.action(api.github.action.recoverOAuthInstallation, {}), @@ -985,9 +979,10 @@ describe("authenticated OAuth installation recovery", () => { ) as typeof fetch; await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "configure_required", installationId: 912, @@ -1039,9 +1034,7 @@ describe("authenticated OAuth installation recovery", () => { }); }); globalThis.fetch = fetchMock as typeof fetch; - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.action(api.github.action.recoverOAuthInstallation, {}), @@ -1093,9 +1086,7 @@ describe("authenticated OAuth installation recovery", () => { }); }); globalThis.fetch = fetchMock as typeof fetch; - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.action(api.github.action.recoverOAuthInstallation, {}), @@ -1122,9 +1113,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "none" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -1136,9 +1128,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -1155,9 +1148,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -1172,9 +1166,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "reauth_required" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -1191,9 +1186,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "unavailable" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -1222,9 +1218,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "configure_required", installationId: 945, @@ -1241,9 +1238,10 @@ describe("authenticated OAuth installation recovery", () => { globalThis.fetch = vi.fn(); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .action(api.github.action.recoverOAuthInstallation, {}), + (await asUser(t, userId)).action( + api.github.action.recoverOAuthInstallation, + {}, + ), ).resolves.toEqual({ status: "unavailable" }); expect(mockedGenerateGitHubAppJWT).not.toHaveBeenCalled(); expect(globalThis.fetch).not.toHaveBeenCalled(); @@ -1265,18 +1263,18 @@ describe("authenticated installation lookup", () => { }), ).toBeNull(); expect( - await t - .withIdentity({ subject: `${otherUserId}|test-session` }) - .query(api.github.query.getInstallation, { installationId: 888 }), + await ( + await asUser(t, otherUserId) + ).query(api.github.query.getInstallation, { installationId: 888 }), ).toBeNull(); expect( - await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .query(api.github.query.getInstallation, { installationId: 888 }), + await ( + await asUser(t, ownerId) + ).query(api.github.query.getInstallation, { installationId: 888 }), ).toMatchObject({ userId: ownerId, installationId: 888 }); - const publicInstallation = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .query(api.github.query.getInstallation, { installationId: 888 }); + const publicInstallation = await ( + await asUser(t, ownerId) + ).query(api.github.query.getInstallation, { installationId: 888 }); expect(publicInstallation).not.toHaveProperty("ownerGithubAccountId"); expect(publicInstallation).not.toHaveProperty("ownershipVerifiedAt"); }); @@ -1304,9 +1302,9 @@ describe("authenticated installation lookup", () => { }); }); - const installations = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .query(api.github.query.getUserInstallations, {}); + const installations = await ( + await asUser(t, ownerId) + ).query(api.github.query.getUserInstallations, {}); expect(installations).toHaveLength(1); expect(installations[0]).toMatchObject({ @@ -1369,7 +1367,7 @@ describe("authenticated installation lookup", () => { repositoryAccessReconciliationPhase: "fetching", }); }); - const identity = t.withIdentity({ subject: `${ownerId}|test-session` }); + const identity = await asUser(t, ownerId); const installations = await identity.query( api.github.query.getUserInstallations, @@ -1834,9 +1832,9 @@ describe("invalid installation cleanup", () => { vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); - const repositories = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, {}); + const repositories = await ( + await asUser(t, ownerId) + ).action(api.github.action.listUserRepositories, {}); await t.finishAllScheduledFunctions(() => vi.advanceTimersToNextTimer()); const { installation, repository } = await t.run(async (ctx) => ({ installation: await ctx.db @@ -1871,9 +1869,9 @@ describe("invalid installation cleanup", () => { vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); - await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, {}); + await ( + await asUser(t, ownerId) + ).action(api.github.action.listUserRepositories, {}); await t.finishAllScheduledFunctions(() => vi.advanceTimersToNextTimer()); const state = await t.run(async (ctx) => ({ installation: await ctx.db @@ -1901,9 +1899,9 @@ describe("invalid installation cleanup", () => { vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); - await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, {}); + await ( + await asUser(t, ownerId) + ).action(api.github.action.listUserRepositories, {}); await t.finishAllScheduledFunctions(() => vi.advanceTimersToNextTimer()); const state = await t.run(async (ctx) => ({ installation: await ctx.db @@ -1912,9 +1910,9 @@ describe("invalid installation cleanup", () => { .first(), repository: await ctx.db.get(repositoryId), })); - const publicInstallations = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .query(api.github.query.getUserInstallations, {}); + const publicInstallations = await ( + await asUser(t, ownerId) + ).query(api.github.query.getUserInstallations, {}); expect(state.installation?.accessSuspendedAt).toEqual(expect.any(Number)); expect(state.repository?.githubAccessRevokedAt).toEqual(expect.any(Number)); @@ -1932,9 +1930,10 @@ describe("invalid installation cleanup", () => { vi.spyOn(console, "error").mockImplementation(() => undefined); await expect( - t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, {}), + (await asUser(t, ownerId)).action( + api.github.action.listUserRepositories, + {}, + ), ).rejects.toThrow("Unable to load repositories from GitHub"); const state = await t.run(async (ctx) => ({ installation: await ctx.db @@ -1993,7 +1992,7 @@ describe("bounded authenticated repository listing", () => { } return Response.json({ repositories: [] }); }) as typeof fetch; - const identity = t.withIdentity({ subject: `${ownerId}|test-session` }); + const identity = await asUser(t, ownerId); const first = await identity.action( api.github.action.listUserRepositories, @@ -2050,7 +2049,7 @@ describe("bounded authenticated repository listing", () => { globalThis.fetch = vi.fn(async () => Response.json({ repositories: [makeGitHubRepository(201)] }), ) as typeof fetch; - const identity = t.withIdentity({ subject: `${ownerId}|test-session` }); + const identity = await asUser(t, ownerId); const pendingPage = await identity.action( api.github.action.listUserRepositories, @@ -2098,7 +2097,7 @@ describe("bounded authenticated repository listing", () => { repositoryRemovalPendingAt: Date.now(), }); }); - const identity = t.withIdentity({ subject: `${ownerId}|test-session` }); + const identity = await asUser(t, ownerId); const installations = await identity.query( api.github.query.getUserInstallations, @@ -2148,7 +2147,7 @@ describe("bounded authenticated repository listing", () => { globalThis.fetch = vi.fn(async () => Response.json({ repositories: [makeGitHubRepository(201)] }), ) as typeof fetch; - const identity = t.withIdentity({ subject: `${ownerId}|test-session` }); + const identity = await asUser(t, ownerId); const pendingInstallations = await identity.query( api.github.query.getUserInstallations, @@ -2277,9 +2276,9 @@ describe("bounded authenticated repository listing", () => { }), ) as typeof fetch; - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, {}); + const result = await ( + await asUser(t, ownerId) + ).action(api.github.action.listUserRepositories, {}); expect(result.repositories.map((repository) => repository.id)).toEqual([ 999, @@ -2339,11 +2338,11 @@ describe("bounded authenticated repository listing", () => { }), ) as typeof fetch; - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, { - reconnectRepositoryId: reconnectRepositoryId, - }); + const result = await ( + await asUser(t, ownerId) + ).action(api.github.action.listUserRepositories, { + reconnectRepositoryId: reconnectRepositoryId, + }); expect(result.repositories.map((repository) => repository.id)).toEqual([ 301, @@ -2364,11 +2363,11 @@ describe("bounded authenticated repository listing", () => { Response.json({ repositories: [makeGitHubRepository(300)] }), ) as typeof fetch; - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.github.action.listUserRepositories, { - cursor: JSON.stringify({ installationId: 200, page: 1 }), - }); + const result = await ( + await asUser(t, ownerId) + ).action(api.github.action.listUserRepositories, { + cursor: JSON.stringify({ installationId: 200, page: 1 }), + }); expect(mockedGetInstallationToken).toHaveBeenCalledWith( 300, @@ -2414,7 +2413,7 @@ describe("durable installation repository reconciliation", () => { "github/action:continueRepositoryAccessReconciliation", ).length, ); - const owner = t.withIdentity({ subject: `${ownerId}|test-session` }); + const owner = await asUser(t, ownerId); const publicWhileRetrying = await owner.query( api.github.query.getUserInstallations, {}, @@ -2489,9 +2488,7 @@ describe("durable installation repository reconciliation", () => { ).toBeUndefined(); expect(terminalState.scheduled).toBe(scheduledBefore + 1); - const otherUser = t.withIdentity({ - subject: `${otherUserId}|test-session`, - }); + const otherUser = await asUser(t, otherUserId); const publicInstallations = await owner.query( api.github.query.getUserInstallations, {}, @@ -3769,7 +3766,7 @@ describe("signed installation webhook ownership binding", () => { githubInstallationReconnectRequired: true, }); - const owner = t.withIdentity({ subject: `${ownerId}|owner-session` }); + const owner = await asUser(t, ownerId); await expect( owner.query(api.repoIndexing.query.getIndexingStatus, { repositoryId }), ).resolves.toMatchObject({ @@ -4128,11 +4125,7 @@ describe("signed installation webhook ownership binding", () => { const { verifiedUserId, profileOnlyUserId } = await t.run(async (ctx) => { const verifiedUserId = await ctx.db.insert("users", {}); const profileOnlyUserId = await ctx.db.insert("users", {}); - await ctx.db.insert("authAccounts", { - userId: verifiedUserId, - provider: "github", - providerAccountId: "654", - }); + await ctx.db.patch(verifiedUserId, { githubAccountId: "654" }); await ctx.db.insert("userProfiles", { userId: profileOnlyUserId, githubUsername: "example-org", @@ -4162,32 +4155,20 @@ describe("signed installation webhook ownership binding", () => { const firstUserId = await ctx.db.insert("users", {}); const secondUserId = await ctx.db.insert("users", {}); const deletedUserId = await ctx.db.insert("users", {}); - await ctx.db.insert("authAccounts", { - userId: firstUserId, - provider: "github", - providerAccountId: "duplicate-account", - }); - await ctx.db.insert("authAccounts", { - userId: secondUserId, - provider: "github", - providerAccountId: "duplicate-account", - }); - await ctx.db.insert("authAccounts", { - userId: deletedUserId, - provider: "github", - providerAccountId: "dangling-account", - }); + await ctx.db.patch(firstUserId, { githubAccountId: "1001" }); + await ctx.db.patch(secondUserId, { githubAccountId: "1001" }); + await ctx.db.patch(deletedUserId, { githubAccountId: "1002" }); await ctx.db.delete(deletedUserId); }); await expect( t.query(internal.github.internalQuery.getUserIdByGithubAccountId, { - githubAccountId: "duplicate-account", + githubAccountId: "1001", }), ).resolves.toBeNull(); await expect( t.query(internal.github.internalQuery.getUserIdByGithubAccountId, { - githubAccountId: "dangling-account", + githubAccountId: "1002", }), ).resolves.toBeNull(); }); @@ -4213,9 +4194,10 @@ describe("signed installation webhook ownership binding", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .query(api.github.query.getUserInstallations, {}), + (await asUser(t, userId)).query( + api.github.query.getUserInstallations, + {}, + ), ).rejects.toThrow("GitHub App installation limit exceeded"); }); }); diff --git a/test/convex/github/oauthInstallationAttestation.test.ts b/test/convex/github/oauthInstallationAttestation.test.ts index 07264e2..fb7b4df 100644 --- a/test/convex/github/oauthInstallationAttestation.test.ts +++ b/test/convex/github/oauthInstallationAttestation.test.ts @@ -5,7 +5,7 @@ import { fetchAccessibleGitHubInstallationIds, GITHUB_INSTALLATION_ATTESTATION_REQUEST_TIMEOUT_MS, GITHUB_INSTALLATION_ATTESTATION_TTL_MS, - persistGitHubInstallationAttestation, + saveInstallationAttestation, } from "../../../convex/github/oauthInstallationAttestation"; import schema from "../../../convex/schema"; @@ -135,144 +135,72 @@ describe("GitHub OAuth installation access attestation", () => { ).rejects.toThrow("incomplete installation access data"); }); - it("stores one current snapshot and strips untrusted profile fields", async () => { + it("stores one sorted snapshot per user for the linked account", async () => { const now = 1_800_000_000_000; - vi.spyOn(Date, "now").mockReturnValue(now); + const mockedNow = vi.spyOn(Date, "now").mockReturnValue(now); const t = convexTest(schema, modules); - const userId = await t.run(async (ctx) => - persistGitHubInstallationAttestation(ctx, { - existingUserId: null, - type: "oauth", - provider: { id: "github", type: "oauth" }, - profile: { - githubAccountId: "654", - githubInstallationIds: [321, 123], - name: "octocat", - email: "octocat@example.com", - image: "https://avatars.example/octocat", - accessToken: "must-not-be-stored", - }, - }), + ctx.db.insert("users", { githubAccountId: "654" }), ); - const state = await t.run(async (ctx) => ({ - user: await ctx.db.get(userId), - attestations: await ctx.db - .query("githubOAuthInstallationAttestations") - .collect(), - })); - expect(state.user).toMatchObject({ - name: "octocat", - email: "octocat@example.com", - image: "https://avatars.example/octocat", - emailVerificationTime: now, - }); - expect(state.user).not.toHaveProperty("githubAccountId"); - expect(state.user).not.toHaveProperty("githubInstallationIds"); - expect(state.user).not.toHaveProperty("accessToken"); - expect(state.attestations).toHaveLength(1); - expect(state.attestations[0]).toMatchObject({ - userId, - githubAccountId: "654", - installationIds: [123, 321], - attestedAt: now, - expiresAt: now + GITHUB_INSTALLATION_ATTESTATION_TTL_MS, - updatedAt: now, - }); - expect(state.attestations[0]).not.toHaveProperty("accessToken"); - }); - - it("replaces the current snapshot only for the exact linked account", async () => { - const now = 1_800_000_000_000; - const mockedNow = vi.spyOn(Date, "now").mockReturnValue(now); - const t = convexTest(schema, modules); - const userId = await t.run(async (ctx) => { - const userId = await ctx.db.insert("users", { name: "before" }); - await ctx.db.insert("authAccounts", { + await t.run((ctx) => + saveInstallationAttestation(ctx, { userId, - provider: "github", - providerAccountId: "654", - }); - return userId; - }); - - await t.run(async (ctx) => - persistGitHubInstallationAttestation(ctx, { - existingUserId: userId, - type: "oauth", - provider: { id: "github", type: "oauth" }, - profile: { - githubAccountId: "654", - githubInstallationIds: [123], - name: "first", - }, + githubAccountId: "654", + installationIds: [321, 123], + now, }), ); mockedNow.mockReturnValue(now + 1_000); - await t.run(async (ctx) => - persistGitHubInstallationAttestation(ctx, { - existingUserId: userId, - type: "oauth", - provider: { id: "github", type: "oauth" }, - profile: { - githubAccountId: "654", - githubInstallationIds: [456], - name: "second", - }, + await t.run((ctx) => + saveInstallationAttestation(ctx, { + userId, + githubAccountId: "654", + installationIds: [456], + now: now + 1_000, }), ); - const state = await t.run(async (ctx) => ({ - user: await ctx.db.get(userId), - attestations: await ctx.db - .query("githubOAuthInstallationAttestations") - .collect(), - })); + const attestations = await t.run((ctx) => + ctx.db.query("githubOAuthInstallationAttestations").collect(), + ); - expect(state.user?.name).toBe("second"); - expect(state.attestations).toHaveLength(1); - expect(state.attestations[0]).toMatchObject({ + expect(attestations).toHaveLength(1); + expect(attestations[0]).toMatchObject({ userId, githubAccountId: "654", installationIds: [456], attestedAt: now + 1_000, + expiresAt: now + 1_000 + GITHUB_INSTALLATION_ATTESTATION_TTL_MS, }); }); - it("rolls back when the OAuth identity does not match the linked account", async () => { + it("refuses invalid ids and a snapshot owned by another account", async () => { const t = convexTest(schema, modules); - const userId = await t.run(async (ctx) => { - const userId = await ctx.db.insert("users", { name: "before" }); - await ctx.db.insert("authAccounts", { - userId, - provider: "github", - providerAccountId: "654", - }); - return userId; - }); - - await expect( - t.run(async (ctx) => - persistGitHubInstallationAttestation(ctx, { - existingUserId: userId, - type: "oauth", - provider: { id: "github", type: "oauth" }, - profile: { - githubAccountId: "999", - githubInstallationIds: [123], - name: "attacker", - }, + const [first, second] = await t.run(async (ctx) => [ + await ctx.db.insert("users", { githubAccountId: "654" }), + await ctx.db.insert("users", { githubAccountId: "777" }), + ]); + const save = ( + userId: typeof first, + githubAccountId: string, + installationIds: unknown, + ) => + t.run((ctx) => + saveInstallationAttestation(ctx, { + userId, + githubAccountId, + installationIds, + now: Date.now(), }), - ), - ).rejects.toThrow("GitHub account identity changed during sign-in"); - const state = await t.run(async (ctx) => ({ - user: await ctx.db.get(userId), - attestations: await ctx.db - .query("githubOAuthInstallationAttestations") - .collect(), - })); + ); - expect(state.user?.name).toBe("before"); - expect(state.attestations).toHaveLength(0); + await expect(save(first, "not-a-number", [1])).rejects.toThrow( + "attestation is invalid", + ); + await expect(save(first, "654", [1, 1])).rejects.toThrow( + "attestation is invalid", + ); + await save(first, "654", [1]); + await expect(save(second, "654", [2])).rejects.toThrow("owner mismatch"); }); }); diff --git a/test/convex/invitations/createIdentity.test.ts b/test/convex/invitations/createIdentity.test.ts index da97889..934f43e 100644 --- a/test/convex/invitations/createIdentity.test.ts +++ b/test/convex/invitations/createIdentity.test.ts @@ -6,6 +6,7 @@ import { api, internal } from "../../../convex/_generated/api"; import type { Id } from "../../../convex/_generated/dataModel"; import * as githubHelpers from "../../../convex/github/helpers"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -139,11 +140,7 @@ async function insertGitHubUser( return await t.run(async (ctx) => { const now = Date.now(); const userId = await ctx.db.insert("users", {}); - await ctx.db.insert("authAccounts", { - userId, - provider: "github", - providerAccountId: githubAccountId.toString(), - }); + await ctx.db.patch(userId, { githubAccountId: githubAccountId.toString() }); for (const githubUsername of profileNames) { await ctx.db.insert("userProfiles", { userId, @@ -185,13 +182,13 @@ describe("verified invitation creation", () => { type: "User", }); - const invitationId = await t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "victim-login", - role: "viewer", - }); + const invitationId = await ( + await asUser(t, ownerUserId) + ).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "victim-login", + role: "viewer", + }); const writes = await getInvitationWrites(t); expect(writes.invitations).toEqual([ @@ -205,9 +202,10 @@ describe("verified invitation creation", () => { expect.objectContaining({ userId: victimUserId, invitationId }), ]); await expect( - t - .withIdentity({ subject: `${attackerUserId}|attacker-session` }) - .query(api.invitations.query.listPending, {}), + (await asUser(t, attackerUserId)).query( + api.invitations.query.listPending, + {}, + ), ).resolves.toEqual([]); }); @@ -231,13 +229,13 @@ describe("verified invitation creation", () => { type: "User", }); - await t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "duplicate-login", - role: "viewer", - }); + await ( + await asUser(t, ownerUserId) + ).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "duplicate-login", + role: "viewer", + }); expect((await getInvitationWrites(t)).invitations[0]).toMatchObject({ inviteeUserId: mappedUserId, @@ -254,13 +252,13 @@ describe("verified invitation creation", () => { type: "User", }); - const invitationId = await t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "old-login", - role: "viewer", - }); + const invitationId = await ( + await asUser(t, ownerUserId) + ).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "old-login", + role: "viewer", + }); expect(mockedGetInstallationToken).toHaveBeenCalledWith( 812, @@ -290,13 +288,11 @@ describe("verified invitation creation", () => { }); await expect( - t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "unmapped-user", - role: "viewer", - }), + (await asUser(t, ownerUserId)).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "unmapped-user", + role: "viewer", + }), ).rejects.toThrow("User not found"); expect(await getInvitationWrites(t)).toEqual({ invitations: [], @@ -316,13 +312,11 @@ describe("verified invitation creation", () => { }); await expect( - t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "duplicate-account", - role: "viewer", - }), + (await asUser(t, ownerUserId)).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "duplicate-account", + role: "viewer", + }), ).rejects.toThrow(); expect(await getInvitationWrites(t)).toEqual({ invitations: [], @@ -341,13 +335,11 @@ describe("verified invitation creation", () => { }); await expect( - t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "canonical-user", - role: "viewer", - }), + (await asUser(t, ownerUserId)).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "canonical-user", + role: "viewer", + }), ).rejects.toThrow("Repository is no longer available"); expect(mockedGetInstallationToken).not.toHaveBeenCalled(); expect(mockedFetchGitHubAppJson).not.toHaveBeenCalled(); @@ -370,13 +362,13 @@ describe("verified invitation creation", () => { type: "User", }); - const invitationId = await t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "paused-repository-invitee", - role: "viewer", - }); + const invitationId = await ( + await asUser(t, ownerUserId) + ).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "paused-repository-invitee", + role: "viewer", + }); expect((await getInvitationWrites(t)).invitations).toEqual([ expect.objectContaining({ @@ -399,13 +391,11 @@ describe("verified invitation creation", () => { } await expect( - t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "canonical-user", - role: "viewer", - }), + (await asUser(t, ownerUserId)).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "canonical-user", + role: "viewer", + }), ).rejects.toThrow(); expect(await getInvitationWrites(t)).toEqual({ invitations: [], @@ -454,7 +444,7 @@ describe("verified invitation creation", () => { login: "canonical-name", type: "User", }); - const owner = t.withIdentity({ subject: `${ownerUserId}|owner-session` }); + const owner = await asUser(t, ownerUserId); await owner.action(api.invitations.action.create, { repositoryId, inviteeGithubUsername: "canonical-name", @@ -491,18 +481,19 @@ describe("verified invitation creation", () => { login: "verified-member", type: "User", }); - const invitationId = await t - .withIdentity({ subject: `${ownerUserId}|owner-session` }) - .action(api.invitations.action.create, { - repositoryId, - inviteeGithubUsername: "verified-member", - role: "viewer", - }); + const invitationId = await ( + await asUser(t, ownerUserId) + ).action(api.invitations.action.create, { + repositoryId, + inviteeGithubUsername: "verified-member", + role: "viewer", + }); await expect( - t - .withIdentity({ subject: `${inviteeUserId}|invitee-session` }) - .mutation(api.invitations.mutation.accept, { invitationId }), + (await asUser(t, inviteeUserId)).mutation( + api.invitations.mutation.accept, + { invitationId }, + ), ).resolves.toBe(invitationId); const member = await t.run(async (ctx) => ctx.db diff --git a/test/convex/invitations/identity.test.ts b/test/convex/invitations/identity.test.ts index 0a7c0aa..3bf2b5a 100644 --- a/test/convex/invitations/identity.test.ts +++ b/test/convex/invitations/identity.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest"; import { api, internal } from "../../../convex/_generated/api"; import type { Doc } from "../../../convex/_generated/dataModel"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -139,12 +140,8 @@ describe("invitation identity authorization", () => { createdAt: Date.now(), }), ); - const invitee = t.withIdentity({ - subject: `${inviteeUserId}|test-session`, - }); - const attacker = t.withIdentity({ - subject: `${attackerUserId}|test-session`, - }); + const invitee = await asUser(t, inviteeUserId); + const attacker = await asUser(t, attackerUserId); await expect( invitee.query(api.invitations.query.listPending, {}), @@ -224,9 +221,7 @@ describe("invitation identity authorization", () => { createdAt: Date.now(), }); }); - const invitee = t.withIdentity({ - subject: `${inviteeUserId}|test-session`, - }); + const invitee = await asUser(t, inviteeUserId); await expect( invitee.query(api.invitations.query.listPending, {}), @@ -257,9 +252,7 @@ describe("invitation identity authorization", () => { createdAt: Date.now(), }); }); - const invitee = t.withIdentity({ - subject: `${inviteeUserId}|test-session`, - }); + const invitee = await asUser(t, inviteeUserId); await expect( invitee.query(api.invitations.query.listPending, {}), @@ -306,9 +299,7 @@ describe("invitation identity authorization", () => { createdAt: Date.now(), }); }); - const invitee = t.withIdentity({ - subject: `${inviteeUserId}|test-session`, - }); + const invitee = await asUser(t, inviteeUserId); await expect( invitee.query(api.invitations.query.listPending, {}), @@ -351,11 +342,7 @@ describe("invitation identity authorization", () => { status: "pending", createdAt: now, }); - await ctx.db.insert("authAccounts", { - userId: inviteeUserId, - provider: "github", - providerAccountId: "777", - }); + await ctx.db.patch(inviteeUserId, { githubAccountId: "777" }); }); await expect( @@ -410,9 +397,7 @@ describe("invitation identity authorization", () => { }); return id; }); - const invitee = t.withIdentity({ - subject: `${inviteeUserId}|test-session`, - }); + const invitee = await asUser(t, inviteeUserId); await expect( invitee.mutation(api.invitations.mutation.accept, { invitationId }), diff --git a/test/convex/invitations/queryAccess.test.ts b/test/convex/invitations/queryAccess.test.ts index d593024..dc90fc1 100644 --- a/test/convex/invitations/queryAccess.test.ts +++ b/test/convex/invitations/queryAccess.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { api } from "../../../convex/_generated/api"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -105,17 +106,17 @@ describe("repository invitation query access", () => { return { ownerId, repositoryId, viewerId }; }); - const viewerResult = await t - .withIdentity({ subject: `${fixture.viewerId}|test-session` }) - .query(api.invitations.query.getPendingForRepository, { - repositoryId: fixture.repositoryId, - }); + const viewerResult = await ( + await asUser(t, fixture.viewerId) + ).query(api.invitations.query.getPendingForRepository, { + repositoryId: fixture.repositoryId, + }); expect(viewerResult).toEqual([]); - const viewerRole = await t - .withIdentity({ subject: `${fixture.viewerId}|test-session` }) - .query(api.repositoryMembers.query.getMyRole, { - repositoryId: fixture.repositoryId, - }); + const viewerRole = await ( + await asUser(t, fixture.viewerId) + ).query(api.repositoryMembers.query.getMyRole, { + repositoryId: fixture.repositoryId, + }); expect(viewerRole).toEqual({ role: "viewer", isOwner: false, @@ -123,11 +124,11 @@ describe("repository invitation query access", () => { canManageMembers: false, }); - const ownerResult = await t - .withIdentity({ subject: `${fixture.ownerId}|test-session` }) - .query(api.invitations.query.getPendingForRepository, { - repositoryId: fixture.repositoryId, - }); + const ownerResult = await ( + await asUser(t, fixture.ownerId) + ).query(api.invitations.query.getPendingForRepository, { + repositoryId: fixture.repositoryId, + }); expect(ownerResult).toEqual([ expect.objectContaining({ inviteeGithubUsername: "invitee", diff --git a/test/convex/invitations/teamEntitlementAccess.test.ts b/test/convex/invitations/teamEntitlementAccess.test.ts index edecec9..44bad4b 100644 --- a/test/convex/invitations/teamEntitlementAccess.test.ts +++ b/test/convex/invitations/teamEntitlementAccess.test.ts @@ -5,6 +5,7 @@ import { api } from "../../../convex/_generated/api"; import type { Id } from "../../../convex/_generated/dataModel"; import type { MutationCtx } from "../../../convex/_generated/server"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -158,11 +159,12 @@ async function expectDeniedWithoutSideEffects( fixture: Awaited>, ) { await expect( - t - .withIdentity({ subject: `${fixture.memberUserId}|member-session` }) - .mutation(api.invitations.mutation.accept, { + (await asUser(t, fixture.memberUserId)).mutation( + api.invitations.mutation.accept, + { invitationId: fixture.invitationId, - }), + }, + ), ).rejects.toThrow(); const state = await t.run(async (ctx) => ({ @@ -196,11 +198,12 @@ describe("repository owner team entitlement", () => { const fixture = await insertFixture(t, kind); await expect( - t - .withIdentity({ subject: `${fixture.memberUserId}|member-session` }) - .mutation(api.invitations.mutation.accept, { + (await asUser(t, fixture.memberUserId)).mutation( + api.invitations.mutation.accept, + { invitationId: fixture.invitationId, - }), + }, + ), ).resolves.toBe(fixture.invitationId); await expect( @@ -258,12 +261,8 @@ describe("repository owner team entitlement", () => { joinedAt: Date.now(), }); }); - const member = t.withIdentity({ - subject: `${fixture.memberUserId}|member-session`, - }); - const owner = t.withIdentity({ - subject: `${fixture.ownerUserId}|owner-session`, - }); + const member = await asUser(t, fixture.memberUserId); + const owner = await asUser(t, fixture.ownerUserId); await expect( member.query(api.repositoryMembers.query.getMyRole, { @@ -367,9 +366,7 @@ describe("repository owner team entitlement", () => { }); }); - const member = t.withIdentity({ - subject: `${fixture.memberUserId}|member-session`, - }); + const member = await asUser(t, fixture.memberUserId); await expect( member.query(api.repositoryMembers.query.getMyRole, { repositoryId: fixture.repositoryId, diff --git a/test/convex/lemonSqueezy/billingSettlement.test.ts b/test/convex/lemonSqueezy/billingSettlement.test.ts index 01c7357..2dc896c 100644 --- a/test/convex/lemonSqueezy/billingSettlement.test.ts +++ b/test/convex/lemonSqueezy/billingSettlement.test.ts @@ -21,6 +21,7 @@ import { type WebhookEnvelope, } from "../../../convex/lemonSqueezy/webhook"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -1771,9 +1772,7 @@ describe("authoritative subscription and invoice settlement", () => { status: "open", }); - const authenticated = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const authenticated = await asUser(t, adminUserId); await expect( authenticated.mutation( api.admin.paymentMutation.requeueSubscriptionInvoiceReview, @@ -3178,9 +3177,7 @@ describe("authoritative subscription and invoice settlement", () => { attemptCount: 1, }); const reviewId = firstAttemptReview.review._id; - const admin = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const admin = await asUser(t, adminUserId); await expect( admin.mutation(api.admin.paymentMutation.addTokens, { @@ -3415,9 +3412,7 @@ describe("authoritative subscription and invoice settlement", () => { boundaryId, }; }); - const admin = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const admin = await asUser(t, adminUserId); const requeueArgs = { manualReviewId: reviewId, evidenceReference: "ls-support-case-underfunded-7193", diff --git a/test/convex/providerApiKeys/providerApiKeys.test.ts b/test/convex/providerApiKeys/providerApiKeys.test.ts index e4a2dcd..c637e3c 100644 --- a/test/convex/providerApiKeys/providerApiKeys.test.ts +++ b/test/convex/providerApiKeys/providerApiKeys.test.ts @@ -8,6 +8,7 @@ import { encryptProviderKey, } from "../../../convex/providerApiKeys/crypto"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -44,7 +45,7 @@ async function signedIn(t: ReturnType) { const userId = await t.run(async (ctx) => ctx.db.insert("users", {})); return { userId, - as: t.withIdentity({ subject: `${userId}|session` }), + as: await asUser(t, userId), }; } @@ -151,9 +152,10 @@ describe("provider key management", () => { expect(listed[0]).not.toHaveProperty("ciphertext"); expect(listed[0]).not.toHaveProperty("iv"); - const other = t.withIdentity({ - subject: `${await t.run(async (ctx) => ctx.db.insert("users", {}))}|other`, - }); + const other = await asUser( + t, + await t.run(async (ctx) => ctx.db.insert("users", {})), + ); await expect( other.query(api.providerApiKeys.query.list, {}), ).resolves.toEqual([]); diff --git a/test/convex/pullRequests/lifecycle.test.ts b/test/convex/pullRequests/lifecycle.test.ts index c2d341f..6f9522e 100644 --- a/test/convex/pullRequests/lifecycle.test.ts +++ b/test/convex/pullRequests/lifecycle.test.ts @@ -17,6 +17,7 @@ import { drainScheduledFunctions } from "../scheduling"; import { REVIEW_BATCH_TOKEN_ESTIMATE } from "../../../convex/pullRequests/github"; import { PRICING, getFreeIncludedTokens } from "../../../convex/_ai/config"; import { encryptProviderKey } from "../../../convex/providerApiKeys/crypto"; +import { asUser } from "../../helpers/auth"; const modules = import.meta.glob("../../../convex/**/*.ts"); beforeEach(() => vi.useFakeTimers()); afterEach(() => { @@ -815,10 +816,11 @@ describe("review commands", () => { const f = await reviewed(); const r = await replies(f); const ticketId = (await f.t.run((ctx) => ctx.db.get(f.first)))!.ticketId; - const run = (command: "review" | "full_review") => - f.t - .withIdentity({ subject: f.userId }) - .action(api.pullRequests.action.command, { ticketId, command }); + const run = async (command: "review" | "full_review") => + (await asUser(f.t, f.userId)).action(api.pullRequests.action.command, { + ticketId, + command, + }); expect(await run("review")).toMatchObject({ command: "review", status: "started", @@ -829,12 +831,10 @@ describe("review commands", () => { expect(r.comment).not.toHaveBeenCalled(); const stranger = await f.t.run((ctx) => ctx.db.insert("users", {})); await expect( - f.t - .withIdentity({ subject: stranger }) - .action(api.pullRequests.action.command, { - ticketId, - command: "review", - }), + (await asUser(f.t, stranger)).action(api.pullRequests.action.command, { + ticketId, + command: "review", + }), ).rejects.toThrow("not authorized"); }); }); @@ -1309,12 +1309,12 @@ describe("PR review durable lifecycle", () => { const f = await fixture(); const { pullRequestReviewsEnabled: _, ...oldSettings } = settings; void _; - await f.t - .withIdentity({ subject: f.userId }) - .mutation(api.repositories.mutation.updateSettings, { - repositoryId: f.repositoryId, - settings: oldSettings, - }); + await ( + await asUser(f.t, f.userId) + ).mutation(api.repositories.mutation.updateSettings, { + repositoryId: f.repositoryId, + settings: oldSettings, + }); expect( (await f.t.run((ctx) => ctx.db.get(f.repositoryId)))?.settings .pullRequestReviewsEnabled, @@ -1324,12 +1324,13 @@ describe("PR review durable lifecycle", () => { const f = await fixture(); const other = await f.t.run((ctx) => ctx.db.insert("users", {})); await expect( - f.t - .withIdentity({ subject: other }) - .mutation(api.repositories.mutation.updateSettings, { + (await asUser(f.t, other)).mutation( + api.repositories.mutation.updateSettings, + { repositoryId: f.repositoryId, settings, - }), + }, + ), ).rejects.toThrow("unauthorized"); }); }); @@ -1348,7 +1349,7 @@ describe("open pull requests when reviews turn on", () => { settings: { ...settings, pullRequestReviewsEnabled: false }, }), ); - const owner = f.t.withIdentity({ subject: f.userId }); + const owner = await asUser(f.t, f.userId); for (let i = 0; i < 2; i++) await owner.mutation(api.repositories.mutation.updateSettings, { repositoryId: f.repositoryId, @@ -1419,7 +1420,7 @@ describe("open pull requests when reviews turn on", () => { }); it("starts at most one catch-up an hour, however often reviews toggle", async () => { const f = await fixture(); - const owner = f.t.withIdentity({ subject: f.userId }); + const owner = await asUser(f.t, f.userId); for (const enabled of [false, true, false, true]) await owner.mutation(api.repositories.mutation.updateSettings, { repositoryId: f.repositoryId, @@ -1429,7 +1430,7 @@ describe("open pull requests when reviews turn on", () => { }); it("starts a catch-up when a repository with reviews on is reactivated", async () => { const f = await fixture(); - const owner = f.t.withIdentity({ subject: f.userId }); + const owner = await asUser(f.t, f.userId); await owner.mutation(api.repositories.mutation.toggleActive, { repositoryId: f.repositoryId, isActive: false, @@ -1573,9 +1574,9 @@ describe("bot review quota protection at the live GitHub boundary", () => { ), }); await expect( - f.t - .withIdentity({ subject: f.userId }) - .action(api.pullRequests.action.recheck, { actionId }), + (await asUser(f.t, f.userId)).action(api.pullRequests.action.recheck, { + actionId, + }), ).rejects.toThrow("Bot-authored pull requests are not reviewed"); expect(f.provider).not.toHaveBeenCalled(); }, @@ -2952,9 +2953,9 @@ describe("explicit verification of failed reviews", () => { ).rejects.toThrow("authenticated"); const stranger = await f.t.run((ctx) => ctx.db.insert("users", {})); await expect( - f.t - .withIdentity({ subject: stranger }) - .action(api.pullRequests.action.recheck, { actionId: f.failedId }), + (await asUser(f.t, stranger)).action(api.pullRequests.action.recheck, { + actionId: f.failedId, + }), ).rejects.toThrow("authorized"); expect(access).not.toHaveBeenCalled(); }); diff --git a/test/convex/repoIndexing/fileListBound.test.ts b/test/convex/repoIndexing/fileListBound.test.ts index c153d78..61aafb0 100644 --- a/test/convex/repoIndexing/fileListBound.test.ts +++ b/test/convex/repoIndexing/fileListBound.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { api, internal } from "../../../convex/_generated/api"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -91,20 +92,20 @@ describe("repository query bounds", () => { return { userId, repositoryId }; }); - const files = await t - .withIdentity({ subject: `${userId}|test-session` }) - .query(api.repoIndexing.query.getFileList, { - repositoryId, - limit: 1_000, - }); + const files = await ( + await asUser(t, userId) + ).query(api.repoIndexing.query.getFileList, { + repositoryId, + limit: 1_000, + }); expect(files).toHaveLength(500); - const logs = await t - .withIdentity({ subject: `${userId}|test-session` }) - .query(api.repoIndexing.query.getIndexingLogs, { - repositoryId, - limit: 1_000, - }); + const logs = await ( + await asUser(t, userId) + ).query(api.repoIndexing.query.getIndexingLogs, { + repositoryId, + limit: 1_000, + }); expect(logs).toHaveLength(500); }); @@ -180,9 +181,7 @@ describe("repository query bounds", () => { }); return { userId, installationId, repositoryId, now }; }); - const authenticated = t.withIdentity({ - subject: `${fixture.userId}|test-session`, - }); + const authenticated = await asUser(t, fixture.userId); await expect( authenticated.query(api.repoIndexing.query.getFileContent, { diff --git a/test/convex/repoLearnings/trustedCount.test.ts b/test/convex/repoLearnings/trustedCount.test.ts index 238dabe..c48afb8 100644 --- a/test/convex/repoLearnings/trustedCount.test.ts +++ b/test/convex/repoLearnings/trustedCount.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vitest"; import { api } from "../../../convex/_generated/api"; import schema from "../../../convex/schema"; import { getTrustedLearningRepositoryKey } from "../../../convex/repoLearnings/trust"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -76,9 +77,9 @@ describe("repository learning trusted count", () => { return { userId, repositoryId }; }); - const count = await t - .withIdentity({ subject: `${userId}|test-session` }) - .query(api.repoLearnings.query.countByRepository, { repositoryId }); + const count = await ( + await asUser(t, userId) + ).query(api.repoLearnings.query.countByRepository, { repositoryId }); expect(count).toBe(1); }); diff --git a/test/convex/repositories/connectIdentity.test.ts b/test/convex/repositories/connectIdentity.test.ts index 2ad2cdb..6d71973 100644 --- a/test/convex/repositories/connectIdentity.test.ts +++ b/test/convex/repositories/connectIdentity.test.ts @@ -9,6 +9,7 @@ import type { Id } from "../../../convex/_generated/dataModel"; import { internalMutation } from "../../../convex/_generated/server"; import * as githubHelpers from "../../../convex/github/helpers"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; let mockedFetch: MockedFunction< typeof githubHelpers.fetchGitHubAppJsonWithRetry @@ -148,12 +149,12 @@ describe("repository connection identity", () => { stargazers_count: 5, }); - const repositoryId = await t - .withIdentity({ subject: `${userId}|session` }) - .action(api.repositories.action.createAndIndex, { - installationId: 123, - githubRepositoryId: 456, - }); + const repositoryId = await ( + await asUser(t, userId) + ).action(api.repositories.action.createAndIndex, { + installationId: 123, + githubRepositoryId: 456, + }); const repository = await t.run( async (ctx) => await ctx.db.get(repositoryId), ); @@ -180,12 +181,10 @@ describe("repository connection identity", () => { ); await expect( - t - .withIdentity({ subject: `${userId}|session` }) - .action(api.repositories.action.createAndIndex, { - installationId: 123, - githubRepositoryId: 999, - }), + (await asUser(t, userId)).action(api.repositories.action.createAndIndex, { + installationId: 123, + githubRepositoryId: 999, + }), ).rejects.toThrow( "Unable to verify repository access through the GitHub App installation", ); @@ -209,12 +208,10 @@ describe("repository connection identity", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|session` }) - .action(api.repositories.action.createAndIndex, { - installationId: 123, - githubRepositoryId: 456, - }), + (await asUser(t, userId)).action(api.repositories.action.createAndIndex, { + installationId: 123, + githubRepositoryId: 456, + }), ).rejects.toThrow( "Unable to verify repository access through the GitHub App installation", ); @@ -241,12 +238,10 @@ describe("repository connection identity", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|session` }) - .action(api.repositories.action.createAndIndex, { - installationId: 123, - githubRepositoryId: 456, - }), + (await asUser(t, userId)).action(api.repositories.action.createAndIndex, { + installationId: 123, + githubRepositoryId: 456, + }), ).rejects.toThrow( "Unable to verify repository access through the GitHub App installation", ); @@ -307,13 +302,11 @@ describe("repository connection identity", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|session` }) - .action(api.repositories.action.createAndIndex, { - installationId: 123, - githubRepositoryId: 457, - reconnectRepositoryId, - }), + (await asUser(t, userId)).action(api.repositories.action.createAndIndex, { + installationId: 123, + githubRepositoryId: 457, + reconnectRepositoryId, + }), ).resolves.toEqual(expect.any(String)); expect(mockedToken).toHaveBeenCalledOnce(); }); @@ -364,13 +357,11 @@ describe("repository connection identity", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|session` }) - .action(api.repositories.action.createAndIndex, { - installationId: 123, - githubRepositoryId: 457, - reconnectRepositoryId, - }), + (await asUser(t, userId)).action(api.repositories.action.createAndIndex, { + installationId: 123, + githubRepositoryId: 457, + reconnectRepositoryId, + }), ).rejects.toThrow("Repository reconnect target is not available"); expect(mockedToken).not.toHaveBeenCalled(); }); diff --git a/test/convex/repositories/createScheduling.test.ts b/test/convex/repositories/createScheduling.test.ts index 1e2871a..966c07c 100644 --- a/test/convex/repositories/createScheduling.test.ts +++ b/test/convex/repositories/createScheduling.test.ts @@ -5,6 +5,7 @@ import { v } from "convex/values"; import { internal } from "../../../convex/_generated/api"; import { internalAction } from "../../../convex/_generated/server"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const noopIndexRepository = internalAction({ args: { @@ -66,15 +67,15 @@ describe("repository creation", () => { return userId; }); - const repositoryId = await t - .withIdentity({ subject: `${userId}|test-session` }) - .mutation(internal.repositories.mutation.create, { - installationId: 123, - githubRepositoryId: 456, - githubRepo: "owner/repo", - name: "repo", - githubUrl: "https://github.com/owner/repo", - }); + const repositoryId = await ( + await asUser(t, userId) + ).mutation(internal.repositories.mutation.create, { + installationId: 123, + githubRepositoryId: 456, + githubRepo: "owner/repo", + name: "repo", + githubUrl: "https://github.com/owner/repo", + }); const state = await t.run(async (ctx) => ({ repository: await ctx.db.get(repositoryId), @@ -182,9 +183,7 @@ describe("repository creation", () => { }); return { userId, memberId, repositoryId }; }); - const identity = t.withIdentity({ - subject: `${fixture.userId}|test-session`, - }); + const identity = await asUser(t, fixture.userId); await expect( identity.mutation(internal.repositories.mutation.create, { @@ -331,16 +330,17 @@ describe("repository creation", () => { }); await expect( - t - .withIdentity({ subject: `${fixture.userId}|test-session` }) - .mutation(internal.repositories.mutation.create, { + (await asUser(t, fixture.userId)).mutation( + internal.repositories.mutation.create, + { installationId: 889, githubRepositoryId: 4_700, githubRepo: "owner/reused-name", name: "reused-name", githubUrl: "https://github.com/owner/reused-name", reconnectRepositoryId: fixture.reconnectRepositoryId, - }), + }, + ), ).rejects.toThrow("repository already connected"); const state = await t.run(async (ctx) => ({ @@ -418,16 +418,16 @@ describe("repository creation", () => { return { userId, repositoryId, now }; }); - const repositoryId = await t - .withIdentity({ subject: `${fixture.userId}|test-session` }) - .mutation(internal.repositories.mutation.create, { - installationId: 889, - githubRepositoryId: 9_003, - githubRepo: "owner/paused-after-reinstall", - name: "paused-after-reinstall", - githubUrl: "https://github.com/owner/paused-after-reinstall", - reconnectRepositoryId: fixture.repositoryId, - }); + const repositoryId = await ( + await asUser(t, fixture.userId) + ).mutation(internal.repositories.mutation.create, { + installationId: 889, + githubRepositoryId: 9_003, + githubRepo: "owner/paused-after-reinstall", + name: "paused-after-reinstall", + githubUrl: "https://github.com/owner/paused-after-reinstall", + reconnectRepositoryId: fixture.repositoryId, + }); const state = await t.run(async (ctx) => ({ repository: await ctx.db.get(repositoryId), @@ -521,15 +521,15 @@ describe("repository creation", () => { return { userId, staleRepositoryId }; }); - const repositoryId = await t - .withIdentity({ subject: `${fixture.userId}|test-session` }) - .mutation(internal.repositories.mutation.create, { - installationId: 125, - githubRepositoryId: 459, - githubRepo: "owner/pinned", - name: "pinned", - githubUrl: "https://github.com/owner/pinned", - }); + const repositoryId = await ( + await asUser(t, fixture.userId) + ).mutation(internal.repositories.mutation.create, { + installationId: 125, + githubRepositoryId: 459, + githubRepo: "owner/pinned", + name: "pinned", + githubUrl: "https://github.com/owner/pinned", + }); const state = await t.run(async (ctx) => ({ stale: await ctx.db.get(fixture.staleRepositoryId), @@ -580,15 +580,16 @@ describe("repository creation", () => { }); await expect( - t - .withIdentity({ subject: `${callerId}|test-session` }) - .mutation(internal.repositories.mutation.create, { + (await asUser(t, callerId)).mutation( + internal.repositories.mutation.create, + { installationId: 456, githubRepositoryId: 789, githubRepo: "other-owner/private-repo", name: "private-repo", githubUrl: "https://github.com/other-owner/private-repo", - }), + }, + ), ).rejects.toThrow("unauthorized installation"); const state = await t.run(async (ctx) => ({ @@ -621,15 +622,16 @@ describe("repository creation", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .mutation(internal.repositories.mutation.create, { + (await asUser(t, userId)).mutation( + internal.repositories.mutation.create, + { installationId: 789, githubRepositoryId: 790, githubRepo: "owner/repo", name: "repo", githubUrl: "https://github.com/owner/repo", - }), + }, + ), ).rejects.toThrow("unauthorized installation"); expect( await t.run(async (ctx) => ctx.db.query("repositories").collect()), @@ -667,15 +669,16 @@ describe("repository creation", () => { }); await expect( - t - .withIdentity({ subject: `${userId}|test-session` }) - .mutation(internal.repositories.mutation.create, { + (await asUser(t, userId)).mutation( + internal.repositories.mutation.create, + { installationId: 890, githubRepositoryId: 891, githubRepo: "owner/reconciliation-race", name: "reconciliation-race", githubUrl: "https://github.com/owner/reconciliation-race", - }), + }, + ), ).rejects.toThrow("unauthorized installation"); expect( diff --git a/test/convex/repositories/disconnectLifecycle.test.ts b/test/convex/repositories/disconnectLifecycle.test.ts index b5967db..88eb99f 100644 --- a/test/convex/repositories/disconnectLifecycle.test.ts +++ b/test/convex/repositories/disconnectLifecycle.test.ts @@ -7,6 +7,7 @@ import { api, internal } from "../../../convex/_generated/api"; import { internalAction } from "../../../convex/_generated/server"; import schema from "../../../convex/schema"; import { CLAIMED_EXECUTION_RECOVERY_GRACE_MS } from "../../../convex/ticketActions/executionRecovery"; +import { asUser } from "../../helpers/auth"; const noopIndexRepository = internalAction({ args: { @@ -127,7 +128,7 @@ describe("repository lifecycle fencing", () => { it("applies repeated desired activity states without toggling or duplicate jobs", async () => { const t = convexTest(schema, modules); const { userId, repositoryId } = await insertRepository(t); - const owner = t.withIdentity({ subject: `${userId}|test-session` }); + const owner = await asUser(t, userId); for (let i = 0; i < 2; i++) await owner.mutation(api.repositories.mutation.toggleActive, { repositoryId, @@ -157,9 +158,7 @@ describe("repository lifecycle fencing", () => { it("bumps on pause, schedules a fresh resume, and rejects stale publication", async () => { const t = convexTest(schema, modules); const { userId, repositoryId } = await insertRepository(t); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await authenticated.mutation(api.repositories.mutation.toggleActive, { repositoryId, @@ -227,10 +226,8 @@ describe("repository lifecycle fencing", () => { }); return { invitationId, inviteeUserId }; }); - const owner = t.withIdentity({ subject: `${userId}|test-session` }); - const invitee = t.withIdentity({ - subject: `${fixture.inviteeUserId}|test-session`, - }); + const owner = await asUser(t, userId); + const invitee = await asUser(t, fixture.inviteeUserId); await owner.mutation(api.repositories.mutation.remove, { repositoryId }); @@ -563,9 +560,7 @@ describe("repository lifecycle fencing", () => { }; }); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await authenticated.mutation(api.repositories.mutation.remove, { repositoryId, }); @@ -756,9 +751,7 @@ describe("repository lifecycle fencing", () => { }); return { foreignRepositoryId, otherUserId, storageId }; }); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await authenticated.mutation(api.repositories.mutation.remove, { repositoryId, }); diff --git a/test/convex/repositories/queryAccess.test.ts b/test/convex/repositories/queryAccess.test.ts index 971c62e..047b23b 100644 --- a/test/convex/repositories/queryAccess.test.ts +++ b/test/convex/repositories/queryAccess.test.ts @@ -6,6 +6,7 @@ import type { Doc, Id } from "../../../convex/_generated/dataModel"; import { getCanonicalGitHubRepositoryFullNameKey } from "../../../convex/github/repositoryIdentity"; import { REPOSITORY_ROUTE_DUPLICATE_LIMIT } from "../../../convex/repositories/query"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -231,7 +232,7 @@ describe("repository route access", () => { disconnectCleanupPhase: "tree", }); - const caller = t.withIdentity({ subject: `${callerId}|test-session` }); + const caller = await asUser(t, callerId); const [repositories, repositoryByRoute, repositoryById] = await Promise.all( [ caller.query(api.repositories.query.list, {}), @@ -293,9 +294,9 @@ describe("repository route access", () => { ragContinuationToken: "private-token", }); }); - const repo = await t - .withIdentity({ subject: `${userId}|test-session` }) - .query(api.repositories.query.getById, { repositoryId }); + const repo = await ( + await asUser(t, userId) + ).query(api.repositories.query.getById, { repositoryId }); expect(repo?.indexingProgress).toEqual({ phase: "search", lastProgressAt: 1000, @@ -314,9 +315,9 @@ describe("repository route access", () => { const callerId = await t.run(async (ctx) => ctx.db.insert("users", {})); const repositoryId = await insertRepository(t, callerId, "Owner/Repo"); - const repository = await t - .withIdentity({ subject: `${callerId}|test-session` }) - .query(api.repositories.query.get, { owner: "owner", repo: "repo" }); + const repository = await ( + await asUser(t, callerId) + ).query(api.repositories.query.get, { owner: "owner", repo: "repo" }); expect(repository).toMatchObject({ _id: repositoryId, @@ -335,9 +336,9 @@ describe("repository route access", () => { await insertRepository(t, otherUserId); const ownedRepositoryId = await insertRepository(t, callerId); - const repository = await t - .withIdentity({ subject: `${callerId}|test-session` }) - .query(api.repositories.query.get, { owner: "owner", repo: "repo" }); + const repository = await ( + await asUser(t, callerId) + ).query(api.repositories.query.get, { owner: "owner", repo: "repo" }); expect(repository).toMatchObject({ _id: ownedRepositoryId, @@ -381,9 +382,9 @@ describe("repository route access", () => { }); }); - const repository = await t - .withIdentity({ subject: `${callerId}|test-session` }) - .query(api.repositories.query.get, { owner: "owner", repo: "repo" }); + const repository = await ( + await asUser(t, callerId) + ).query(api.repositories.query.get, { owner: "owner", repo: "repo" }); expect(repository).toMatchObject({ _id: sharedRepositoryId, @@ -397,9 +398,9 @@ describe("repository route access", () => { await insertRepository(t, callerId); await insertInstallation(t, callerId); - const repository = await t - .withIdentity({ subject: `${callerId}|test-session` }) - .query(api.repositories.query.get, { owner: "owner", repo: "repo" }); + const repository = await ( + await asUser(t, callerId) + ).query(api.repositories.query.get, { owner: "owner", repo: "repo" }); expect(repository).not.toHaveProperty("invitationUnavailableReason"); }); @@ -425,9 +426,9 @@ describe("repository route access", () => { await insertRepository(t, callerId); await insertInstallation(t, callerId, state); - const repository = await t - .withIdentity({ subject: `${callerId}|test-session` }) - .query(api.repositories.query.get, { owner: "owner", repo: "repo" }); + const repository = await ( + await asUser(t, callerId) + ).query(api.repositories.query.get, { owner: "owner", repo: "repo" }); expect(repository).toMatchObject({ invitationUnavailableReason: expectedReason, @@ -444,9 +445,10 @@ describe("repository route access", () => { } await expect( - t - .withIdentity({ subject: `${callerId}|test-session` }) - .query(api.repositories.query.get, { owner: "owner", repo: "repo" }), + (await asUser(t, callerId)).query(api.repositories.query.get, { + owner: "owner", + repo: "repo", + }), ).rejects.toThrow("repository lookup exceeded the duplicate safety limit"); }); }); diff --git a/test/convex/repositories/syncInstallation.test.ts b/test/convex/repositories/syncInstallation.test.ts index 2b3d93c..973cf6c 100644 --- a/test/convex/repositories/syncInstallation.test.ts +++ b/test/convex/repositories/syncInstallation.test.ts @@ -8,6 +8,7 @@ import type { Id } from "../../../convex/_generated/dataModel"; import { internalMutation } from "../../../convex/_generated/server"; import * as githubHelpers from "../../../convex/github/helpers"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; let mockedFetchGitHubAppJsonWithRetry: MockedFunction< typeof githubHelpers.fetchGitHubAppJsonWithRetry @@ -201,14 +202,15 @@ describe("repository installation recovery", () => { }); }); - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.repositories.action.syncRepository, { repositoryId }); + const result = await ( + await asUser(t, ownerId) + ).action(api.repositories.action.syncRepository, { repositoryId }); await expect( - t - .withIdentity({ subject: `${ownerId}|test-session` }) - .mutation(api.repositories.mutation.toggleActive, { repositoryId }), + (await asUser(t, ownerId)).mutation( + api.repositories.mutation.toggleActive, + { repositoryId }, + ), ).rejects.toThrow("GitHub App repository access has been removed"); expect(result).toEqual({ @@ -233,9 +235,9 @@ describe("repository installation recovery", () => { stargazers_count: 10, }); - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.repositories.action.syncRepository, { repositoryId }); + const result = await ( + await asUser(t, ownerId) + ).action(api.repositories.action.syncRepository, { repositoryId }); expect(result).toEqual({ success: true, message: "Sync started" }); expect(mockedFetchGitHubAppJsonWithRetry.mock.calls[0]?.[0]).toBe( @@ -302,9 +304,10 @@ describe("repository installation recovery", () => { }); await expect( - t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.repositories.action.syncRepository, { repositoryId }), + (await asUser(t, ownerId)).action( + api.repositories.action.syncRepository, + { repositoryId }, + ), ).resolves.toEqual({ success: true, message: "Sync started" }); const state = await t.run(async (ctx) => ({ @@ -336,9 +339,9 @@ describe("repository installation recovery", () => { await insertInstallation(t, otherUserId, 222); const repositoryId = await insertRepository(t, ownerId, 222); - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.repositories.action.syncRepository, { repositoryId }); + const result = await ( + await asUser(t, ownerId) + ).action(api.repositories.action.syncRepository, { repositoryId }); expect(result).toEqual({ success: false, @@ -361,9 +364,9 @@ describe("repository installation recovery", () => { await t.run(async (ctx) => { await ctx.db.patch(repositoryId, { githubRepositoryId: 999 }); }); - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.repositories.action.syncRepository, { repositoryId }); + const result = await ( + await asUser(t, ownerId) + ).action(api.repositories.action.syncRepository, { repositoryId }); const repository = await t.run(async (ctx) => ctx.db.get(repositoryId)); expect(result).toEqual({ @@ -388,9 +391,9 @@ describe("repository installation recovery", () => { ); const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); - const result = await t - .withIdentity({ subject: `${ownerId}|test-session` }) - .action(api.repositories.action.syncRepository, { repositoryId }); + const result = await ( + await asUser(t, ownerId) + ).action(api.repositories.action.syncRepository, { repositoryId }); expect(result.success).toBe(false); expect(result.message).not.toContain("sensitive"); diff --git a/test/convex/subscriptions/entitlementProvenance.test.ts b/test/convex/subscriptions/entitlementProvenance.test.ts index bbe2795..3aab448 100644 --- a/test/convex/subscriptions/entitlementProvenance.test.ts +++ b/test/convex/subscriptions/entitlementProvenance.test.ts @@ -9,6 +9,7 @@ import { hasTrustedProEntitlement, } from "../../../convex/subscriptions/entitlement"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -121,9 +122,7 @@ describe("trusted Pro entitlement provenance", () => { vi.setSystemTime(new Date("2026-07-20T12:34:56.789Z")); const t = convexTest(schema, modules); const userId = await t.run((ctx) => ctx.db.insert("users", {})); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.subscriptions.query.getCurrent, {}), @@ -164,9 +163,7 @@ describe("trusted Pro entitlement provenance", () => { }); return userId; }); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.subscriptions.query.calculateOverage, {}), @@ -219,9 +216,7 @@ describe("trusted Pro entitlement provenance", () => { }); return userId; }); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.subscriptions.query.getCurrent, {}), diff --git a/test/convex/subscriptions/mutationSecurity.test.ts b/test/convex/subscriptions/mutationSecurity.test.ts index d58a51b..fa51af4 100644 --- a/test/convex/subscriptions/mutationSecurity.test.ts +++ b/test/convex/subscriptions/mutationSecurity.test.ts @@ -9,6 +9,7 @@ import { createSettlementKeyFingerprint, } from "../../../convex/lemonSqueezy/webhook"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -232,12 +233,13 @@ describe("subscription mutation trust boundary", () => { ); await expect( - t - .withIdentity({ subject: `${callerUserId}|client-session` }) - .mutation(api.admin.paymentMutation.reactivateSubscription, { + (await asUser(t, callerUserId)).mutation( + api.admin.paymentMutation.reactivateSubscription, + { subscriptionId, operationId: "00000000-0000-4000-8000-000000000001", - }), + }, + ), ).rejects.toThrow("Admin access required"); const subscriptions = await t.run(async (ctx) => @@ -280,12 +282,13 @@ describe("subscription mutation trust boundary", () => { }); await expect( - t - .withIdentity({ subject: `${adminUserId}|admin-session` }) - .mutation(api.admin.paymentMutation.reactivateSubscription, { + (await asUser(t, adminUserId)).mutation( + api.admin.paymentMutation.reactivateSubscription, + { subscriptionId, operationId: "00000000-0000-4000-8000-000000000002", - }), + }, + ), ).resolves.toEqual({ success: true }); const subscription = await t.run(async (ctx) => ctx.db.get(subscriptionId)); @@ -348,9 +351,7 @@ describe("subscription mutation trust boundary", () => { ); return { adminUserId, targetUserId, subscriptionId, boundaryId }; }); - const admin = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const admin = await asUser(t, adminUserId); await expect( admin.mutation(api.admin.paymentMutation.reactivateSubscription, { @@ -484,9 +485,7 @@ describe("subscription mutation trust boundary", () => { oldBoundaryId, }; }); - const admin = t.withIdentity({ - subject: `${adminUserId}|admin-session`, - }); + const admin = await asUser(t, adminUserId); await expect( admin.mutation(api.admin.paymentMutation.reactivateSubscription, { @@ -621,12 +620,13 @@ describe("subscription mutation trust boundary", () => { }); await expect( - t - .withIdentity({ subject: `${adminUserId}|admin-session` }) - .mutation(api.admin.paymentMutation.reactivateSubscription, { + (await asUser(t, adminUserId)).mutation( + api.admin.paymentMutation.reactivateSubscription, + { subscriptionId, operationId: "00000000-0000-4000-8000-000000000005", - }), + }, + ), ).rejects.toThrow( "Purchased-token wallet cannot cover the exact terminal settlement", ); diff --git a/test/convex/subscriptions/trialCredit.test.ts b/test/convex/subscriptions/trialCredit.test.ts index f29453e..4a9b8a8 100644 --- a/test/convex/subscriptions/trialCredit.test.ts +++ b/test/convex/subscriptions/trialCredit.test.ts @@ -13,6 +13,7 @@ import { } from "../../../convex/_ai/config"; import { getEffectiveSubscriptionEntitlement } from "../../../convex/subscriptions/entitlement"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = import.meta.glob("../../../convex/**/*.ts"); const AFTER_CUTOFF = Date.parse("2026-12-15T12:00:00Z"); @@ -23,7 +24,7 @@ afterEach(() => { async function signedIn(t: ReturnType) { const userId = await t.run(async (ctx) => ctx.db.insert("users", {})); - return { userId, as: t.withIdentity({ subject: `${userId}|session` }) }; + return { userId, as: await asUser(t, userId) }; } async function wallet(t: ReturnType) { @@ -117,7 +118,7 @@ describe("one-time trial credit", () => { const userId = await t.run(async (ctx) => ctx.db.insert("users", { name: "octocat" }), ); - const as = t.withIdentity({ subject: `${userId}|session` }); + const as = await asUser(t, userId); const { CURRENT_PRIVACY_POLICY_VERSION, CURRENT_TERMS_VERSION } = await import("../../../convex/users/legal"); vi.useFakeTimers(); diff --git a/test/convex/ticketActions/publicRecoveryRedaction.test.ts b/test/convex/ticketActions/publicRecoveryRedaction.test.ts index 579f78e..7046265 100644 --- a/test/convex/ticketActions/publicRecoveryRedaction.test.ts +++ b/test/convex/ticketActions/publicRecoveryRedaction.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest"; import { api, internal } from "../../../convex/_generated/api"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -83,9 +84,7 @@ describe("public ticket recovery redaction", () => { }); return { userId, ticketId, actionId }; }); - const caller = t.withIdentity({ - subject: `${fixture.userId}|test-session`, - }); + const caller = await asUser(t, fixture.userId); const [tickets, ticket, actions, action] = await Promise.all([ caller.query(api.tickets.query.list, {}), diff --git a/test/convex/tokenUsage/chatUsage.test.ts b/test/convex/tokenUsage/chatUsage.test.ts index 69593e0..bef3f07 100644 --- a/test/convex/tokenUsage/chatUsage.test.ts +++ b/test/convex/tokenUsage/chatUsage.test.ts @@ -29,6 +29,7 @@ import { CLAUDE_API_ENDS_AT, GENERATION_MODELS, } from "../../../convex/_ai/config"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -678,7 +679,7 @@ describe("AI chat usage reservations", () => { const t = convexTest(schema, modules); const fixture = await insertFixture(t); const adminUserId = await insertAdminUser(t); - const admin = t.withIdentity({ subject: `${adminUserId}|admin-session` }); + const admin = await asUser(t, adminUserId); const ended = await insertEndedProPeriod(t, fixture, { purchasedTokens: 100, overageTokens: 40, @@ -2893,7 +2894,7 @@ describe("AI chat usage reservations", () => { const t = convexTest(schema, modules); const fixture = await insertFixture(t); const adminUserId = await insertAdminUser(t); - const admin = t.withIdentity({ subject: `${adminUserId}|admin-session` }); + const admin = await asUser(t, adminUserId); const notBilled = reservationArgs(fixture, "reconcile-not-billed"); await reserve(t, notBilled); await markStarted(t, notBilled); @@ -2962,7 +2963,7 @@ describe("AI chat usage reservations", () => { const t = convexTest(schema, modules); const fixture = await insertFixture(t); const adminUserId = await insertAdminUser(t); - const admin = t.withIdentity({ subject: `${adminUserId}|admin-session` }); + const admin = await asUser(t, adminUserId); const subscriptionId = await insertTrustedProWallet(t, fixture.userId, 100); const billed = reservationArgs(fixture, "reconcile-over-ceiling", 1, { inputTokenLimit: 10, diff --git a/test/convex/tokenUsage/numericSafety.test.ts b/test/convex/tokenUsage/numericSafety.test.ts index 4e835a3..e7772c0 100644 --- a/test/convex/tokenUsage/numericSafety.test.ts +++ b/test/convex/tokenUsage/numericSafety.test.ts @@ -6,6 +6,7 @@ import { MAX_COLLECT_LIMIT } from "../../../convex/_utils/pagination"; import schema from "../../../convex/schema"; import { calculateSafeBillingCosts } from "../../../convex/subscriptions/query"; import { readQuotaTokenUsage } from "../../../convex/tokenUsage/quota"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -173,7 +174,7 @@ describe("token usage numeric safety", () => { }); } }); - const authenticated = t.withIdentity({ subject: `${userId}|session` }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.tokenUsage.query.getCurrentMonthUsage, {}), @@ -206,7 +207,7 @@ describe("token usage numeric safety", () => { createdAt: Date.now(), }); }); - const authenticated = t.withIdentity({ subject: `${userId}|session` }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.tokenUsage.query.getCurrentMonthUsage, {}), diff --git a/test/convex/tokenUsage/periodTotals.test.ts b/test/convex/tokenUsage/periodTotals.test.ts index c06d94d..e702993 100644 --- a/test/convex/tokenUsage/periodTotals.test.ts +++ b/test/convex/tokenUsage/periodTotals.test.ts @@ -19,6 +19,7 @@ import { } from "../../../convex/tokenUsage/periodTotals"; import { insertTokenUsage } from "../../../convex/tokenUsage/totals"; import { drainScheduledFunctions } from "../scheduling"; +import { asUser } from "../../helpers/auth"; const modules = import.meta.glob("../../../convex/**/*.ts"); type Backend = ReturnType; @@ -303,10 +304,10 @@ describe("token usage period totals", () => { }), ); }); - const asUser = t.withIdentity({ subject: `${userId}|session` }); + const caller = await asUser(t, userId); const fromTotals = { - month: await asUser.query(api.tokenUsage.query.getCurrentMonthUsage, {}), - repositories: await asUser.query( + month: await caller.query(api.tokenUsage.query.getCurrentMonthUsage, {}), + repositories: await caller.query( api.tokenUsage.query.getUsageByRepository, {}, ), @@ -319,8 +320,8 @@ describe("token usage period totals", () => { } }); const fromRows = { - month: await asUser.query(api.tokenUsage.query.getCurrentMonthUsage, {}), - repositories: await asUser.query( + month: await caller.query(api.tokenUsage.query.getCurrentMonthUsage, {}), + repositories: await caller.query( api.tokenUsage.query.getUsageByRepository, {}, ), @@ -389,8 +390,8 @@ describe("token usage period totals", () => { totalCostCents: 0, }); - const asUser = t.withIdentity({ subject: `${userId}|session` }); - const fromTotals = await asUser.query( + const caller = await asUser(t, userId); + const fromTotals = await caller.query( api.tokenUsage.query.getUsageByRepository, {}, ); @@ -401,7 +402,7 @@ describe("token usage period totals", () => { await ctx.db.delete(doc._id); } }); - const fromRows = await asUser.query( + const fromRows = await caller.query( api.tokenUsage.query.getUsageByRepository, {}, ); diff --git a/test/convex/tokenUsage/purchasedTokenBalance.test.ts b/test/convex/tokenUsage/purchasedTokenBalance.test.ts index 74e8ede..69dba88 100644 --- a/test/convex/tokenUsage/purchasedTokenBalance.test.ts +++ b/test/convex/tokenUsage/purchasedTokenBalance.test.ts @@ -5,6 +5,7 @@ import { api, internal } from "../../../convex/_generated/api"; import type { Id } from "../../../convex/_generated/dataModel"; import { PRICING, getFreeIncludedTokens } from "../../../convex/_ai/config"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -88,7 +89,7 @@ describe("durable purchased-token balance", () => { now: july, purchasedTokens: 100, }); - const authenticated = t.withIdentity({ subject: `${userId}|session` }); + const authenticated = await asUser(t, userId); await recordChatUsage(t, userId, getFreeIncludedTokens(Date.now()) + 60); await expect( @@ -245,7 +246,7 @@ describe("durable purchased-token balance", () => { }); return { userId, subscriptionId }; }); - const authenticated = t.withIdentity({ subject: `${userId}|session` }); + const authenticated = await asUser(t, userId); const tokenLimit = PRICING.PRO_INCLUDED_TOKENS + 100; await expect( @@ -298,7 +299,7 @@ describe("durable purchased-token balance", () => { createdAt: now, }); }); - const authenticated = t.withIdentity({ subject: `${userId}|session` }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.subscriptions.query.getCurrent, {}), diff --git a/test/convex/tokenUsage/userKeyUsage.test.ts b/test/convex/tokenUsage/userKeyUsage.test.ts index 5a79b07..7278fe5 100644 --- a/test/convex/tokenUsage/userKeyUsage.test.ts +++ b/test/convex/tokenUsage/userKeyUsage.test.ts @@ -29,6 +29,7 @@ import { rebuildUsageTotalsHour, } from "../../../convex/tokenUsage/totals"; import schema from "../../../convex/schema"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -928,7 +929,7 @@ describe("usage reporting for user keys", () => { ); expect(totals).toEqual([expect.objectContaining({ totalTokens: 40 })]); - const as = t.withIdentity({ subject: `${fixture.userId}|session` }); + const as = await asUser(t, fixture.userId); const monthly = await as.query( api.tokenUsage.query.getCurrentMonthUsage, {}, @@ -1008,7 +1009,7 @@ describe("usage reporting for user keys", () => { }); }); - const as = t.withIdentity({ subject: `${fixture.userId}|session` }); + const as = await asUser(t, fixture.userId); const usage = await as.query(api.tokenUsage.query.getUserKeyUsage, {}); expect(usage).toMatchObject({ isPartial: false, @@ -1074,7 +1075,7 @@ describe("usage reporting for user keys", () => { // Another account sees none of it. const otherUser = await t.run(async (ctx) => ctx.db.insert("users", {})); - const other = t.withIdentity({ subject: `${otherUser}|session` }); + const other = await asUser(t, otherUser); await expect( other.query(api.tokenUsage.query.getTicketUsage, { ticketId: fixture.ticketId, @@ -1142,7 +1143,7 @@ describe("round 3 provider key state", () => { await expect( resolveGenerationProvider(actionCtx(t), { userId: fixture.userId }), ).rejects.toMatchObject({ code: "unreadable" }); - const as = t.withIdentity({ subject: `${fixture.userId}|session` }); + const as = await asUser(t, fixture.userId); await expect(as.query(api.providerApiKeys.query.list, {})).resolves.toEqual( [expect.objectContaining({ readable: false, status: "active" })], ); @@ -1161,7 +1162,7 @@ describe("round 3 provider key state", () => { await expect( resolveGenerationProvider(actionCtx(t), { userId: fixture.userId }), ).rejects.toMatchObject({ code: "service_unavailable" }); - const as = t.withIdentity({ subject: `${fixture.userId}|session` }); + const as = await asUser(t, fixture.userId); await expect(as.query(api.providerApiKeys.query.list, {})).resolves.toEqual( [expect.objectContaining({ serviceUnavailable: true, readable: true })], ); @@ -1229,7 +1230,7 @@ describe("round 4 server key expectations", () => { const correctKey = process.env.BYOK_ENCRYPTION_KEY; process.env.BYOK_ENCRYPTION_KEY = btoa("w".repeat(32)); vi.spyOn(console, "error").mockImplementation(() => undefined); - const as = t.withIdentity({ subject: `${fixture.userId}|session` }); + const as = await asUser(t, fixture.userId); await expect( resolveGenerationProvider(actionCtx(t), { userId: fixture.userId }), @@ -1267,7 +1268,7 @@ describe("round 4 server key expectations", () => { internal.providerApiKeys.internalMutation.setExpectedEncryptionKeyId, { keyId: newKeyId }, ); - const as = t.withIdentity({ subject: `${fixture.userId}|session` }); + const as = await asUser(t, fixture.userId); // Keys saved under the old server key must be entered again. await expect(as.query(api.providerApiKeys.query.list, {})).resolves.toEqual( [expect.objectContaining({ serviceUnavailable: false, readable: false })], diff --git a/test/convex/users/authRedirect.test.ts b/test/convex/users/authRedirect.test.ts index 6f2523f..d413ec0 100644 --- a/test/convex/users/authRedirect.test.ts +++ b/test/convex/users/authRedirect.test.ts @@ -1,44 +1,26 @@ +import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { resolveAuthRedirect } from "../../../convex/_utils/authRedirect"; +import { + allowedSignInOrigins, + CLI_LOGIN_PORTS, +} from "../../../convex/_utils/authRedirect"; -const site = "https://gitdog.dev"; -const state = "a".repeat(64); -const callback = `http://127.0.0.1:54321/gitdog/callback?state=${state}`; - -describe("authentication redirect destinations", () => { - it("permits the CLI's exact state-bound loopback callback", () => { - expect(resolveAuthRedirect(callback, site)).toBe(callback); - }); - - it.each([ - "/tickets", - "?next=profile", - "https://gitdog.dev/repositories/connect", - ])("preserves web sign-in to %s", (target) => { - expect(new URL(resolveAuthRedirect(target, site)).origin).toBe(site); +describe("sign-in redirect origins", () => { + it("allows only the site's origin and the CLI's fixed loopback ports", () => { + expect(allowedSignInOrigins("https://gitdog.dev/some/path?x=1")).toEqual([ + "https://gitdog.dev", + ...CLI_LOGIN_PORTS.map((port) => `http://127.0.0.1:${port}`), + ]); }); - it.each([ - "https://evil.example/", - "https://gitdog.dev.evil.example/", - "//evil.example/", - "/\\evil.example/", - "https://attacker@gitdog.dev/", - "javascript:alert(1)", - `http://localhost:54321/gitdog/callback?state=${state}`, - `http://127.0.0.1.evil.example:54321/gitdog/callback?state=${state}`, - `http://127.0.0.2:54321/gitdog/callback?state=${state}`, - callback.replace(":54321", ":80"), - callback.replace(":54321", ":65536"), - callback.replace("/gitdog/callback", "/other"), - callback.replace("http:", "https:"), - callback.replace(state, "short"), - callback + "&next=https://evil.example", - callback + "#fragment", - callback + "\n", - callback + "\r\n", - callback.replace("127.0.0.1", "2130706433"), - ])("rejects unsafe destination %s", (target) => { - expect(() => resolveAuthRedirect(target, site)).toThrow(); + it("matches the ports the CLI listens on", () => { + const cli = readFileSync( + new URL("../../../packages/cli/src/auth.ts", import.meta.url), + "utf8", + ); + const listed = /LOGIN_CALLBACK_PORTS = \[([^\]]+)\]/.exec(cli)?.[1]; + expect(listed?.split(",").map((port) => Number(port.trim()))).toEqual([ + ...CLI_LOGIN_PORTS, + ]); }); }); diff --git a/test/convex/users/authV2.test.ts b/test/convex/users/authV2.test.ts new file mode 100644 index 0000000..e56c32d --- /dev/null +++ b/test/convex/users/authV2.test.ts @@ -0,0 +1,166 @@ +import { convexTest } from "convex-test"; +import { describe, expect, it } from "vitest"; +import { internal } from "../../../convex/_generated/api"; +import schema from "../../../convex/schema"; + +const modules = { + "../../../convex/_generated/api.ts": () => + import("../../../convex/_generated/api"), + "../../../convex/users/internalMutation.ts": () => + import("../../../convex/users/internalMutation"), + "../../../convex/users/migrations.ts": () => + import("../../../convex/users/migrations"), +}; + +const profile = (id: string, login = "octocat") => ({ + id, + login, + email: `${login}@example.com`, + emailVerified: true, + avatarUrl: `https://avatars.example/${login}`, +}); + +describe("GitHub sign-in user callbacks", () => { + it("creates one user per GitHub account and reuses a user from before 2.0", async () => { + const t = convexTest(schema, modules); + const existing = await t.run((ctx) => + ctx.db.insert("users", { name: "old", githubAccountId: "654" }), + ); + + const returning = await t.mutation( + internal.users.internalMutation.createUserFromGithub, + { method: { name: "github", profile: profile("654") } }, + ); + const newcomer = await t.mutation( + internal.users.internalMutation.createUserFromGithub, + { method: { name: "github", profile: profile("777", "newcomer") } }, + ); + + expect(returning).toBe(existing); + const users = await t.run((ctx) => ctx.db.query("users").collect()); + expect(users).toHaveLength(2); + expect(users.find((user) => user._id === newcomer)).toMatchObject({ + name: "newcomer", + githubAccountId: "777", + email: "newcomer@example.com", + image: "https://avatars.example/newcomer", + }); + }); + + it("refreshes the profile and refuses a different GitHub account", async () => { + const t = convexTest(schema, modules); + const userId = await t.run((ctx) => + ctx.db.insert("users", { name: "old", githubAccountId: "654" }), + ); + + await t.mutation(internal.users.internalMutation.updateUserFromGithub, { + method: { name: "github", profile: profile("654", "renamed") }, + userId, + }); + await expect( + t.mutation(internal.users.internalMutation.updateUserFromGithub, { + method: { name: "github", profile: profile("999", "attacker") }, + userId, + }), + ).rejects.toThrow("identity changed"); + + expect(await t.run((ctx) => ctx.db.get(userId))).toMatchObject({ + name: "renamed", + githubAccountId: "654", + }); + }); +}); + +describe("@convex-dev/auth 2.0 migration", () => { + it("keeps the account of someone who signs in before the migration runs", async () => { + const t = convexTest(schema, modules); + const userId = await t.run(async (ctx) => { + const userId = await ctx.db.insert("users", { name: "octocat" }); + await ctx.db.insert("authAccounts", { + userId, + provider: "github", + providerAccountId: "654", + }); + return userId; + }); + + const signedIn = await t.mutation( + internal.users.internalMutation.createUserFromGithub, + { method: { name: "github", profile: profile("654") } }, + ); + const migrated = await t.mutation( + internal.users.migrations.migrateToAuthV2, + {}, + ); + + expect(signedIn).toBe(userId); + expect(migrated).toMatchObject({ linkedUsers: 0, done: true }); + await expect( + t.run((ctx) => ctx.db.query("users").collect()), + ).resolves.toEqual([expect.objectContaining({ githubAccountId: "654" })]); + }); + + it("links each GitHub account to its user and deletes the old auth rows", async () => { + const t = convexTest(schema, modules); + const userId = await t.run(async (ctx) => { + const userId = await ctx.db.insert("users", { name: "octocat" }); + await ctx.db.insert("authAccounts", { + userId, + provider: "github", + providerAccountId: "654", + }); + const sessionId = await ctx.db.insert("authSessions", { + userId, + expirationTime: Date.now() + 1_000, + }); + await ctx.db.insert("authRefreshTokens", { + sessionId, + expirationTime: Date.now() + 1_000, + }); + return userId; + }); + + const first = await t.mutation( + internal.users.migrations.migrateToAuthV2, + {}, + ); + const again = await t.mutation( + internal.users.migrations.migrateToAuthV2, + {}, + ); + + expect(first).toEqual({ linkedUsers: 1, deletedRows: 3, done: true }); + expect(again).toEqual({ linkedUsers: 0, deletedRows: 0, done: true }); + expect((await t.run((ctx) => ctx.db.get(userId)))?.githubAccountId).toBe( + "654", + ); + for (const table of [ + "authAccounts", + "authSessions", + "authRefreshTokens", + ] as const) + await expect( + t.run((ctx) => ctx.db.query(table).collect()), + ).resolves.toEqual([]); + }); + + it("stops without deleting anything when a GitHub account is claimed twice", async () => { + const t = convexTest(schema, modules); + await t.run(async (ctx) => { + await ctx.db.insert("users", { githubAccountId: "654" }); + const other = await ctx.db.insert("users", {}); + await ctx.db.insert("authAccounts", { + userId: other, + provider: "github", + providerAccountId: "654", + }); + }); + + await expect( + t.mutation(internal.users.migrations.migrateToAuthV2, {}), + ).rejects.toThrow("conflicts"); + await expect( + t.run((ctx) => ctx.db.query("authAccounts").collect()), + ).resolves.toHaveLength(1); + }); +}); diff --git a/test/convex/users/legalAttestation.test.ts b/test/convex/users/legalAttestation.test.ts index 343ff8d..183e01a 100644 --- a/test/convex/users/legalAttestation.test.ts +++ b/test/convex/users/legalAttestation.test.ts @@ -23,6 +23,7 @@ import { guardAiProviderWithCurrentLegalAttestation, } from "../../../convex/_ai/legalAttestation"; import type { AiProvider } from "../../../convex/_ai/model"; +import { asUser } from "../../helpers/auth"; const noopGenerateChunkEmbeddings = internalAction({ args: { @@ -149,9 +150,7 @@ describe("user legal eligibility attestation", () => { const userId = await t.run(async (ctx) => ctx.db.insert("users", { name: "octocat" }), ); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.mutation(api.users.mutation.attestLegalEligibility, { @@ -172,9 +171,7 @@ describe("user legal eligibility attestation", () => { const userId = await t.run(async (ctx) => ctx.db.insert("users", { name: "octocat" }), ); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.mutation(api.users.mutation.attestLegalEligibility, { @@ -204,9 +201,7 @@ describe("user legal eligibility attestation", () => { const userId = await t.run(async (ctx) => ctx.db.insert("users", { name: "octocat" }), ); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.mutation(api.users.mutation.attestLegalEligibility, { @@ -233,9 +228,7 @@ describe("user legal eligibility attestation", () => { image: "https://avatars.example/octocat.png", }), ); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( t.query(internal.users.internalQuery.hasCurrentLegalAttestation, { @@ -339,9 +332,7 @@ describe("user legal eligibility attestation", () => { }); return userId; }); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await expect( authenticated.query(api.users.query.getCurrentUser, {}), @@ -384,12 +375,7 @@ describe("user legal eligibility attestation", () => { const insertAccount = async ( userId: Id<"users">, providerAccountId: string, - ) => - await ctx.db.insert("authAccounts", { - userId, - provider: "github", - providerAccountId, - }); + ) => await ctx.db.patch(userId, { githubAccountId: providerAccountId }); const currentUserId = await ctx.db.insert("users", {}); await insertAccount(currentUserId, "77"); @@ -528,9 +514,7 @@ describe("user legal eligibility attestation", () => { } return { userId, repositoryIds }; }); - const authenticated = t.withIdentity({ - subject: `${userId}|test-session`, - }); + const authenticated = await asUser(t, userId); await authenticated.mutation( api.users.mutation.attestLegalEligibility, diff --git a/test/convex/users/projectApiKeys.test.ts b/test/convex/users/projectApiKeys.test.ts index 88299ae..4c2025a 100644 --- a/test/convex/users/projectApiKeys.test.ts +++ b/test/convex/users/projectApiKeys.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { api, internal } from "../../../convex/_generated/api"; import schema from "../../../convex/schema"; import { hashApiKey } from "../../../convex/apiKeys/security"; +import { asUser } from "../../helpers/auth"; const modules = { "../../../convex/_generated/api.ts": () => @@ -108,8 +109,8 @@ async function fixture() { foreignTicketId, }; }); - const owner = t.withIdentity({ subject: ids.owner }); - const viewer = t.withIdentity({ subject: ids.viewer }); + const owner = await asUser(t, ids.owner); + const viewer = await asUser(t, ids.viewer); const create = (scopes: Array<"read" | "write"> = ["read"]) => owner.action(api.apiKeys.action.create, { repositoryId: ids.repositoryId, diff --git a/test/helpers/auth.ts b/test/helpers/auth.ts new file mode 100644 index 0000000..d4c5f2e --- /dev/null +++ b/test/helpers/auth.ts @@ -0,0 +1,39 @@ +import type { TestConvex } from "convex-test"; +import type { GenericSchema, SchemaDefinition } from "convex/server"; +import { registerCore, sessionIdentity } from "@convex-dev/auth/test"; +import { components } from "../../convex/_generated/api"; +import type { Id } from "../../convex/_generated/dataModel"; + +type AnyTestConvex = TestConvex>; + +const withCore = new WeakSet(); + +/** + * Call as `userId` through a real @convex-dev/auth session, as a signed-in + * client would: the access token's subject is a session in the core + * component, and getAuthUserId resolves the user through it. + */ +export async function asUser( + t: T, + userId: Id<"users">, +): Promise> { + // Convex Auth checks token issuers against the deployment's cloud URL. + process.env.CONVEX_CLOUD_URL ??= "https://gitdog-test.convex.cloud"; + if (!withCore.has(t)) { + registerCore(t); + withCore.add(t); + } + const tokens = await t.run(async (ctx) => + ctx.runMutation(components.auth.public._internal_dangerous_signIn, { + claims: { method: "github", profile: {} }, + componentPath: "authGithub", + userId, + accessTokenTtlSeconds: 60, + refreshInactivityTimeoutSeconds: 30 * 24 * 60 * 60, + sessionMaxLifetimeSeconds: 30 * 24 * 60 * 60, + }), + ); + return t.withIdentity(sessionIdentity(tokens)) as ReturnType< + T["withIdentity"] + >; +} diff --git a/test/pages/legalAgeCompliance.test.ts b/test/pages/legalAgeCompliance.test.ts index 66a57f9..51ce1ab 100644 --- a/test/pages/legalAgeCompliance.test.ts +++ b/test/pages/legalAgeCompliance.test.ts @@ -140,7 +140,7 @@ describe("legal age compliance", () => { for (const file of files) { const source = await readFile(file, "utf8"); - if (source.includes('signIn("github"')) { + if (source.includes("useSignInWithGithub(")) { directSignInFiles.push(file); } } diff --git a/test/pages/legalConsentPage.test.ts b/test/pages/legalConsentPage.test.ts index 23e3298..205cb30 100644 --- a/test/pages/legalConsentPage.test.ts +++ b/test/pages/legalConsentPage.test.ts @@ -20,10 +20,11 @@ vi.mock("convex/react", () => ({ })); vi.mock("@convex-dev/auth/react", () => ({ - useAuthActions: () => ({ - signIn: vi.fn(), - signOut: vi.fn(), - }), + useAuthActions: () => ({ signOut: vi.fn() }), +})); + +vi.mock("@convex-dev/auth/methods/github/react", () => ({ + useSignInWithGithub: () => ({ signIn: vi.fn() }), })); vi.mock("react-i18next", () => ({ From b99cd6cfa55ee40dc73a529e9b7f53ab8a06d9aa Mon Sep 17 00:00:00 2001 From: Hyo Date: Fri, 20 Nov 2026 22:29:59 +0900 Subject: [PATCH 2/2] docs: note where installation access is recorded after the auth 2.0 move --- convex/auth.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/convex/auth.ts b/convex/auth.ts index 5b087cc..f778636 100644 --- a/convex/auth.ts +++ b/convex/auth.ts @@ -15,6 +15,9 @@ const core = setupConvexAuth({ export const { signOut, refreshSession, isAuthenticated } = core; +// Sign-in never sees the GitHub user token in 2.0, so it records no +// installation access. "Verify GitHub access" (github/accessVerification.ts) +// does, whenever installation recovery reports reauth_required. export const { startSignInWithGithub, completeSignInWithGithub } = setupGithub( core, {