-
Notifications
You must be signed in to change notification settings - Fork 1
fix(auth): require authenticated access across browser and HTTP #241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
brianorwhatever
wants to merge
4
commits into
main
Choose a base branch
from
codex/authenticated-boundary
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,963
−1,353
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
7c904d1
fix(auth): require verified credentials for browser and HTTP operations
brianorwhatever afb3e6f
fix(auth): address review recovery and rollout gaps
brianorwhatever 99e995f
fix(auth): isolate denied offline edits and conceal resource existence
brianorwhatever 0425318
fix(auth): finish resource denial and retry consistency
brianorwhatever File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,26 +1,24 @@ | ||
| import { httpAction } from "./_generated/server"; | ||
| import { api } from "./_generated/api"; | ||
| import { internal } from "./_generated/api"; | ||
| import type { Id } from "./_generated/dataModel"; | ||
| import { AuthError, unauthorizedResponseWithCors } from "./lib/auth"; | ||
| import { requireAuthenticatedUser } from "./lib/authUser"; | ||
| import { jsonResponse, errorResponse } from "./lib/httpResponses"; | ||
| import { authenticatedRequest } from "./lib/actor"; | ||
| import { jsonResponse, errorResponse, handlerErrorResponse } from "./lib/httpResponses"; | ||
|
|
||
| export const getListActivity = httpAction(async (ctx, request) => { | ||
| try { | ||
| await requireAuthenticatedUser(ctx, request); | ||
| const body = await request.json(); | ||
| const { listId, limit } = body as { listId: string; limit?: number }; | ||
| if (!listId) return errorResponse(request, "listId is required"); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| const activities = await ctx.runQuery((api as any).activity.getListActivity, { | ||
| const activities = await ctx.runQuery(internal.activity.getListActivityInternal, { | ||
| ...await authenticatedRequest(ctx, request), | ||
| listId: listId as Id<"lists">, | ||
| limit, | ||
| }); | ||
|
|
||
| return jsonResponse(request, { activities }); | ||
| } catch (error) { | ||
| if (error instanceof AuthError) return unauthorizedResponseWithCors(request, error.message); | ||
| return errorResponse(request, error instanceof Error ? error.message : "Failed to get activity", 500); | ||
| return handlerErrorResponse(request, error, "Failed to get activity"); | ||
| } | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { authorizeResources } from "./lib/permissions"; | ||
| import { requireSession } from "./lib/session"; | ||
| import { v } from "convex/values"; | ||
| import { internalQuery, internalMutation, mutation } from "./_generated/server"; | ||
| import { internal } from "./_generated/api"; | ||
| import { authenticate, type ResolvedActor } from "./lib/actor"; | ||
| import { verifyAuthToken } from "./lib/jwt"; | ||
| import { hashApiKey } from "./lib/apiKeyHelpers"; | ||
| import { AuthError } from "./lib/auth"; | ||
|
|
||
| export const resolve = internalQuery({ | ||
| args: { authToken: v.optional(v.string()), apiKey: v.optional(v.string()) }, | ||
| handler: (ctx, args): Promise<ResolvedActor> => authenticate(ctx, args), | ||
| }); | ||
|
|
||
| // Establishing a record proves possession of a signed session, never a DID. | ||
| const establishOperation = { | ||
| args: { authToken: v.string() }, | ||
| handler: async (ctx: import("./_generated/server").MutationCtx, args: { authToken: string }) => { | ||
| const session = await verifyAuthToken(args.authToken).catch(() => { | ||
| throw new AuthError("Invalid or expired token", "INVALID_TOKEN"); | ||
| }); | ||
| const tokenHash = await hashApiKey(args.authToken); | ||
| const existing = await ctx.db.query("accessSessions").withIndex("by_hash", q => q.eq("tokenHash", tokenHash)).first(); | ||
| if (existing) { | ||
| if (existing.revokedAt !== undefined) throw new AuthError("Invalid or expired token", "INVALID_TOKEN"); | ||
| return; | ||
| } | ||
| const user = await ctx.db.query("users").withIndex("by_turnkey_id", q => q.eq("turnkeySubOrgId", session.turnkeySubOrgId)).first(); | ||
| if (!user) throw new AuthError("User not found", "UNAUTHORIZED"); | ||
| const id = await ctx.db.insert("accessSessions", { tokenHash, subject: session.turnkeySubOrgId, expiresAt: session.expiresAt }); | ||
| await ctx.scheduler.runAt(session.expiresAt, internal.actorSession.expire, { id }); | ||
| }, | ||
| }; | ||
| export const establish = mutation(establishOperation); | ||
| export const establishInternal = internalMutation(establishOperation); | ||
| export const expire = internalMutation({ | ||
| args: { id: v.id("accessSessions") }, | ||
| handler: async (ctx, { id }) => { | ||
| const record = await ctx.db.get(id); | ||
| if (record && record.expiresAt <= Date.now()) await ctx.db.delete(id); | ||
| }, | ||
| }); | ||
|
|
||
| // Recover records whose individual expiry callback did not complete. Revoked | ||
| // records remain until token expiry so they cannot be established again. | ||
| export const cleanupExpiredSessions = internalMutation({ | ||
| args: {}, | ||
| handler: async (ctx) => { | ||
| const expired = await ctx.db | ||
| .query("accessSessions") | ||
| .withIndex("by_expires_at", q => q.lte("expiresAt", Date.now())) | ||
| .take(100); | ||
| for (const session of expired) await ctx.db.delete(session._id); | ||
| return expired.length; | ||
| }, | ||
| }); | ||
|
|
||
| const revokeOperation = { | ||
| args: { authToken: v.string() }, | ||
| handler: async (ctx: import("./_generated/server").MutationCtx, args: { authToken: string }) => { | ||
| const tokenHash = await hashApiKey(args.authToken); | ||
| const record = await ctx.db.query("accessSessions").withIndex("by_hash", q => q.eq("tokenHash", tokenHash)).first(); | ||
| if (record) { | ||
| await ctx.db.patch(record._id, { revokedAt: Date.now() }); | ||
| } else { | ||
| // A pre-rollout JWT can be logged out before its first authenticated call. | ||
| const session = await verifyAuthToken(args.authToken); | ||
| const id = await ctx.db.insert("accessSessions", { tokenHash, subject: session.turnkeySubOrgId, expiresAt: session.expiresAt, revokedAt: Date.now() }); | ||
| await ctx.scheduler.runAt(session.expiresAt, internal.actorSession.expire, { id }); | ||
| } | ||
| }, | ||
| }; | ||
| export const revoke = mutation(revokeOperation); | ||
| export const revokeInternal = internalMutation(revokeOperation); | ||
|
|
||
| export const identity = internalQuery({ | ||
| args: { authToken: v.string() }, | ||
| handler: (ctx, args) => requireSession(ctx, args.authToken), | ||
| }); | ||
|
|
||
| export const authorize = internalQuery({ | ||
| args: { | ||
| authToken: v.optional(v.string()), apiKey: v.optional(v.string()), | ||
| resources: v.object({ | ||
| lists: v.optional(v.array(v.union(v.id("lists"), v.null()))), | ||
| items: v.optional(v.array(v.union(v.id("items"), v.null()))), | ||
| anchors: v.optional(v.array(v.union(v.id("bitcoinAnchors"), v.null()))), | ||
| accounts: v.optional(v.array(v.union(v.id("users"), v.null()))), | ||
| }), | ||
| }, | ||
| handler: async (ctx, args): Promise<void> => { | ||
| const actor = await authenticate(ctx, args); | ||
| await authorizeResources(ctx, actor, { | ||
| lists: args.resources.lists?.filter(id => id !== null), | ||
| items: args.resources.items?.filter(id => id !== null), | ||
| anchors: args.resources.anchors?.filter(id => id !== null), | ||
| accounts: args.resources.accounts?.filter(id => id !== null), | ||
| }); | ||
| }, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.