⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(security): protect workspace ownership and update vulnerable dependencies
Tin Sever88ce2d0a3495
diff --git a/.github/workflows/android.yml b/.github/workflows/android.ymlindex ae6d925c2..8bbe520da 100644--- a/.github/workflows/android.yml+++ b/.github/workflows/android.yml@@ -36,7 +36,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- name: Install dependenciesdiff --git a/.github/workflows/browserstack.yml b/.github/workflows/browserstack.ymlindex ecebb727d..ef18e221c 100644--- a/.github/workflows/browserstack.yml+++ b/.github/workflows/browserstack.yml@@ -30,7 +30,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Classify BrowserStack changesid: classifydiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 621fb7dae..49a2f1fa4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -29,7 +29,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- id: classifyname: Classify complete pull request diff@@ -54,7 +54,7 @@ jobs:version: 12.15.0- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- run: pnpm --dir tests/e2e install --frozen-lockfile --ignore-scripts@@ -107,7 +107,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- run: npm ci --ignore-scriptsworking-directory: scripts/ui-review-bot@@ -123,7 +123,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- run: npm ci --ignore-scripts --no-audit --no-fundworking-directory: scripts/slop-labeler@@ -147,7 +147,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- id: install@@ -190,7 +190,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- name: Install dependencies@@ -222,7 +222,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- name: Install dependencies@@ -276,7 +276,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- name: Install dependencies@@ -315,7 +315,7 @@ jobs:version: 12.15.0- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- run: pnpm install --frozen-lockfile --ignore-scripts --filter @kaneo/api...- run: npm ci --ignore-scripts@@ -408,7 +408,7 @@ jobs:version: 12.15.0- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- run: pnpm install --frozen-lockfile- name: Start disposable S3 storage@@ -560,7 +560,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Reject failed, cancelled, and unexpected skipped checksenv:diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.ymlindex 02b3c51e8..b8c3cbc00 100644--- a/.github/workflows/code-review.yml+++ b/.github/workflows/code-review.yml@@ -32,7 +32,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- id: requestenv:@@ -56,7 +56,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- run: npm --prefix scripts/ui-review-bot ci --ignore-scripts- name: Read PR source and review changed behaviordiff --git a/.github/workflows/contribution-eligibility.yml b/.github/workflows/contribution-eligibility.ymlindex 895550a75..1c540e195 100644--- a/.github/workflows/contribution-eligibility.yml+++ b/.github/workflows/contribution-eligibility.yml@@ -58,7 +58,7 @@ jobs:- name: Set up Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Check open pull requestsdiff --git a/.github/workflows/dependency-graph.yml b/.github/workflows/dependency-graph.ymlnew file mode 100644index 000000000..db426b81d--- /dev/null+++ b/.github/workflows/dependency-graph.yml@@ -0,0 +1,40 @@+name: Dependency graph++on:+ push:+ branches: [main]+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: dependency-graph-main+ cancel-in-progress: false++jobs:+ submit:+ if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')+ runs-on: blacksmith-4vcpu-ubuntu-2404+ timeout-minutes: 15+ permissions:+ contents: write+ steps:+ - uses: useblacksmith/checkout@25227e61ff9dafe400e22fa487b673eac4e4409a # v1+ with:+ persist-credentials: false+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0+ with:+ version: 12.15.0+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7+ with:+ node-version: 24.22.2+ package-manager-cache: false+ - name: Install submission dependencies without lifecycle scripts+ run: pnpm install --filter . --frozen-lockfile --ignore-scripts+ - name: Check dependency snapshot construction+ run: node --test scripts/ci/dependency-graph*.test.mjs+ - name: Submit both dependency graphs for this commit+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: node scripts/ci/dependency-graph.mjs --submitdiff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.ymlindex 92d9a3cf0..7b355d509 100644--- a/.github/workflows/deploy-site.yml+++ b/.github/workflows/deploy-site.yml@@ -34,7 +34,7 @@ jobs:- name: Setup Nodeuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: "24.22.1"+ node-version: "24.22.2"- name: Setup pnpmuses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0diff --git a/.github/workflows/issue-priority.yml b/.github/workflows/issue-priority.ymlindex b2fef0e58..349a4d784 100644--- a/.github/workflows/issue-priority.yml+++ b/.github/workflows/issue-priority.yml@@ -22,7 +22,7 @@ jobs:- name: Set up Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Rank and label issuediff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.ymlindex b8edbd9db..8b1450ab6 100644--- a/.github/workflows/pr-title.yml+++ b/.github/workflows/pr-title.yml@@ -24,7 +24,7 @@ jobs:- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- run: pnpm install --frozen-lockfile --ignore-scripts --filter kaneo- name: Validate Conventional Commit titlediff --git a/.github/workflows/publish-mcp.yml b/.github/workflows/publish-mcp.ymlindex db4f80bdc..b675e405f 100644--- a/.github/workflows/publish-mcp.yml+++ b/.github/workflows/publish-mcp.yml@@ -52,7 +52,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2# Publish workflows must not read cache content that a pull# request could have poisoned (zizmor cache-poisoning).package-manager-cache: falsediff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 08addaac8..bc9e23014 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -58,7 +58,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- name: Install dependencies@@ -110,7 +110,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Wait for successful main CI on this exact commitenv:@@ -172,7 +172,7 @@ jobs:- name: Setup Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2cache: pnpm- name: Install dependenciesdiff --git a/.github/workflows/slop-labeler.yml b/.github/workflows/slop-labeler.ymlindex 8003c86b8..bac2e52bf 100644--- a/.github/workflows/slop-labeler.yml+++ b/.github/workflows/slop-labeler.yml@@ -38,7 +38,7 @@ jobs:- name: Set up Node.jsuses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Install trusted scanner dependenciesdiff --git a/.github/workflows/ui-review-run.yml b/.github/workflows/ui-review-run.ymlindex fdac18875..6836477dc 100644--- a/.github/workflows/ui-review-run.yml+++ b/.github/workflows/ui-review-run.yml@@ -33,7 +33,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- run: npm --prefix scripts/ui-review-bot ci --ignore-scripts- name: Plan scenarios from PR text (no PR code execution)@@ -66,7 +66,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0with:@@ -101,7 +101,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- run: npm --prefix scripts/ui-review-bot ci --ignore-scripts- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2diff --git a/.github/workflows/ui-review.yml b/.github/workflows/ui-review.ymlindex 1b794d997..a4deffb28 100644--- a/.github/workflows/ui-review.yml+++ b/.github/workflows/ui-review.yml@@ -39,7 +39,7 @@ jobs:persist-credentials: false- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7with:- node-version: 24.22.1+ node-version: 24.22.2package-manager-cache: false- name: Verify command and current repository permissionsid: requestdiff --git a/Dockerfile.kaneo b/Dockerfile.kaneoindex f85832d9a..ebea65b0e 100644--- a/Dockerfile.kaneo+++ b/Dockerfile.kaneo@@ -1,4 +1,4 @@-FROM --platform=$BUILDPLATFORM node:24.22.1-alpine AS api-builder+FROM --platform=$BUILDPLATFORM node:24.22.2-alpine AS api-builderRUN apk add --no-cache python3 make g++ && \corepack enable && \@@ -42,7 +42,7 @@ RUN pnpm run build# Assembles the production node_modules on the BUILD platform (native, no QEMU emulation).# All API runtime deps are pure JavaScript (bcrypt was replaced with bcryptjs), so this# node_modules is architecture-independent and is copied into the runtime stage below.-FROM --platform=$BUILDPLATFORM node:24.22.1-alpine AS api-runtime+FROM --platform=$BUILDPLATFORM node:24.22.2-alpine AS api-runtimeWORKDIR /app@@ -68,7 +68,7 @@ COPY --from=api-builder /app/packages/permissions ./packages/permissionsCOPY --from=api-builder /app/packages/importers/dist ./packages/importers/distCOPY --from=api-builder /app/packages/mcp/dist ./packages/mcp/dist-FROM --platform=$BUILDPLATFORM node:24.22.1-alpine AS web-builder+FROM --platform=$BUILDPLATFORM node:24.22.2-alpine AS web-builderRUN apk add --no-cache python3 make g++ && \corepack enable && \@@ -99,7 +99,7 @@ RUN pnpm run buildWORKDIR /app/apps/webRUN pnpm run build && find dist -type f -name '*.map' -delete-FROM node:24.22.1-alpine AS runtime+FROM node:24.22.2-alpine AS runtime# Alpine replaces older package patches, so accept later security fixes too.RUN apk add --no-cache 'nginx>=1.30.6' && \diff --git a/apps/api/Dockerfile b/apps/api/Dockerfileindex 10a4b6415..6090f7eae 100644--- a/apps/api/Dockerfile+++ b/apps/api/Dockerfile@@ -1,5 +1,5 @@# Build stage-FROM --platform=$BUILDPLATFORM node:24.22.1-alpine AS builder+FROM --platform=$BUILDPLATFORM node:24.22.2-alpine AS builder# Install build dependencies in a single layerRUN apk add --no-cache python3 make g++ && \@@ -52,7 +52,7 @@ RUN sed -i 's/"extends": "@kaneo\/typescript-config\/base.json"/"extends": "..\/# Production dependencies stage - runs on the BUILD platform (native, no QEMU emulation).# All API runtime deps are pure JavaScript (bcrypt was replaced with bcryptjs), so the# resulting node_modules is architecture-independent and safe to copy into the arm64 runtime.-FROM --platform=$BUILDPLATFORM node:24.22.1-alpine AS prod-deps+FROM --platform=$BUILDPLATFORM node:24.22.2-alpine AS prod-depsRUN corepack enable && corepack prepare [email protected] --activate@@ -72,7 +72,7 @@ RUN sed -i 's/"prepare": "husky"/"prepare": ""/g' package.json && \HUSKY=0 NODE_ENV=production pnpm install --prod --frozen-lockfile --no-optional# Production stage - use specific version tag without SHA256-FROM node:24.22.1-alpine AS runtime+FROM node:24.22.2-alpine AS runtime# Set up user in a single layerRUN addgroup -g 1001 appuser && \diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 3f73f71b5..1c9ae028e 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -72,6 +72,10 @@ import { publishMemberProjects } from "./project-access/publish-member-projects"import { handleMemberAdded } from "./workspace-members/handle-member-added";import { handleMemberRemoved } from "./workspace-members/handle-member-removed";import { handleOwnerPromoted } from "./workspace-members/handle-owner-promoted";+import { assertInvitationOwnerAllowed } from "./workspace-members/assert-invitation-owner-allowed";+import { assertStoredOwnerRoleSafe } from "./workspace-members/assert-stored-owner-role-safe";+import { assertNativeOwnerRoleSafe } from "./workspace-members/assert-native-owner-role-safe";+import { normalizeInvitationRole } from "./workspace-members/normalize-invitation-role";import { hideInaccessibleInvitationProjects } from "./project-access/hide-inaccessible-invitation-projects";import assertManagedProfileUnchanged from "./user/controllers/assert-managed-profile-unchanged";import { hideInvitationsFromNonInviters } from "./utils/hide-invitations-from-non-inviters";@@ -620,10 +624,16 @@ export const auth = betterAuth({});},beforeCreateInvitation: async ({ invitation }) => {- const access = await resolveInvitationProjectAccess(invitation);- return { data: access };+ const role = normalizeInvitationRole(invitation.role) ?? invitation.role;+ await assertInvitationOwnerAllowed({ ...invitation, role });+ const access = await resolveInvitationProjectAccess({+ ...invitation,+ role,+ });+ return { data: { ...access, role } };},beforeAcceptInvitation: async ({ invitation, user }) => {+ assertStoredOwnerRoleSafe(invitation.role);await applyInvitationProjectAccess(invitation, user.id);},afterAcceptInvitation: async ({ member }) => {@@ -931,7 +941,29 @@ export const auth = betterAuth({await prepareAdminUserRemoval(ctx);}+ if (+ ctx.path === "/organization/invite-member" ||+ ctx.path === "/organization/remove-member"+ ) {+ const workspaceId =+ ctx.body?.organizationId ||+ organizationViewer?.session.activeOrganizationId;+ if (organizationViewer && typeof workspaceId === "string") {+ await assertNativeOwnerRoleSafe(+ organizationViewer.user.id,+ workspaceId,+ );+ }+ }+if (ctx.path === "/organization/invite-member") {+ // This hook runs before validation. Normalize only valid role shapes,+ // including arrays; the provider still validates role names and auth.+ // Resends bypass beforeCreateInvitation and must pass this check too.+ const role = normalizeInvitationRole(ctx.body?.role);+ if (role !== undefined && ctx.body) {+ ctx.body.role = role;+ }if (ctx.body?.resend === true && typeof ctx.body.email === "string") {const viewer = organizationViewer;const workspaceId =diff --git a/apps/api/src/user/account-deletion.ts b/apps/api/src/user/account-deletion.tsindex 036d64ff3..38fa40ac4 100644--- a/apps/api/src/user/account-deletion.ts+++ b/apps/api/src/user/account-deletion.ts@@ -1,3 +1,5 @@+import { isOwnerRole } from "../project-access/is-owner-role";+export type WorkspaceMembershipSummary = {workspaceId: string;workspaceName: string;@@ -13,10 +15,7 @@ export type AccountDeletionPlan = {};export function hasOwnerRole(role: string) {- return role- .split(",")- .map((entry) => entry.trim().toLowerCase())- .includes("owner");+ return isOwnerRole(role);}export function planAccountDeletion(diff --git a/apps/api/src/utils/assert-owner-invitation-resend-allowed.ts b/apps/api/src/utils/assert-owner-invitation-resend-allowed.tsindex 9c13267ea..c7e600e49 100644--- a/apps/api/src/utils/assert-owner-invitation-resend-allowed.ts+++ b/apps/api/src/utils/assert-owner-invitation-resend-allowed.ts@@ -1,8 +1,10 @@import { APIError } from "better-auth/api";-import { and, eq } from "drizzle-orm";+import { and, eq, gt } from "drizzle-orm";import db, { schema } from "../database";+import { isOwnerRole } from "../project-access/is-owner-role";+import { assertStoredOwnerRoleSafe } from "../workspace-members/assert-stored-owner-role-safe";+import { normalizeInvitationRole } from "../workspace-members/normalize-invitation-role";import { roleHasWorkspacePermission } from "./require-workspace-permission";-import { splitRoles } from "./split-roles";export async function assertOwnerInvitationResendAllowed(userId: string,@@ -20,8 +22,10 @@ export async function assertOwnerInvitationResendAllowed().limit(1);// Let the provider report its normal membership/permission failures.- if (!member || splitRoles(member.role).includes("owner")) return;+ if (!member) return;+ const owner = isOwnerRole(member.role);if (+ !owner &&!(await roleHasWorkspacePermission(workspaceId, member.role, {invitation: ["create"],}))@@ -36,11 +40,18 @@ export async function assertOwnerInvitationResendAllowed(eq(schema.invitationTable.workspaceId, workspaceId),eq(schema.invitationTable.email, email.toLowerCase()),eq(schema.invitationTable.status, "pending"),+ gt(schema.invitationTable.expiresAt, new Date()),),);+ for (const invitation of invitations) {+ // A resend updates expiry before email and skips the creation hook. Old+ // ambiguous owner invitations require review, even when resent by owners.+ assertStoredOwnerRoleSafe(invitation.role);+ }if (+ !owner &&invitations.some((invitation) =>- splitRoles(invitation.role).includes("owner"),+ isOwnerRole(normalizeInvitationRole(invitation.role)),)) {throw new APIError("FORBIDDEN", {diff --git a/apps/api/src/utils/hide-invitations-from-non-inviters.ts b/apps/api/src/utils/hide-invitations-from-non-inviters.tsindex 3340876b1..94077c4be 100644--- a/apps/api/src/utils/hide-invitations-from-non-inviters.ts+++ b/apps/api/src/utils/hide-invitations-from-non-inviters.ts@@ -1,8 +1,9 @@import { and, eq } from "drizzle-orm";import db, { schema } from "../database";+import { isOwnerRole } from "../project-access/is-owner-role";+import { normalizeInvitationRole } from "../workspace-members/normalize-invitation-role";import { hasInstanceAdminRole } from "./instance-admin-role";import { roleHasWorkspacePermission } from "./require-workspace-permission";-import { splitRoles } from "./split-roles";export async function hideInvitationsFromNonInviters(viewer: { id: string; role?: string | null },@@ -33,7 +34,7 @@ export async function hideInvitationsFromNonInviters(invitation: ["create"],}): false,- owner: splitRoles(member?.role).includes("owner"),+ owner: isOwnerRole(member?.role),});}@@ -45,7 +46,7 @@ export async function hideInvitationsFromNonInviters(return (access?.canInvite &&typeof invitation?.role === "string" &&- (access.owner || !splitRoles(invitation.role).includes("owner"))+ (access.owner || !isOwnerRole(normalizeInvitationRole(invitation.role))));});invitations.splice(0, invitations.length, ...visible);diff --git a/apps/api/src/utils/split-roles.test.ts b/apps/api/src/utils/split-roles.test.tsindex 19acaaf99..cfd37dd63 100644--- a/apps/api/src/utils/split-roles.test.ts+++ b/apps/api/src/utils/split-roles.test.ts@@ -11,7 +11,22 @@ describe("splitRoles", () => {});it("trims names and drops empty and repeated entries", () => {- expect(splitRoles(" owner , ,viewer,owner,")).toEqual(["owner", "viewer"]);+ expect(splitRoles(" member , ,viewer,member,")).toEqual([+ "member",+ "viewer",+ ]);+ });++ it("never grants ownership by trimming a stored token", () => {+ for (const role of [+ " owner",+ "owner ",+ "member, owner",+ "member,\towner\n",+ ]) {+ expect(splitRoles(role)).not.toContain("owner");+ }+ expect(splitRoles("member, owner,owner")).toEqual(["member", "owner"]);});it("returns an empty list for a missing or blank role", () => {diff --git a/apps/api/src/utils/split-roles.ts b/apps/api/src/utils/split-roles.tsindex 2c0de206a..9d6c6808b 100644--- a/apps/api/src/utils/split-roles.ts+++ b/apps/api/src/utils/split-roles.ts@@ -2,6 +2,9 @@ export function splitRoles(role: string | null | undefined): string[] {if (typeof role !== "string") return [];const names = role.split(",")+ // Stored owner grants must agree with the provider and project access.+ // Never turn a legacy padded token into a new ownership grant on read.+ .filter((name) => name.trim() !== "owner" || name === "owner").map((name) => name.trim()).filter(Boolean);return [...new Set(names)];diff --git a/apps/api/src/workspace-members/assert-invitation-owner-allowed.ts b/apps/api/src/workspace-members/assert-invitation-owner-allowed.tsnew file mode 100644index 000000000..e0ce9fd15--- /dev/null+++ b/apps/api/src/workspace-members/assert-invitation-owner-allowed.ts@@ -0,0 +1,29 @@+import { APIError } from "better-auth/api";+import { and, eq } from "drizzle-orm";+import db, { schema } from "../database";+import { isOwnerRole } from "../project-access/is-owner-role";+import { normalizeInvitationRole } from "./normalize-invitation-role";++export async function assertInvitationOwnerAllowed(invitation: {+ role: string;+ organizationId: string;+ inviterId: string;+}) {+ if (!isOwnerRole(normalizeInvitationRole(invitation.role))) return;+ const [inviter] = await db+ .select({ role: schema.workspaceUserTable.role })+ .from(schema.workspaceUserTable)+ .where(+ and(+ eq(schema.workspaceUserTable.workspaceId, invitation.organizationId),+ eq(schema.workspaceUserTable.userId, invitation.inviterId),+ ),+ )+ .limit(1);+ if (!isOwnerRole(inviter?.role)) {+ throw new APIError("FORBIDDEN", {+ code: "YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE",+ message: "Only workspace owners can invite owners.",+ });+ }+}diff --git a/apps/api/src/workspace-members/assert-native-owner-role-safe.ts b/apps/api/src/workspace-members/assert-native-owner-role-safe.tsnew file mode 100644index 000000000..b13915d82--- /dev/null+++ b/apps/api/src/workspace-members/assert-native-owner-role-safe.ts@@ -0,0 +1,23 @@+import { and, eq } from "drizzle-orm";+import db, { schema } from "../database";+import { assertStoredOwnerRoleSafe } from "./assert-stored-owner-role-safe";++export async function assertNativeOwnerRoleSafe(+ userId: string,+ workspaceId: string,+) {+ const [member] = await db+ .select({ role: schema.workspaceUserTable.role })+ .from(schema.workspaceUserTable)+ .where(+ and(+ eq(schema.workspaceUserTable.workspaceId, workspaceId),+ eq(schema.workspaceUserTable.userId, userId),+ ),+ )+ .limit(1);+ // The provider trims the actor's owner token on invitation and removal,+ // unlike its other authorization checks. Quarantine those legacy grants+ // without changing stored membership or granting canonical ownership.+ if (member) assertStoredOwnerRoleSafe(member.role);+}diff --git a/apps/api/src/workspace-members/assert-stored-owner-role-safe.test.ts b/apps/api/src/workspace-members/assert-stored-owner-role-safe.test.tsnew file mode 100644index 000000000..f2527298c--- /dev/null+++ b/apps/api/src/workspace-members/assert-stored-owner-role-safe.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vite-plus/test";+import { assertStoredOwnerRoleSafe } from "./assert-stored-owner-role-safe";++describe("stored ownership review", () => {+ it.each(["owner ", " owner", "member, owner", "member,\towner\n"])(+ "requires review instead of promoting %j on read",+ (role) => {+ expect(() => assertStoredOwnerRoleSafe(role)).toThrow();+ },+ );++ it.each([+ null, undefined, "member", "member, recruiter", "owner", "member,owner", "owner, owner",+ ])(+ "preserves roles with no ambiguous ownership grant (%j)",+ (role) => {+ expect(() => assertStoredOwnerRoleSafe(role)).not.toThrow();+ },+ );+});diff --git a/apps/api/src/workspace-members/assert-stored-owner-role-safe.ts b/apps/api/src/workspace-members/assert-stored-owner-role-safe.tsnew file mode 100644index 000000000..8f065a915--- /dev/null+++ b/apps/api/src/workspace-members/assert-stored-owner-role-safe.ts@@ -0,0 +1,12 @@+import { APIError } from "better-auth/api";+import { isOwnerRole } from "../project-access/is-owner-role";+import { normalizeInvitationRole } from "./normalize-invitation-role";++export function assertStoredOwnerRoleSafe(role: string | null | undefined) {+ if (isOwnerRole(normalizeInvitationRole(role)) && !isOwnerRole(role)) {+ throw new APIError("FORBIDDEN", {+ code: "OWNER_ROLE_REVIEW_REQUIRED",+ message: "A workspace owner must review this role before it can be used.",+ });+ }+}diff --git a/apps/api/src/workspace-members/normalize-invitation-role.test.ts b/apps/api/src/workspace-members/normalize-invitation-role.test.tsnew file mode 100644index 000000000..a08fdd3b7--- /dev/null+++ b/apps/api/src/workspace-members/normalize-invitation-role.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vite-plus/test";+import { normalizeInvitationRole } from "./normalize-invitation-role";++describe("invitation role normalization", () => {+ it.each([+ [" member, owner ", "member,owner"],+ [["member", "\towner\n"], "member,owner"],+ [["member, owner", "member"], "member,owner"],+ [" member , recruiter,member,,", "member,recruiter"],+ ])("normalizes valid provider role shapes (%j)", (input, expected) => {+ expect(normalizeInvitationRole(input)).toBe(expected);+ });++ it.each(+ [null, undefined, 1, {}, ["member", 1], [["owner"]]].map((role) => ({+ role,+ })),+ )("leaves invalid shapes for provider validation ($role)", ({ role }) => {+ expect(normalizeInvitationRole(role)).toBeUndefined();+ });+});diff --git a/apps/api/src/workspace-members/normalize-invitation-role.ts b/apps/api/src/workspace-members/normalize-invitation-role.tsnew file mode 100644index 000000000..ad5430a1f--- /dev/null+++ b/apps/api/src/workspace-members/normalize-invitation-role.ts@@ -0,0 +1,18 @@+// Request roles need normalization before either provider owner checks or+// project access checks. Invalid shapes remain for the provider to reject.+export function normalizeInvitationRole(role: unknown): string | undefined {+ if (+ typeof role !== "string" &&+ !(Array.isArray(role) && role.every((name) => typeof name === "string"))+ ) {+ return undefined;+ }+ const roles: string[] = typeof role === "string" ? [role] : role;+ return [+ ...new Set(+ roles+ .flatMap((name) => name.split(",").map((token) => token.trim()))+ .filter(Boolean),+ ),+ ].join(",");+}diff --git a/apps/web/Dockerfile b/apps/web/Dockerfileindex 9cfd44e34..f5211306c 100644--- a/apps/web/Dockerfile+++ b/apps/web/Dockerfile@@ -1,6 +1,6 @@# syntax=docker/dockerfile:1# Build stage-FROM --platform=$BUILDPLATFORM node:24.22.1-alpine AS builder+FROM --platform=$BUILDPLATFORM node:24.22.2-alpine AS builder# Sentry org/project are public identifiers (not secrets). The auth token# is the only real secret; it is mounted via `--mount=type=secret` duringdiff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 000000000..72a4adc08--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,57 @@+diff --git a/index.js b/index.js+--- a/index.js++++ b/index.js+@@ -46,6 +46,7 @@++ // Protects from prototype poisoning and unexpected merging up the prototype chain.+ function propertyIsUnsafe(target, key) {++ if (key === '__proto__') return true+ return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,+ && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,+ && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.+@@ -55,6 +56,7 @@+ var destination = {}+ if (options.isMergeableObject(target)) {+ getKeys(target).forEach(function(key) {++ if (key === '__proto__') return+ destination[key] = cloneUnlessOtherwiseSpecified(target[key], options)+ })+ }+diff --git a/dist/cjs.js b/dist/cjs.js+--- a/dist/cjs.js++++ b/dist/cjs.js+@@ -71,6 +71,7 @@++ // Protects from prototype poisoning and unexpected merging up the prototype chain.+ function propertyIsUnsafe(target, key) {++ if (key === '__proto__') return true+ return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,+ && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,+ && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.+@@ -80,6 +81,7 @@+ var destination = {};+ if (options.isMergeableObject(target)) {+ getKeys(target).forEach(function(key) {++ if (key === '__proto__') return+ destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);+ });+ }+diff --git a/dist/umd.js b/dist/umd.js+--- a/dist/umd.js++++ b/dist/umd.js+@@ -75,6 +75,7 @@++ // Protects from prototype poisoning and unexpected merging up the prototype chain.+ function propertyIsUnsafe(target, key) {++ if (key === '__proto__') return true+ return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,+ && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,+ && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.+@@ -84,6 +85,7 @@+ var destination = {};+ if (options.isMergeableObject(target)) {+ getKeys(target).forEach(function(key) {++ if (key === '__proto__') return+ destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);+ });+ }diff --git a/patches/[email protected] b/patches/[email protected]deleted file mode 100644index 4e1eb7c64..000000000--- a/patches/[email protected]+++ /dev/null@@ -1,23 +0,0 @@-diff --git a/lib/rsa.js b/lib/rsa.js-index a4264822b..430905451 100644---- a/lib/rsa.js-+++ b/lib/rsa.js-@@ -1168,11 +1168,16 @@ pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) {- parseAllBytes: options._parseAllDigestBytes- });--- // validate DigestInfo structure and element count-+ // validate DigestInfo structure and element counts (outer DigestInfo-+ // and nested DigestAlgorithm). asn1.validate ignores extra children,-+ // so length must be checked explicitly at each nesting level to-+ // prevent low-exponent PKCS#1 v1.5 signature forgery (CVE-2026-85393).- var capture = {};- var errors = [];- if(!asn1.validate(obj, digestInfoValidator, capture, errors) ||-- obj.value.length !== 2) {-+ obj.value.length !== 2 ||-+ obj.value[0].value.length !==-+ (('parameters' in capture) ? 2 : 1)) {- var error = new Error(- 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +- 'DigestInfo value.');diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 436e3f9b6..32881a3be 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -187,9 +187,11 @@ overrides:hono: '>=4.13.14 <5'lodash: 4.18.1markdown-it: 15.0.3- minimatch: 10.2.6+ minimatch: 11.0.4+ glob: 14.0.3+ node-forge: 1.4.2rollup: 4.65.1- seroval: '>=1.5.3'+ seroval: 1.6.11effect@<4.0.0-0: '>=3.20.0'fast-xml-parser: '>=5.5.7'socket.io-parser: '>=4.2.7'@@ -197,7 +199,7 @@ overrides:path-to-regexp: '>=8.4.0'brace-expansion: '>=5.0.12 <6'yaml: '>=2.8.3'- qs: '>=6.16.0'+ qs: 6.16.2ws: '>=8.20.1'ip-address: 10.7.5postcss: '>=8.5.32 <9'@@ -223,7 +225,7 @@ overrides:vitest@*: 5.0.5patchedDependencies:- [email protected]: 7af5fa910c9692d7af8fa33df2f5a3d74505f4e7c46a012d0e0137903d01215c+ [email protected]: 9dc8a7fbaa157ccfc5e00257048c4758e857071050fe7fddba831a0c65358a29[email protected]: 961e904f64170e793e7ee7ea99c70d9df6319e1807c59dfc2817051a075cacddimporters:@@ -2969,6 +2971,9 @@ packages:'@ioredis/[email protected]':resolution: {integrity: sha512-vrx0AE/T0h7cRZwfo1M39Cr+ZhZrkf0V8mQN75wucKCxCLD9l/VX6no3gFvrLqD1IlG/1LtzWovqEw3t0Vr9zg==}+ '@isaacs/[email protected]':+ resolution: {integrity: sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==}+'@isaacs/[email protected]':resolution: {integrity: sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA==}engines: {node: '>=12'}@@ -5068,10 +5073,12 @@ packages:'@smithy/[email protected]':resolution: {integrity: sha512-zRMhfkByhT2snNdr1si24vJitU6Cr9ix2MikUfWmkAgp4jrNP0GcKSP5YvwQ+TlI8AZXER5QOGJn3JsVtSD9/A==}engines: {node: '>=18.0.0'}+ deprecated: Deprecated due to a bug in custom logger data redaction. See https://github.com/aws/aws-sdk-js-v3/issues/8393.'@smithy/[email protected]':resolution: {integrity: sha512-97imTcCyiPd8k0e9+ts/Sp0W65Dn9Ti357J7M09Ov4tI8Q1JDJVFSoAJtjEVKqfHEr3Pdo2jfolqKCaaiszH0g==}engines: {node: '>=18.0.0'}+ deprecated: Deprecated due to a bug in custom logger data redaction. See https://github.com/aws/aws-sdk-js-v3/issues/8393.'@smithy/[email protected]':resolution: {integrity: sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==}@@ -8178,8 +8185,8 @@ packages:resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}engines: {node: '>= 6'}- resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}+ resolution: {integrity: sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==}engines: {node: 18 || 20 || >=22}@@ -9257,9 +9264,9 @@ packages:resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}engines: {node: '>=4'}- resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}- engines: {node: 18 || 20 || >=22}+ resolution: {integrity: sha512-/UJ1dEoVQTjPNDh6SGlUo+ueLMmoHTas4q+8yaAR/5t6nLAIiBDJtoYUh20IYleix7ehiQkgczb84PE3uzHkxg==}+ engines: {node: 20 || >=22}resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}@@ -9445,8 +9452,8 @@ packages:encoding:optional: true- resolution: {integrity: sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==}+ resolution: {integrity: sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==}engines: {node: '>= 6.13.0'}@@ -9818,8 +9825,8 @@ packages:resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}- resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}+ resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==}engines: {node: 18 || 20 || >=22}@@ -10095,8 +10102,8 @@ packages:resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}engines: {node: '>=6'}- resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==}+ resolution: {integrity: sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==}engines: {node: '>=0.6'}@@ -10591,16 +10598,16 @@ packages:resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==}engines: {node: '>=10'}peerDependencies:- seroval: '>=1.5.3'+ seroval: 1.6.11resolution: {integrity: sha512-N7mWAMydj89EnYTHtRpS3LBrAz3J9O6oVrqpuXuvlAHfAUG8WEKqtbAd7SBiJNY5NfCAFhSdyAh7wI4Shjqy4g==}engines: {node: '>=10'}peerDependencies:- seroval: '>=1.5.3'+ seroval: 1.6.11- resolution: {integrity: sha512-AeDcLh0yO2SFm9W71essgnSzLV9DI8ZH0x0knXn2DMnUZj728mpLbxjlbB6IqKCmqh8JA3cEqRyGoNkt584JcQ==}+ resolution: {integrity: sha512-hpb6XnMCGN/A+79Uf8V7/iTGkyyyazNn5X0CoCAp7Uy9vT3RT8jZ9GLcnxGoVjg3P8AArbe4ZVHq6C8oT2a0kA==}engines: {node: '>=10'}@@ -13436,10 +13443,10 @@ snapshots:expo-server: 58.0.6fetch-nodeshim: 0.4.10getenv: 2.0.0- glob: 13.0.6+ glob: 14.0.3lan-network: 0.2.1multitars: 1.0.2- node-forge: 1.4.0(patch_hash=7af5fa910c9692d7af8fa33df2f5a3d74505f4e7c46a012d0e0137903d01215c)+ node-forge: 1.4.2npm-package-arg: 11.0.3ora: 3.4.0picomatch: 4.0.7@@ -13476,7 +13483,7 @@ snapshots:'@expo/[email protected]':dependencies:- node-forge: 1.4.0(patch_hash=7af5fa910c9692d7af8fa33df2f5a3d74505f4e7c46a012d0e0137903d01215c)+ node-forge: 1.4.2dependencies:@@ -13488,7 +13495,7 @@ snapshots:chalk: 4.1.2debug: 4.4.3([email protected])getenv: 2.0.0- glob: 13.0.6+ glob: 14.0.3semver: 7.8.5slugify: 1.6.9xcode: 4.0.0@@ -13506,9 +13513,9 @@ snapshots:'@expo/json-file': 11.2.1'@expo/platforms': 58.0.1'@expo/require-utils': 58.0.4([email protected])([email protected])- deepmerge: 4.3.1+ deepmerge: 4.3.1(patch_hash=9dc8a7fbaa157ccfc5e00257048c4758e857071050fe7fddba831a0c65358a29)getenv: 2.0.0- glob: 13.0.6+ glob: 14.0.3resolve-workspace-root: 2.0.1semver: 7.8.5slugify: 1.6.9@@ -13553,9 +13560,9 @@ snapshots:chalk: 4.1.2debug: 4.4.3([email protected])getenv: 2.0.0- glob: 13.0.6+ glob: 14.0.3ignore: 5.3.2- minimatch: 10.2.6+ minimatch: 11.0.4resolve-from: 5.0.0semver: 7.8.5transitivePeerDependencies:@@ -13640,7 +13647,7 @@ snapshots:chalk: 4.1.2debug: 4.4.3([email protected])getenv: 2.0.0- glob: 13.0.6+ glob: 14.0.3hermes-parser: 0.36.1jsc-safe-url: 0.2.4lightningcss: 1.33.0@@ -14013,6 +14020,8 @@ snapshots:'@ioredis/[email protected]': {}+ '@isaacs/[email protected]': {}+'@isaacs/[email protected]': {}'@jest/[email protected]':@@ -16163,7 +16172,7 @@ snapshots:dependencies:'@sentry/core': 11.9.0dotenv: 17.4.2- glob: 13.0.6+ glob: 14.0.3magic-string: 1.4.3oxc-parser: 0.152.0sentry: 0.45.0@@ -16256,7 +16265,7 @@ snapshots:'@dotenvx/dotenvx': 1.52.0cn: 0.2.6code-block-writer: 13.0.3- deepmerge: 4.3.1+ deepmerge: 4.3.1(patch_hash=9dc8a7fbaa157ccfc5e00257048c4758e857071050fe7fddba831a0c65358a29)execa: 9.6.1fast-glob: 3.3.3fs-extra: 11.3.3@@ -16606,8 +16615,8 @@ snapshots:dependencies:'@tanstack/history': 1.162.5cookie-es: 3.1.1- seroval: 1.6.7- seroval-plugins: 1.6.8([email protected])+ seroval: 1.6.11+ seroval-plugins: 1.6.8([email protected])dependencies:@@ -16967,7 +16976,7 @@ snapshots:'@ts-morph/[email protected]':dependencies:fast-glob: 3.3.3- minimatch: 10.2.6+ minimatch: 11.0.4path-browserify: 1.0.1'@types/[email protected]': {}@@ -17881,7 +17890,7 @@ snapshots:http-errors: 2.0.1iconv-lite: 0.7.3on-finished: 2.4.1- qs: 6.16.0+ qs: 6.16.2raw-body: 3.0.2type-is: 2.1.0transitivePeerDependencies:@@ -18588,7 +18597,7 @@ snapshots:optional: true- [email protected]: {}+ [email protected](patch_hash=9dc8a7fbaa157ccfc5e00257048c4758e857071050fe7fddba831a0c65358a29): {}@@ -19261,7 +19270,7 @@ snapshots:once: 1.4.0parseurl: 1.3.3proxy-addr: 2.0.8- qs: 6.16.0+ qs: 6.16.2range-parser: 1.3.0router: 2.2.0([email protected])send: 1.2.1([email protected])@@ -19503,11 +19512,11 @@ snapshots:dependencies:is-glob: 4.0.3dependencies:- minimatch: 10.2.6+ minimatch: 11.0.4minipass: 7.1.3- path-scurry: 2.0.2+ path-scurry: 3.0.0dependencies:@@ -19633,7 +19642,7 @@ snapshots:dependencies:'@selderee/plugin-htmlparser2': 0.11.0- deepmerge: 4.3.1+ deepmerge: 4.3.1(patch_hash=9dc8a7fbaa157ccfc5e00257048c4758e857071050fe7fddba831a0c65358a29)dom-serializer: 2.0.0htmlparser2: 8.0.2selderee: 0.11.0@@ -20714,8 +20723,9 @@ snapshots:dependencies:+ '@isaacs/nonrecursive-glob-match': 1.0.3brace-expansion: 5.0.12@@ -20953,7 +20963,7 @@ snapshots:dependencies:whatwg-url: 5.0.0- [email protected](patch_hash=7af5fa910c9692d7af8fa33df2f5a3d74505f4e7c46a012d0e0137903d01215c): {}+ [email protected]: {}@@ -21327,7 +21337,7 @@ snapshots:dependencies:lru-cache: 11.5.3minipass: 7.1.3@@ -21635,7 +21645,7 @@ snapshots:dependencies:es-define-property: 1.0.1side-channel: 1.1.1@@ -21772,7 +21782,7 @@ snapshots:css-tree: 3.2.1debounce: 2.2.0esbuild: 0.28.2- glob: 13.0.6+ glob: 14.0.3jiti: 2.6.1log-symbols: 7.0.1marked: 15.0.12@@ -22405,15 +22415,15 @@ snapshots:dependencies:- seroval: 1.6.7+ seroval: 1.6.11dependencies:- seroval: 1.6.7+ seroval: 1.6.11- [email protected]: {}+ [email protected]: {}dependencies:@@ -22457,7 +22467,7 @@ snapshots:cn: 0.2.6commander: 14.0.3dedent: 1.7.1- deepmerge: 4.3.1+ deepmerge: 4.3.1(patch_hash=9dc8a7fbaa157ccfc5e00257048c4758e857071050fe7fddba831a0c65358a29)diff: 9.0.0execa: 9.6.1fast-glob: 3.3.3@@ -22637,8 +22647,8 @@ snapshots:dependencies:csstype: 3.2.3- seroval: 1.6.7- seroval-plugins: 1.5.6([email protected])+ seroval: 1.6.11+ seroval-plugins: 1.5.6([email protected])dependencies:diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 27975d433..baeb4e3fa 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -11,9 +11,11 @@ overrides:hono: ">=4.13.14 <5"lodash: 4.18.1markdown-it: 15.0.3- minimatch: 10.2.6+ minimatch: 11.0.4+ glob: 14.0.3+ node-forge: 1.4.2rollup: 4.65.1- seroval: ">=1.5.3"+ seroval: 1.6.11"effect@<4.0.0-0": ">=3.20.0"fast-xml-parser: ">=5.5.7"socket.io-parser: ">=4.2.7"@@ -21,7 +23,7 @@ overrides:path-to-regexp: ">=8.4.0"brace-expansion: ">=5.0.12 <6"yaml: ">=2.8.3"- qs: ">=6.16.0"+ qs: 6.16.2ws: ">=8.20.1"ip-address: 10.7.5postcss: ">=8.5.32 <9"@@ -47,8 +49,8 @@ overrides:vite@*: "catalog:"vitest@*: "catalog:"patchedDependencies:- # No upstream release yet; preserve the existing Forge and Zod 3 consumer APIs.- [email protected]: patches/[email protected]+ # Preserve compatibility while upstream fixes remain unavailable.+ [email protected]: patches/[email protected][email protected]: patches/[email protected]allowBuilds:"@prisma/engines": false@@ -108,3 +110,8 @@ minimumReleaseAgeExclude:- "@expo/[email protected]"- "@expo/[email protected]"diff --git a/renovate.json b/renovate.jsonindex 7c55ae8f5..f6f3a3932 100644--- a/renovate.json+++ b/renovate.json@@ -1,7 +1,7 @@{"$schema": "https://docs.renovatebot.com/renovate-schema.json","extends": ["config:recommended", "helpers:pinGitHubActionDigests"],- "enabledManagers": ["npm", "github-actions"],+ "enabledManagers": ["npm", "github-actions", "dockerfile"],"ignorePaths": ["**/node_modules/**","**/bower_components/**",@@ -25,6 +25,20 @@"commitMessagePrefix": "ci(deps):"},"packageRules": [+ {+ "matchManagers": ["dockerfile"],+ "matchDatasources": ["docker"],+ "commitMessagePrefix": "fix(deps):",+ "matchPackageNames": ["node"],+ "allowedVersions": "/^24\\./"+ },+ {+ "matchManagers": ["dockerfile"],+ "matchDatasources": ["docker"],+ "commitMessagePrefix": "fix(deps):",+ "matchPackageNames": ["nginx"],+ "allowedVersions": "/^1\\.30\\./"+ },{"matchManagers": ["npm"],"matchPackageNames": ["@aws-sdk/*"],diff --git a/scripts/ci/README.md b/scripts/ci/README.mdindex 0b7be12e9..d8494646d 100644--- a/scripts/ci/README.md+++ b/scripts/ci/README.md@@ -49,7 +49,20 @@ branch protection.## Dependency updates-The hosted Mend Renovate GitHub App handles npm and GitHub Actions updates from `renovate.json`.+The hosted Mend Renovate GitHub App handles npm, GitHub Actions, and Dockerfile updates from `renovate.json`.+Docker updates stay on the maintained Node 24 and stable Nginx 1.30 lines.+Check upstream security floors before approving a change of release line.+Keep GitHub's dependency graph and Dependabot alerts enabled: Renovate reads that+alert feed for security updates; replacing the updater does not replace detection.+The **Dependency graph** workflow submits both resolved pnpm graphs on trusted+main-branch updates. pnpm 12 writes multiple YAML documents, which GitHub's+static lockfile parser currently misses+([upstream issue](https://github.com/pnpm/pnpm/issues/13805)).+Manifest-only detection omits transitive dependencies and the isolated browser+runner. The submission reads the actual application graph in each lockfile,+keeps their manifests separate, and refuses invalid or empty graphs. Submission+permissions are confined to the trusted-main workflow; PR checks validate the+payload builder without writing to GitHub.Routine PR creation is allowed Monday 00:00–06:00 UTC, subject to hosted App availability.Routine npm updates wait seven days and group related package families, with patches and minors on separate branches.Unrelated npm updates stay separate; at most three routine dependency PRs remain open at once.@@ -91,14 +104,18 @@ appear in advisory scanners because its upstream version has not changed;record the advisory, patch, and regression evidence instead of changing packageversions to hide the finding.-The root backports cover Node-forge's nested DigestAlgorithm validation-([GHSA-86w9-cpqp-85rv](https://github.com/advisories/GHSA-86w9-cpqp-85rv),-[upstream fix](https://github.com/digitalbazaar/forge/pull/1152)) and bounded-collection validation in Zod 3, including its embedded Zod 4 exports+The root backports cover deepmerge's result-prototype poisoning+([GHSA-gcqx-w48m-w2h4](https://github.com/advisories/GHSA-gcqx-w48m-w2h4))+and bounded collection validation in Zod 3, including its embedded Zod 4 exports([GHSA-mrhx-c7xc-m3w5](https://github.com/advisories/GHSA-mrhx-c7xc-m3w5),[upstream fix](https://github.com/colinhacks/zod/pull/6652),-[Zod 3 tracking](https://github.com/colinhacks/zod/issues/6653)). Run-`pnpm test:security:dependencies` against the installed dependency graph.+[Zod 3 tracking](https://github.com/colinhacks/zod/issues/6653)).+The deepmerge patch drops `__proto__` keys both while cloning the target and+merging the source, including its CommonJS and browser entries. It leaves+ordinary keys, symbols, array options, and custom merges intact.+Forge 1.4.2 replaces our earlier signature-verification backport. Keep its+DigestInfo regression cases and Buffer-PEM compatibility test when updating it.+Run `pnpm test:security:dependencies` against the installed dependency graph.Remove a backport only when its replacement passes the same regression cases.The BrowserStack cache-policy patch and its removal conditions are documentedin [the test workspace](../../tests/e2e/patches/README.md); run its checks withdiff --git a/scripts/ci/dependency-graph-identity.mjs b/scripts/ci/dependency-graph-identity.mjsnew file mode 100644index 000000000..ab08f0027--- /dev/null+++ b/scripts/ci/dependency-graph-identity.mjs@@ -0,0 +1,29 @@+// pnpm peer contexts and patch hashes are not part of the published npm version.+export function packageIdentity(key) {+ if (typeof key !== "string") throw new Error("Expected a package key");+ const base = key.split("(", 1)[0];+ let depth = 0;+ for (const character of key.slice(base.length)) {+ if (character === "(") depth++;+ else if (character === ")") depth--;+ else if (depth === 0) throw new Error(`Invalid pnpm suffix: ${key}`);+ if (depth < 0) throw new Error(`Invalid pnpm suffix: ${key}`);+ }+ if (depth !== 0) throw new Error(`Invalid pnpm suffix: ${key}`);+ const match = /^(?<name>(?:@[^/@\s]+\/)?[^/@\s]+)@(?<version>\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?)$/.exec(base);+ if (!match) throw new Error(`Unsupported npm package identity: ${key}`);+ const { name, version } = match.groups;+ const encodedName = name.split("/").map(encodeURIComponent).join("/");+ return { base, purl: `pkg:npm/${encodedName}@${encodeURIComponent(version)}` };+}++export function dependencyKey(name, reference) {+ if (typeof reference !== "string" || reference.length === 0) {+ throw new Error(`Invalid resolved reference for ${name}`);+ }+ const value = reference.startsWith("npm:") ? reference.slice(4) : reference;+ // Aliases carry the real package name, including scoped names, in the version.+ const key = value.split("(", 1)[0].includes("@") ? value : `${name}@${value}`;+ packageIdentity(key);+ return key;+}diff --git a/scripts/ci/dependency-graph-lock.mjs b/scripts/ci/dependency-graph-lock.mjsnew file mode 100644index 000000000..4e0c9839d--- /dev/null+++ b/scripts/ci/dependency-graph-lock.mjs@@ -0,0 +1,164 @@+import { posix } from "node:path";+import { parseAllDocuments } from "yaml";+import { dependencyKey, packageIdentity } from "./dependency-graph-identity.mjs";++const groups = ["dependencies", "optionalDependencies", "devDependencies"];++function mapping(value, label) {+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ throw new Error(`Expected a mapping: ${label}`);+ }+ return value;+}++function dependencyGroup(owner, group) {+ return mapping(Object.hasOwn(owner, group) ? owner[group] : {}, group);+}++function mainDocument(source) {+ const documents = parseAllDocuments(source);+ const candidates = [];+ for (const document of documents) {+ if (document.errors.length) throw new Error(document.errors[0].message);+ const lock = mapping(document.toJS({ maxAliasCount: 100 }), "lock document");+ if (lock.lockfileVersion !== "9.0") throw new Error("Expected pnpm lockfile version 9.0");+ const importers = Object.values(mapping(lock.importers, "importers"));+ if (!importers.length) throw new Error("Empty importers");+ for (const importer of importers) mapping(importer, "importer");+ const application = importers.some((importer) =>+ groups.some((group) => group in importer),+ );+ const environment = importers.some(+ (importer) =>+ "configDependencies" in importer ||+ "packageManagerDependencies" in importer,+ );+ if (application && !environment) candidates.push(lock);+ else if (!environment || application) throw new Error("Unrecognized or mixed lock document");+ }+ if (candidates.length !== 1) throw new Error("Expected exactly one application lock document");+ return candidates[0];+}++export function buildManifest(source, path) {+ const lock = mainDocument(source);+ const packages = mapping(lock.packages, "packages");+ const snapshots = mapping(lock.snapshots, "snapshots");+ if (!Object.keys(packages).length || !Object.keys(snapshots).length) {+ throw new Error(`Empty application graph: ${path}`);+ }++ const resolved = new Map();+ const packageBases = new Set();+ for (const [key, value] of Object.entries(packages)) {+ mapping(value, key);+ const { base, purl } = packageIdentity(key);+ packageBases.add(base);+ resolved.set(purl, { package_url: purl, dependencies: new Set() });+ }++ const identities = new Map();+ const covered = new Set();+ for (const [key, value] of Object.entries(snapshots)) {+ mapping(value, key);+ const { base, purl } = packageIdentity(key);+ if (!packageBases.has(base)) throw new Error(`Snapshot missing package: ${key}`);+ covered.add(base);+ identities.set(key, purl);+ }+ for (const base of packageBases) {+ if (!covered.has(base)) throw new Error(`Package missing snapshot: ${base}`);+ }++ function resolve(name, reference) {+ const key = dependencyKey(name, reference);+ if (!identities.has(key)) {+ throw new Error(`Unresolved dependency: ${name} -> ${reference}`);+ }+ return key;+ }++ const edges = new Map();+ for (const [key, snapshot] of Object.entries(snapshots)) {+ const children = new Set();+ // pnpm lists resolved peers here too. transitivePeerDependencies contains+ // names without versions, so it cannot establish additional resolved edges.+ for (const group of ["dependencies", "optionalDependencies"]) {+ const references = dependencyGroup(snapshot, group);+ for (const [name, reference] of Object.entries(references)) {+ const child = resolve(name, reference);+ children.add(child);+ resolved.get(identities.get(key)).dependencies.add(identities.get(child));+ }+ }+ edges.set(key, children);+ }++ const direct = new Set();+ const runtimeRoots = [];+ const developmentRoots = [];+ for (const [importerPath, importer] of Object.entries(lock.importers)) {+ for (const group of groups) {+ for (const [name, value] of Object.entries(dependencyGroup(importer, group))) {+ const { version } = mapping(value, name);+ if (typeof version === "string" && version.startsWith("link:")) {+ const target = posix.normalize(posix.join(importerPath, version.slice(5)));+ if (!Object.hasOwn(lock.importers, target)) {+ throw new Error(`Missing workspace importer: ${target}`);+ }+ // Every workspace importer is processed; local links have no npm PURL.+ continue;+ }+ const key = resolve(name, version);+ direct.add(identities.get(key));+ (group === "devDependencies" ? developmentRoots : runtimeRoots).push(key);+ }+ }+ }+ if (!direct.size) throw new Error(`No direct npm dependencies: ${path}`);++ function reachable(roots) {+ const seen = new Set();+ const queue = [...roots];+ while (queue.length) {+ const key = queue.pop();+ if (seen.has(key)) continue;+ seen.add(key);+ queue.push(...edges.get(key));+ }+ return new Set([...seen].map((key) => identities.get(key)));+ }+ const runtime = reachable(runtimeRoots);+ const development = reachable(developmentRoots);++ return {+ name: path,+ file: { source_location: path },+ resolved: Object.fromEntries(+ [...resolved]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([purl, entry]) => {+ // Unreachable entries remain, without an invented scope/relationship.+ const relationship = direct.has(purl)+ ? "direct"+ : runtime.has(purl) || development.has(purl)+ ? "indirect"+ : undefined;+ const scope = runtime.has(purl)+ ? "runtime"+ : development.has(purl)+ ? "development"+ : undefined;+ return [+ purl,+ {+ package_url: entry.package_url,+ ...(relationship && { relationship }),+ ...(scope && { scope }),+ dependencies: [...entry.dependencies].sort(),+ },+ ];+ }),+ ),+ };+}diff --git a/scripts/ci/dependency-graph-snapshot.mjs b/scripts/ci/dependency-graph-snapshot.mjsnew file mode 100644index 000000000..eea04a1e1--- /dev/null+++ b/scripts/ci/dependency-graph-snapshot.mjs@@ -0,0 +1,35 @@+import { buildManifest } from "./dependency-graph-lock.mjs";++export const lockPaths = ["pnpm-lock.yaml", "tests/e2e/pnpm-lock.yaml"];++// https://docs.github.com/en/rest/dependency-graph/dependency-submission+export function buildSnapshot(sources, { sha, ref, runId, scanned }) {+ if (!/^(?:[a-f\d]{40}|[a-f\d]{64})$/i.test(sha ?? "")) {+ throw new Error("Invalid commit SHA");+ }+ if (ref !== "refs/heads/main") throw new Error("Dependency snapshots require main");+ if (typeof runId !== "string" || !runId) throw new Error("Missing run ID");+ if (typeof scanned !== "string" || !Number.isFinite(Date.parse(scanned))) {+ throw new Error("Invalid scan time");+ }+ if (+ Object.keys(sources).sort().join("\n") !== [...lockPaths].sort().join("\n")+ ) {+ throw new Error("Both application and e2e locks are required");+ }+ return {+ version: 0,+ sha,+ ref,+ job: { id: runId, correlator: "kaneo-pnpm-locks" },+ detector: {+ name: "kaneo-pnpm-locks",+ version: "1.0.0",+ url: "https://github.com/usekaneo/kaneo/blob/main/scripts/ci/dependency-graph.mjs",+ },+ scanned,+ manifests: Object.fromEntries(+ lockPaths.map((path) => [path, buildManifest(sources[path], path)]),+ ),+ };+}diff --git a/scripts/ci/dependency-graph.mjs b/scripts/ci/dependency-graph.mjsnew file mode 100644index 000000000..1ddb62a24--- /dev/null+++ b/scripts/ci/dependency-graph.mjs@@ -0,0 +1,67 @@+import { readFile } from "node:fs/promises";+import { pathToFileURL } from "node:url";+import { buildSnapshot, lockPaths } from "./dependency-graph-snapshot.mjs";++export async function main(args = process.argv.slice(2), env = process.env) {+ if (args.length !== 1 || !["--dry-run", "--submit"].includes(args[0])) {+ throw new Error("Usage: node scripts/ci/dependency-graph.mjs --dry-run|--submit");+ }+ const sources = Object.fromEntries(+ await Promise.all(+ lockPaths.map(async (path) => [path, await readFile(path, "utf8")]),+ ),+ );+ const snapshot = buildSnapshot(sources, {+ sha: env.GITHUB_SHA,+ ref: env.GITHUB_REF,+ runId: `${env.GITHUB_RUN_ID || "dry-run"}-${env.GITHUB_RUN_ATTEMPT || "1"}`,+ scanned: new Date().toISOString(),+ });+ if (args[0] === "--dry-run") {+ process.stdout.write(`${JSON.stringify(snapshot, null, 2)}\n`);+ return;+ }++ if (+ env.GITHUB_ACTIONS !== "true" ||+ !["push", "workflow_dispatch"].includes(env.GITHUB_EVENT_NAME)+ ) {+ throw new Error("Submission requires a trusted main workflow");+ }+ if (!env.GITHUB_TOKEN || !/^\d+$/.test(env.GITHUB_RUN_ID ?? "")) {+ throw new Error("Missing workflow credentials");+ }+ if (!/^[\w.-]+\/[\w.-]+$/.test(env.GITHUB_REPOSITORY ?? "")) {+ throw new Error("Invalid repository");+ }++ const endpoint = `https://api.github.com/repos/${env.GITHUB_REPOSITORY}/dependency-graph/snapshots`;+ const response = await fetch(endpoint, {+ method: "POST",+ headers: {+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${env.GITHUB_TOKEN}`,+ "Content-Type": "application/json",+ "X-GitHub-Api-Version": "2026-03-10",+ },+ body: JSON.stringify(snapshot),+ redirect: "error",+ signal: AbortSignal.timeout(60_000),+ });+ if (response.status !== 201) {+ throw new Error(`Dependency submission failed: HTTP ${response.status}`);+ }+ const result = await response.json();+ if (result.result !== "SUCCESS") throw new Error("Dependency submission did not report SUCCESS");+ for (const [path, manifest] of Object.entries(snapshot.manifests)) {+ const count = Object.keys(manifest.resolved).length;+ console.log(`${path}: submitted ${count} npm packages`);+ }+}++if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main().catch((error) => {+ console.error(error.message);+ process.exitCode = 1;+ });+}diff --git a/scripts/ci/dependency-graph.test.mjs b/scripts/ci/dependency-graph.test.mjsnew file mode 100644index 000000000..35b222a0b--- /dev/null+++ b/scripts/ci/dependency-graph.test.mjs@@ -0,0 +1,355 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import { parseAllDocuments, stringify } from "yaml";+import { dependencyKey, packageIdentity } from "./dependency-graph-identity.mjs";+import { buildManifest } from "./dependency-graph-lock.mjs";+import { buildSnapshot, lockPaths } from "./dependency-graph-snapshot.mjs";+import { main } from "./dependency-graph.mjs";++// Reduced from the actual pnpm 12 locks: environment document first, then the+// workspace graph with catalog aliases, linked importers, peers and patches.+const environment = `---+lockfileVersion: '9.0'+importers:+ .:+ configDependencies: {}+ packageManagerDependencies:+ pnpm: {specifier: 12.15.0, version: 12.15.0}+packages:+ [email protected]: {resolution: {integrity: sha512-fixture}}+snapshots:+ [email protected]: {}+`;+const application = `---+lockfileVersion: '9.0'+settings: {autoInstallPeers: true, excludeLinksFromLockfile: false}+importers:+ .:+ dependencies:+ vite: {specifier: 'catalog:', version: '@voidzero-dev/[email protected]([email protected])'}+ shared: {specifier: 'workspace:*', version: 'link:packages/shared'}+ devDependencies:+ browserstack-node-sdk: {specifier: 1.75.1, version: '1.75.1([email protected])'}+ packages/shared:+ dependencies:+ node-forge: {specifier: 1.4.2, version: 1.4.2}+packages:+ '@voidzero-dev/[email protected]': {resolution: {integrity: sha512-fixture}}+ [email protected]: {resolution: {integrity: sha512-fixture}}+ [email protected]: {resolution: {integrity: sha512-fixture}}+ [email protected]: {resolution: {integrity: sha512-fixture}}+ [email protected]: {resolution: {integrity: sha512-fixture}}+ [email protected]: {resolution: {integrity: sha512-fixture}, os: [darwin]}+ [email protected]: {resolution: {integrity: sha512-fixture}}+snapshots:+ '@voidzero-dev/[email protected]([email protected])':+ dependencies:+ qs: 6.16.2+ merged: [email protected](patch_hash=abcdef)+ optionalDependencies:+ fsevents: 2.3.3+ transitivePeerDependencies: [unresolved-peer]+ dependencies:+ qs: 6.16.2+ [email protected]: {}+ [email protected]: {}+ [email protected](patch_hash=abcdef): {}+ [email protected]: {optional: true}+ [email protected]: {}+`;+const fixture = environment + application;+const context = {+ sha: "a".repeat(40),+ ref: "refs/heads/main",+ runId: "123-1",+ scanned: "2026-11-02T00:00:00.000Z",+};+const sources = Object.fromEntries(lockPaths.map((path) => [path, fixture]));++function changedApplication(change) {+ const lock = parseAllDocuments(application)[0].toJS();+ change(lock);+ return `${environment}---\n${stringify(lock)}`;+}++// Assertions mirror the official REST snapshot/manifest/dependency schemas:+// https://github.com/github/rest-api-description (components/schemas/snapshot).+// No network or file writes are needed to validate a constructed payload.+function assertPayload(snapshot) {+ assert.deepEqual(Object.keys(snapshot).sort(), [+ "detector", "job", "manifests", "ref", "scanned", "sha", "version",+ ]);+ assert.equal(snapshot.version, 0);+ assert.match(snapshot.sha, /^(?:[a-f\d]{40}|[a-f\d]{64})$/i);+ assert.match(snapshot.ref, /^refs\//);+ assert.ok(Number.isFinite(Date.parse(snapshot.scanned)));+ assert.deepEqual(Object.keys(snapshot.job).sort(), ["correlator", "id"]);+ assert.deepEqual(Object.keys(snapshot.detector).sort(), ["name", "url", "version"]);+ const descriptions = [+ ...Object.values(snapshot.job),+ ...Object.values(snapshot.detector),+ ];+ for (const value of descriptions) {+ assert.equal(typeof value, "string");+ assert.ok(value.length);+ }+ assert.deepEqual(Object.keys(snapshot.manifests), lockPaths);+ for (const [path, manifest] of Object.entries(snapshot.manifests)) {+ assert.deepEqual(Object.keys(manifest).sort(), ["file", "name", "resolved"]);+ assert.equal(manifest.name, path);+ assert.deepEqual(manifest.file, { source_location: path });+ assert.ok(Object.keys(manifest.resolved).length);+ for (const [key, entry] of Object.entries(manifest.resolved)) {+ assert.equal(entry.package_url, key);+ assert.match(key, /^pkg:npm\//);+ const fields = ["package_url", "relationship", "scope", "dependencies"];+ assert.ok(Object.keys(entry).every((field) => fields.includes(field)));+ if (entry.relationship) {+ assert.ok(["direct", "indirect"].includes(entry.relationship));+ }+ if (entry.scope) {+ assert.ok(["runtime", "development"].includes(entry.scope));+ }+ assert.ok(Array.isArray(entry.dependencies));+ for (const dependency of entry.dependencies) {+ assert.equal(typeof dependency, "string");+ assert.ok(Object.hasOwn(manifest.resolved, dependency));+ }+ }+ }+}++test("npm identities retain real names and versions, removing only pnpm contexts", () => {+ assert.equal(+ "pkg:npm/%40scope/[email protected]",+ );+ assert.equal(+ packageIdentity("[email protected](patch_hash=abcdef)").purl,+ "pkg:npm/[email protected]",+ );+ assert.equal(+ packageIdentity("[email protected]+build.2").purl,+ "pkg:npm/[email protected]%2Bbuild.2",+ );+ assert.equal(+ dependencyKey("alias", "@scope/[email protected]([email protected])"),+ "@scope/[email protected]([email protected])",+ );+ assert.equal(dependencyKey("alias", "npm:[email protected]"), "[email protected]");+ assert.equal(dependencyKey("alias", "[email protected]"), "[email protected]");+ assert.equal(dependencyKey("@scope/pkg", "1.2.3"), "@scope/[email protected]");+ for (const value of [+ "pkg@https://example.com/a.tgz",+ "pkg@latest",+ "[email protected](unclosed",+ "[email protected]([email protected])junk",+ ]) {+ assert.throws(() => packageIdentity(value));+ }+});++test("selects the main graph in either document order, retaining all packages and edges", () => {+ const manifest = buildManifest(fixture, lockPaths[0]);+ assert.deepEqual(+ buildManifest(application + environment, lockPaths[0]),+ manifest,+ );+ const entries = manifest.resolved;+ assert.equal(Object.keys(entries).length, 7);+ assert.ok(!Object.hasOwn(entries, "pkg:npm/[email protected]"));+ assert.ok(!Object.hasOwn(entries, "pkg:npm/[email protected]"));+ assert.deepEqual(+ entries["pkg:npm/%40voidzero-dev/[email protected]"].dependencies,+ );+ assert.equal(entries["pkg:npm/[email protected]"].relationship, "indirect");+ assert.equal(entries["pkg:npm/[email protected]"].scope, "runtime");+ assert.equal(entries["pkg:npm/[email protected]"].relationship, "direct");+ assert.equal(+ entries["pkg:npm/[email protected]"].scope,+ "development",+ );+ assert.equal(entries["pkg:npm/[email protected]"].scope, "runtime");+ assert.deepEqual(entries["pkg:npm/[email protected]"], {+ package_url: "pkg:npm/[email protected]",+ dependencies: [],+ });+});++test("merges edges from peer variants without losing packages or mistaking development for runtime", () => {+ const source = changedApplication((lock) => {+ lock.snapshots["[email protected]([email protected])"] = {+ dependencies: { orphan: "1.0.0" },+ };+ lock.importers["."].devDependencies.second = {+ version: "[email protected]([email protected])",+ };+ });+ const entries = buildManifest(source, lockPaths[0]).resolved;+ assert.equal(Object.keys(entries).length, 7);+ assert.deepEqual(+ entries["pkg:npm/[email protected]"].dependencies,+ ["pkg:npm/[email protected]", "pkg:npm/[email protected]"],+ );+ assert.equal(entries["pkg:npm/[email protected]"].scope, "development");+});++test("fails closed on malformed, ambiguous, empty or incomplete locks", () => {+ const invalid = [+ environment,+ fixture + application,+ "---\nlockfileVersion: [broken",+ fixture.replace("lockfileVersion: '9.0'", "lockfileVersion: '10.0'"),+ application.replace("settings:", "lockfileVersion: '9.0'\nsettings:"),+ changedApplication((lock) => {+ lock.packages = {};+ }),+ changedApplication((lock) => {+ lock.snapshots = {};+ }),+ changedApplication((lock) => {+ delete lock.snapshots["[email protected]"];+ }),+ changedApplication((lock) => {+ delete lock.packages["[email protected]"];+ }),+ changedApplication((lock) => {+ lock.packages["unsupported@file:../pkg"] = {};+ }),+ changedApplication((lock) => {+ lock.snapshots["[email protected]"].dependencies = { missing: "1.0.0" };+ }),+ changedApplication((lock) => {+ lock.snapshots["[email protected]"].optionalDependencies = { missing: "1.0.0" };+ }),+ changedApplication((lock) => {+ lock.importers["."].dependencies.missing = { version: "1.0.0" };+ }),+ changedApplication((lock) => {+ lock.importers["."].dependencies.shared.version = "link:missing";+ }),+ changedApplication((lock) => {+ lock.importers["."].dependencies = null;+ }),+ changedApplication((lock) => {+ lock.importers = { ".": { dependencies: {} } };+ }),+ ];+ for (const source of invalid) {+ assert.throws(() => buildManifest(source, lockPaths[0]));+ }+});++test("one stable snapshot contains two distinct manifests at the same commit", () => {+ const snapshot = buildSnapshot(sources, context);+ assertPayload(snapshot);+ assert.equal(snapshot.sha, context.sha);+ const next = buildSnapshot(sources, { ...context, runId: "124-2" });+ assert.equal(snapshot.job.correlator, next.job.correlator);+ assert.equal(snapshot.detector.name, next.detector.name);+ assert.notEqual(snapshot.job.id, next.job.id);+ assert.throws(() => buildSnapshot({ [lockPaths[0]]: fixture }, context));+ assert.throws(() => buildSnapshot(sources, { ...context, sha: "main" }));+ assert.throws(() =>+ buildSnapshot(sources, { ...context, ref: "refs/heads/untrusted" }),+ );+ assert.throws(() =>+ buildSnapshot(sources, { ...context, scanned: "invalid" }),+ );+});++test("actual root and e2e locks cover every main-document package with valid payloads", async () => {+ const actual = Object.fromEntries(+ await Promise.all(+ lockPaths.map(async (path) => [path, await readFile(path, "utf8")]),+ ),+ );+ const snapshot = buildSnapshot(actual, context);+ assertPayload(snapshot);+ for (const path of lockPaths) {+ const documents = parseAllDocuments(actual[path]).map((document) =>+ document.toJS(),+ );+ const lock = documents.find((document) => document.settings);+ assert.ok(lock);+ const expected = [+ ...new Set(Object.keys(lock.packages).map((key) => packageIdentity(key).purl)),+ ].sort();+ assert.deepEqual(Object.keys(snapshot.manifests[path].resolved).sort(), expected);+ }+ for (const name of ["qs", "node-forge", "deepmerge"]) {+ assert.ok(+ Object.keys(snapshot.manifests[lockPaths[0]].resolved).some((key) =>+ key.startsWith(`pkg:npm/${name}@`),+ ),+ );+ }+ assert.ok(+ Object.keys(snapshot.manifests[lockPaths[1]].resolved).some((key) =>+ key.startsWith("pkg:npm/browserstack-node-sdk@"),+ ),+ );+});++test("CLI dry-run builds the real payload without networking or file writes", async (t) => {+ let output = "";+ t.mock.method(process.stdout, "write", (chunk) => {+ output += chunk;+ return true;+ });+ const network = t.mock.method(globalThis, "fetch", () => {+ throw new Error("Unexpected network access");+ });+ await main(["--dry-run"], { GITHUB_SHA: context.sha, GITHUB_REF: context.ref });+ assertPayload(JSON.parse(output));+ assert.equal(network.mock.callCount(), 0);+ await assert.rejects(+ main(["--submit"], {+ GITHUB_SHA: context.sha,+ GITHUB_REF: "refs/heads/other",+ }),+ );+ await assert.rejects(+ main(["--submit"], {+ GITHUB_SHA: context.sha,+ GITHUB_REF: context.ref,+ GITHUB_ACTIONS: "true",+ GITHUB_EVENT_NAME: "pull_request",+ }),+ );+ assert.equal(network.mock.callCount(), 0);+});++test("trusted submission sends one complete snapshot to GitHub and rejects unsuccessful responses", async (t) => {+ t.mock.method(console, "log", () => {});+ const env = {+ GITHUB_SHA: context.sha,+ GITHUB_REF: context.ref,+ GITHUB_ACTIONS: "true",+ GITHUB_EVENT_NAME: "workflow_dispatch",+ GITHUB_REPOSITORY: "usekaneo/kaneo",+ GITHUB_RUN_ID: "123",+ GITHUB_RUN_ATTEMPT: "2",+ GITHUB_TOKEN: "synthetic-test-token",+ };+ const network = t.mock.method(globalThis, "fetch", async (url, options) => {+ assert.equal(url, "https://api.github.com/repos/usekaneo/kaneo/dependency-graph/snapshots");+ assert.equal(options.method, "POST");+ assert.equal(options.redirect, "error");+ assert.equal(options.headers.Authorization, "Bearer synthetic-test-token");+ const payload = JSON.parse(options.body);+ assertPayload(payload);+ assert.equal(payload.sha, context.sha);+ assert.equal(payload.job.id, "123-2");+ return Response.json({ result: "SUCCESS" }, { status: 201 });+ });+ await main(["--submit"], env);+ assert.equal(network.mock.callCount(), 1);+ network.mock.mockImplementation(async () => Response.json({ result: "ERROR" }, { status: 201 }));+ await assert.rejects(main(["--submit"], env), /did not report SUCCESS/);+ network.mock.mockImplementation(async () => new Response(null, { status: 403 }));+ await assert.rejects(main(["--submit"], env), /HTTP 403/);+});diff --git a/scripts/security/dependency-deepmerge.test.mjs b/scripts/security/dependency-deepmerge.test.mjsnew file mode 100644index 000000000..73ecbc3d9--- /dev/null+++ b/scripts/security/dependency-deepmerge.test.mjs@@ -0,0 +1,46 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import test from "node:test";++const mobileRequire = createRequire(+ new URL("../../apps/mobile/package.json", import.meta.url),+);+const expoRequire = createRequire(mobileRequire.resolve("expo/package.json"));+const configRequire = createRequire(expoRequire.resolve("@expo/config"));+const merge = configRequire("deepmerge");++test("deepmerge cannot poison a result through null-prototype sources or targets", () => {+ const source = JSON.parse('{"__proto__":{"privileged":true},"name":"safe"}');+ for (const target of [{}, Object.create(null), source]) {+ for (const input of [source, Object.assign(Object.create(null), source)]) {+ const result = merge(target, input);+ assert.equal(Object.getPrototypeOf(result), Object.prototype);+ assert.equal(result.privileged, undefined);+ assert.equal(Object.hasOwn(result, "__proto__"), false);+ assert.equal(result.name, "safe");+ }+ }+ assert.equal({}.privileged, undefined);+});++test("deepmerge protects nested objects, arrays and merge.all without changing ordinary data", () => {+ const unsafe = JSON.parse(+ '{"nested":{"__proto__":{"privileged":true}},"items":[{"__proto__":{"privileged":true}}]}',+ );+ const result = merge.all([+ { nested: { title: "kept" }, items: ["first"] },+ unsafe,+ ]);+ assert.deepEqual(result, { nested: { title: "kept" }, items: ["first", {}] });+ assert.equal(Object.getPrototypeOf(result.nested), Object.prototype);+ assert.equal(Object.getPrototypeOf(result.items[1]), Object.prototype);+ const symbol = Symbol("kept");+ assert.deepEqual(merge({ [symbol]: "value", a: [1] }, { a: [2] }), {+ [symbol]: "value",+ a: [1, 2],+ });+ assert.deepEqual(+ merge({ a: [1] }, { a: [2] }, { arrayMerge: (_a, b) => b }),+ { a: [2] },+ );+});diff --git a/scripts/security/dependency-glob.test.mjs b/scripts/security/dependency-glob.test.mjsnew file mode 100644index 000000000..725ec8777--- /dev/null+++ b/scripts/security/dependency-glob.test.mjs@@ -0,0 +1,49 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++const mobileRequire = createRequire(+ new URL("../../apps/mobile/package.json", import.meta.url),+);+const expoRequire = createRequire(mobileRequire.resolve("expo/package.json"));+const cliRequire = createRequire(expoRequire.resolve("@expo/cli/package.json"));+const globRequire = createRequire(cliRequire.resolve("glob"));++test("Expo glob retains recursive matching, dotfile and ignore behavior", async () => {+ const { glob } = cliRequire("glob");+ const directory = await mkdtemp(join(tmpdir(), "kaneo-glob-security-"));+ try {+ await mkdir(join(directory, "nested"));+ await writeFile(join(directory, "nested", "keep.json"), "{}");+ await writeFile(join(directory, "nested", "ignore.json"), "{}");+ await writeFile(join(directory, ".hidden.json"), "{}");+ const options = { cwd: directory, dot: true, ignore: "**/ignore.json" };+ assert.deepEqual((await glob("**/*.json", options)).sort(), [+ ".hidden.json",+ "nested/keep.json",+ ]);+ assert.deepEqual(cliRequire("glob").globSync("**/*.json", options).sort(), [+ ".hidden.json",+ "nested/keep.json",+ ]);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++test("glob preprocessing cannot amplify a small pattern without a bound", () => {+ const entry = globRequire.resolve("minimatch");+ const code = `const {Minimatch}=require(${JSON.stringify(entry)});new Minimatch(Array(22).fill('**/..').join('/')+'/file',{optimizationLevel:2});process.stdout.write('completed');`;+ const child = spawnSync(process.execPath, ["-e", code], {+ timeout: 5000,+ maxBuffer: 4096,+ encoding: "utf8",+ });+ assert.equal(child.error, undefined, child.error?.message);+ assert.equal(child.status, 0, child.stderr);+ assert.equal(child.stdout, "completed");+});diff --git a/scripts/security/dependency-node-forge.test.mjs b/scripts/security/dependency-node-forge.test.mjsindex 229be7bf6..f02e68803 100644--- a/scripts/security/dependency-node-forge.test.mjs+++ b/scripts/security/dependency-node-forge.test.mjs@@ -61,7 +61,7 @@ test("Expo's node-forge accepts valid SHA-256 DigestInfo with optional NULL", ()});test("Expo's node-forge rejects unconsumed nested DigestAlgorithm elements", () => {- // Backport of https://github.com/digitalbazaar/forge/pull/1152.+ // Keep this case when replacing the earlier local backport with an upstream release.for (const withNull of [false, true]) {assert.throws(() => publicKey.verify(digest, signedDigestInfo(withNull, true)),@@ -69,3 +69,10 @@ test("Expo's node-forge rejects unconsumed nested DigestAlgorithm elements", ());}});++test("Expo certificate tooling accepts PEM buffers after the Forge security upgrade", () => {+ const pem = forge.pki.publicKeyToPem(publicKey);+ const decoded = forge.pem.decode(Buffer.from(pem));+ assert.equal(decoded.length, 1);+ assert.equal(decoded[0].type, "PUBLIC KEY");+});diff --git a/scripts/security/dependency-seroval.test.mjs b/scripts/security/dependency-seroval.test.mjsnew file mode 100644index 000000000..3a2a1a972--- /dev/null+++ b/scripts/security/dependency-seroval.test.mjs@@ -0,0 +1,54 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import test from "node:test";++const webRequire = createRequire(+ new URL("../../apps/web/package.json", import.meta.url),+);+const routerRequire = createRequire(+ webRequire.resolve("@tanstack/react-router"),+);+const coreRequire = createRequire(+ routerRequire.resolve("@tanstack/router-core"),+);+const seroval = coreRequire("seroval");++test("the router's Seroval rejects array nodes whose elements are an attacker-controlled object", () => {+ const payload = seroval.toJSON(["valid"]);+ // A small finite length proves rejection without running an exhaustion payload.+ payload.t.a = { length: 512 };+ assert.throws(() => seroval.fromJSON(payload), seroval.SerovalError);+});++test("Seroval retains shared references, cycles and application value types", () => {+ const value = {+ when: new Date("2026-11-02T00:00:00Z"),+ map: new Map([["key", 1]]),+ bytes: new Uint8Array([1, 2]),+ };+ value.self = value;+ const copy = seroval.fromJSON(seroval.toJSON(value));+ assert.equal(copy.self, copy);+ assert.equal(copy.when.toISOString(), value.when.toISOString());+ assert.deepEqual(copy.map, value.map);+ assert.deepEqual(copy.bytes, value.bytes);+});++test("Seroval serializes the actual typed-array type instead of an own constructor name", () => {+ const bytes = new Uint8Array([1, 2]);+ Object.defineProperty(bytes, "constructor", {+ value: { name: "KaneoInjectedConstructor" },+ });+ const serialized = seroval.serialize(bytes);+ assert.doesNotMatch(serialized, /KaneoInjectedConstructor/);+ assert.deepEqual(seroval.deserialize(serialized), new Uint8Array([1, 2]));+});++test("Seroval escapes closing script tags in RegExp sources while preserving the expression", () => {+ const value = new RegExp("</script><script>synthetic</script>", "i");+ const serialized = seroval.serialize(value);+ assert.doesNotMatch(serialized, /<\/script/i);+ const copy = seroval.deserialize(serialized);+ assert.equal(copy.source, value.source);+ assert.equal(copy.flags, value.flags);+});diff --git a/tests/api-integration/account-deletion.test.ts b/tests/api-integration/account-deletion.test.tsindex fc05c988c..564280d52 100644--- a/tests/api-integration/account-deletion.test.ts+++ b/tests/api-integration/account-deletion.test.ts@@ -130,6 +130,25 @@ describe("API integration: account deletion", () => {expect(workspaces).toHaveLength(1);});+ it.each(["member, owner", "member, Owner ", "member,\u00a0owner"])(+ "does not leave a workspace ownerless by counting a malformed owner grant (%s)",+ async (role) => {+ const owner = await createWorkspaceMember({+ role: "owner",+ workspaceName: "Acme",+ });+ await addMember(owner.workspace.id, role);+ await expect(deleteAccountData(owner.user.id)).rejects.toThrow(+ /only owner of "Acme"/,+ );+ expect(+ await db.query.workspaceUserTable.findFirst({+ where: eq(schema.workspaceUserTable.userId, owner.user.id),+ }),+ ).toBeDefined();+ },+ );+it.each([false, true])("revokes project sockets after leaving even if the old post-delete lookup fails (%s)",async (failLookup) => {diff --git a/tests/api-integration/helpers/invitation-security.ts b/tests/api-integration/helpers/invitation-security.tsnew file mode 100644index 000000000..997be3bb1--- /dev/null+++ b/tests/api-integration/helpers/invitation-security.ts@@ -0,0 +1,124 @@+import { eq } from "drizzle-orm";+import { expect, vi } from "vite-plus/test";+import db, { schema } from "../../../apps/api/src/database";+import { createApp } from "../../../apps/api/src/index";+import { signUpWithSession } from "./auth-session";+import { createProjectFixture } from "./fixtures";++// Keep asynchronous notification subscribers from racing database resets.+vi.mock("../../../apps/api/src/events", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../apps/api/src/events")>()),+ publishEvent: vi.fn().mockResolvedValue(undefined),+}));++type App = ReturnType<typeof createApp>["app"];++export async function organizationRequest(+ app: App,+ headers: Record<string, string>,+ operation: string,+ body: Record<string, unknown>,+) {+ return app.request(`/api/auth/organization/${operation}`, {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify(body),+ });+}++export async function invitationSecurityFixture(actorRole = "recruiter") {+ const { app } = createApp();+ const owner = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Owner",+ role: "user",+ });+ const actor = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Inviter",+ role: "user",+ });+ const created = await organizationRequest(+ app,+ { cookie: owner.cookies },+ "create",+ { name: "Invitation security", slug: "invitation-security" },+ );+ expect(created.status).toBe(200);+ const workspace = (await created.json()) as { id: string };+ await db.insert(schema.workspaceRoleTable).values({+ workspaceId: workspace.id,+ role: "recruiter",+ permission: JSON.stringify({ invitation: ["create"] }),+ });+ const [membership] = await db+ .insert(schema.workspaceUserTable)+ .values({+ workspaceId: workspace.id,+ userId: actor.userId,+ role: actorRole,+ joinedAt: new Date(),+ })+ .returning();+ const { project } = await createProjectFixture({ workspaceId: workspace.id });++ const invite = (+ cookies: string,+ role: unknown,+ extra: Record<string, unknown> = {},+ ) =>+ organizationRequest(app, { cookie: cookies }, "invite-member", {+ organizationId: workspace.id,+ email: "[email protected]",+ role,+ ...extra,+ });+ const pending = async (role: string) => {+ const [invitation] = await db+ .insert(schema.invitationTable)+ .values({+ workspaceId: workspace.id,+ inviterId: owner.userId,+ email: "[email protected]",+ role,+ status: "pending",+ projectAccess: "selected",+ projectIds: [project.id],+ expiresAt: new Date(Date.now() + 86_400_000),+ })+ .returning();+ return invitation;+ };+ const accept = async (invitationId: string) => {+ const invitee = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Invitee",+ role: "user",+ });+ const response = await organizationRequest(+ app,+ { cookie: invitee.cookies },+ "accept-invitation",+ { invitationId },+ );+ return { response, invitee };+ };+ const bearer = async () => {+ const session = await db.query.sessionTable.findFirst({+ where: eq(schema.sessionTable.userId, actor.userId),+ });+ return { authorization: `Bearer ${session!.token}` };+ };+ return {+ app,+ owner,+ actor,+ workspace,+ membership,+ project,+ invite,+ pending,+ accept,+ bearer,+ };+}diff --git a/tests/api-integration/invitation-legacy-owner-role.test.ts b/tests/api-integration/invitation-legacy-owner-role.test.tsnew file mode 100644index 000000000..cb89ee752--- /dev/null+++ b/tests/api-integration/invitation-legacy-owner-role.test.ts@@ -0,0 +1,152 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";+import { invitationSecurityFixture, organizationRequest } from "./helpers/invitation-security";+import { readMemberAccessRows } from "./helpers/project-access/read-member-access-rows";++beforeEach(resetTestDatabase);++describe("legacy invitation ownership", () => {+ it.each(["member, owner", "owner ,member", "member,\towner\n"])(+ "refuses pending %j before acceptance or project access writes",+ async (role) => {+ const ctx = await invitationSecurityFixture();+ const invitation = await ctx.pending(role);+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const { response, invitee } = await ctx.accept(invitation.id);+ expect(response.status).toBe(403);+ expect(await response.json()).toMatchObject({ code: "OWNER_ROLE_REVIEW_REQUIRED" });+ expect(await db.query.invitationTable.findFirst({+ where: eq(schema.invitationTable.id, invitation.id),+ })).toEqual(invitation);+ expect(await db.query.workspaceUserTable.findFirst({+ where: eq(schema.workspaceUserTable.userId, invitee.userId),+ })).toBeUndefined();+ expect(await readMemberAccessRows(ctx.workspace.id, invitee.userId)).toEqual({ rules: [], grants: [] });+ expect(send).not.toHaveBeenCalled();+ },+ );++ it.each(["owner", "member,owner"])(+ "still accepts a previously authorized canonical %s invitation",+ async (role) => {+ const ctx = await invitationSecurityFixture();+ const invitation = await ctx.pending(role);+ const { response, invitee } = await ctx.accept(invitation.id);+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({ member: { role } });+ expect(await readMemberAccessRows(ctx.workspace.id, invitee.userId)).toEqual({ rules: [], grants: [] });+ },+ );++ it("denies legacy owner resends before expiry changes or email, including for owners", async () => {+ const ctx = await invitationSecurityFixture();+ const invitation = await ctx.pending("member, owner");+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ for (const cookies of [ctx.actor.cookies, ctx.owner.cookies]) {+ const response = await ctx.invite(cookies, "member", { resend: true });+ expect(response.status).toBe(403);+ expect(await response.text()).not.toContain(invitation.id);+ expect(await db.query.invitationTable.findFirst({+ where: eq(schema.invitationTable.id, invitation.id),+ })).toEqual(invitation);+ }+ const listed = await ctx.app.request(+ `/api/auth/organization/list-invitations?organizationId=${ctx.workspace.id}`,+ { headers: { cookie: ctx.actor.cookies } },+ );+ expect(listed.status).toBe(200);+ expect(await listed.json()).toEqual([]);+ expect(send).not.toHaveBeenCalled();+ });++ it.each(["member", "owner"])("lets an owner replace an expired ambiguous invitation with %s", async (role) => {+ const ctx = await invitationSecurityFixture();+ const expired = await ctx.pending("member, owner");+ await db.update(schema.invitationTable)+ .set({ expiresAt: new Date(Date.now() - 60_000) })+ .where(eq(schema.invitationTable.id, expired.id));+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const response = await ctx.invite(ctx.owner.cookies, role, { resend: true });+ expect(response.status).toBe(200);+ const created = await response.json() as { id: string; role: string };+ expect(created.id).not.toBe(expired.id);+ expect(created.role).toBe(role);+ expect(send).toHaveBeenCalledOnce();+ });++ it("rejects owner requests even when a resend would retain an ordinary stored role", async () => {+ const ctx = await invitationSecurityFixture();+ const invitation = await ctx.pending("member");+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const response = await ctx.invite(ctx.actor.cookies, ["member", " owner"], { resend: true });+ expect(response.status).toBe(403);+ expect(await db.query.invitationTable.findFirst({+ where: eq(schema.invitationTable.id, invitation.id),+ })).toEqual(invitation);+ expect(send).not.toHaveBeenCalled();+ });++ it("preserves ordinary resends, stored roles and project selections", async () => {+ const ctx = await invitationSecurityFixture();+ const invitation = await ctx.pending("member,recruiter");+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const response = await ctx.invite(ctx.actor.cookies, "member", { resend: true });+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ id: invitation.id, role: "member,recruiter",+ projectAccess: "selected", projectIds: [ctx.project.id],+ });+ expect(send).toHaveBeenCalledOnce();+ });+});++describe("previously accepted ambiguous ownership", () => {+ it.each(["member, owner", "recruiter, owner", "admin, owner"])(+ "removes only the accidental ownership of %j without rewriting membership",+ async (role) => {+ const ctx = await invitationSecurityFixture(role);+ const capabilities = await ctx.app.request(`/api/workspace/${ctx.workspace.id}/capabilities`, {+ headers: { cookie: ctx.actor.cookies },+ });+ expect(capabilities.status).toBe(200);+ expect(await capabilities.json()).toMatchObject({+ deleteWorkspace: false,+ inviteUsers: role !== "member, owner",+ deleteProjects: role === "admin, owner",+ });+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const invited = await ctx.invite(ctx.actor.cookies, "owner");+ expect(invited.status).toBe(403);+ expect(await invited.json()).toMatchObject({ code: "OWNER_ROLE_REVIEW_REQUIRED" });+ const promoted = await organizationRequest(ctx.app, { cookie: ctx.actor.cookies }, "update-member-role", {+ organizationId: ctx.workspace.id, memberId: ctx.membership.id, role: ["member", " owner"],+ });+ expect(promoted.status).toBe(403);+ // A second canonical owner makes the provider's last-owner check pass;+ // the malformed actor must still never acquire the right to remove one.+ const secondOwner = await ctx.accept((await ctx.pending("owner")).id);+ expect(secondOwner.response.status).toBe(200);+ const removed = await organizationRequest(ctx.app, { cookie: ctx.actor.cookies }, "remove-member", {+ organizationId: ctx.workspace.id, memberIdOrEmail: "[email protected]",+ });+ expect(removed.status).toBe(403);+ expect(await removed.json()).toMatchObject({ code: "OWNER_ROLE_REVIEW_REQUIRED" });+ expect(await db.query.workspaceUserTable.findFirst({+ where: eq(schema.workspaceUserTable.id, ctx.membership.id),+ })).toEqual(ctx.membership);+ expect(await db.query.workspaceUserTable.findFirst({+ where: eq(schema.workspaceUserTable.userId, ctx.owner.userId),+ })).toBeDefined();+ expect(send).not.toHaveBeenCalled();+ // Only an explicit decision by a true owner can restore ownership.+ const reviewed = await organizationRequest(ctx.app, { cookie: ctx.owner.cookies }, "update-member-role", {+ organizationId: ctx.workspace.id, memberId: ctx.membership.id, role: "member,owner",+ });+ expect(reviewed.status).toBe(200);+ expect((await ctx.invite(ctx.actor.cookies, "owner", { email: "[email protected]" })).status).toBe(200);+ },+ );+});diff --git a/tests/api-integration/invitation-owner-api-key.test.ts b/tests/api-integration/invitation-owner-api-key.test.tsnew file mode 100644index 000000000..a8bf921b9--- /dev/null+++ b/tests/api-integration/invitation-owner-api-key.test.ts@@ -0,0 +1,128 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";+import {+ invitationSecurityFixture,+ organizationRequest,+} from "./helpers/invitation-security";++beforeEach(resetTestDatabase);++async function createKey(+ ctx: Awaited<ReturnType<typeof invitationSecurityFixture>>,+ cookies: string,+ permissions: Record<string, string[]> | null,+) {+ const response = await ctx.app.request("/api/auth/api-key/create", {+ method: "POST",+ headers: { cookie: cookies, "content-type": "application/json" },+ body: JSON.stringify({ name: "Invitation authorization" }),+ });+ expect(response.status).toBe(200);+ const key = (await response.json()) as { id: string; key: string };+ await db+ .update(schema.apikeyTable)+ .set({+ rateLimitEnabled: false,+ ...(permissions === null+ ? {}+ : { permissions: JSON.stringify(permissions) }),+ })+ .where(eq(schema.apikeyTable.id, key.id));+ return key;+}++describe("invitation ownership with API keys", () => {+ it.each([false, true])(+ "checks the key owner's current membership despite an owner cookie (bearer=%s)",+ async (bearer) => {+ const ctx = await invitationSecurityFixture("owner");+ const key = await createKey(ctx, ctx.actor.cookies, {+ invitation: ["create"],+ });+ await db+ .update(schema.workspaceUserTable)+ .set({ role: "recruiter" })+ .where(eq(schema.workspaceUserTable.id, ctx.membership.id));+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const headers: Record<string, string> = {+ cookie: ctx.owner.cookies,+ ...(bearer+ ? { authorization: `Bearer ${key.key}` }+ : { "x-api-key": key.key }),+ };+ const denied = await organizationRequest(+ ctx.app,+ headers,+ "invite-member",+ {+ organizationId: ctx.workspace.id,+ email: "[email protected]",+ role: ["member", " owner"],+ },+ );+ expect(denied.status).toBe(403);+ expect(await db.select().from(schema.invitationTable)).toEqual([]);+ expect(send).not.toHaveBeenCalled();+ const allowed = await organizationRequest(+ ctx.app,+ headers,+ "invite-member",+ {+ organizationId: ctx.workspace.id,+ email: "[email protected]",+ role: ["member", " recruiter"],+ },+ );+ expect(allowed.status).toBe(200);+ expect(await allowed.json()).toMatchObject({ role: "member,recruiter" });+ },+ );++ it.each([false, true])(+ "enforces invitation scope before owner grants and preserves scoped/legacy owner keys (bearer=%s)",+ async (bearer) => {+ const ctx = await invitationSecurityFixture();+ const key = await createKey(ctx, ctx.owner.cookies, {+ workspace: ["read"],+ });+ const headers: Record<string, string> = bearer+ ? { authorization: `Bearer ${key.key}` }+ : { "x-api-key": key.key };+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const denied = await organizationRequest(+ ctx.app,+ headers,+ "invite-member",+ {+ organizationId: ctx.workspace.id,+ email: "[email protected]",+ role: ["member", " owner"],+ },+ );+ expect(denied.status).toBe(403);+ expect(await denied.json()).toMatchObject({ code: "API_KEY_SCOPE" });+ expect(await db.select().from(schema.invitationTable)).toEqual([]);+ expect(send).not.toHaveBeenCalled();+ for (const permissions of [{ invitation: ["create"] }, null]) {+ const allowedKey = await createKey(ctx, ctx.owner.cookies, permissions);+ const response = await organizationRequest(+ ctx.app,+ bearer+ ? { authorization: `Bearer ${allowedKey.key}` }+ : { "x-api-key": allowedKey.key },+ "invite-member",+ {+ organizationId: ctx.workspace.id,+ email: permissions ? "[email protected]" : "[email protected]",+ role: ["member", " owner"],+ },+ );+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({ role: "member,owner" });+ }+ },+ );+});diff --git a/tests/api-integration/invitation-owner-authorization.test.ts b/tests/api-integration/invitation-owner-authorization.test.tsnew file mode 100644index 000000000..68a5de5b4--- /dev/null+++ b/tests/api-integration/invitation-owner-authorization.test.ts@@ -0,0 +1,168 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { resetTestDatabase } from "./helpers/database";+import {+ invitationSecurityFixture,+ organizationRequest,+} from "./helpers/invitation-security";+import { readMemberAccessRows } from "./helpers/project-access/read-member-access-rows";++beforeEach(resetTestDatabase);++const ownerRoles = [+ "owner",+ "member,owner",+ "member, owner",+ "member, owner",+ "owner ,member",+ "member,\towner\n",+ "member,\u00a0owner\u00a0",+ ["member", " owner"],+ ["member, owner"],+] as const;++describe("invitation ownership authorization", () => {+ it.each(["admin", "recruiter"])(+ "denies all owner role shapes before persistence or email for %s",+ async (actorRole) => {+ const ctx = await invitationSecurityFixture(actorRole);+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ for (const role of ownerRoles) {+ for (const resend of [false, true]) {+ const response = await ctx.invite(ctx.actor.cookies, role, {+ resend,+ });+ expect(response.status, JSON.stringify({ role, resend })).toBe(403);+ expect(await response.json()).toMatchObject({+ code: "YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE",+ });+ }+ }+ expect(await db.select().from(schema.invitationTable)).toEqual([]);+ expect(await db.select().from(schema.workspaceUserTable)).toHaveLength(2);+ expect(send).not.toHaveBeenCalled();+ },+ );++ it("checks bearer sessions and the active workspace before provider validation", async () => {+ const ctx = await invitationSecurityFixture();+ await db+ .update(schema.sessionTable)+ .set({ activeOrganizationId: ctx.workspace.id })+ .where(eq(schema.sessionTable.userId, ctx.actor.userId));+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const response = await organizationRequest(+ ctx.app,+ await ctx.bearer(),+ "invite-member",+ {+ organizationId: "",+ email: "[email protected]",+ role: ["member", "\towner "],+ },+ );+ expect(response.status).toBe(403);+ expect(await db.select().from(schema.invitationTable)).toEqual([]);+ expect(send).not.toHaveBeenCalled();+ });++ it.each(["owner", "member,owner"])(+ "allows a true %s to grant normalized multi-role ownership",+ async (ownerRole) => {+ const ctx = await invitationSecurityFixture();+ await db+ .update(schema.workspaceUserTable)+ .set({ role: ownerRole })+ .where(eq(schema.workspaceUserTable.userId, ctx.owner.userId));+ const created = await ctx.invite(ctx.owner.cookies, [+ "member",+ " owner ",+ ]);+ expect(created.status).toBe(200);+ const invitation = (await created.json()) as { id: string; role: string };+ expect(invitation.role).toBe("member,owner");+ const { response, invitee } = await ctx.accept(invitation.id);+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ member: { role: "member,owner" },+ });+ const followup = await ctx.invite(invitee.cookies, "owner", {+ email: "[email protected]",+ });+ expect(followup.status).toBe(200);+ },+ );++ it.each(+ ["member", " member, recruiter ", ["member", " recruiter "]].map(+ (role) => ({ role }),+ ),+ )(+ "preserves regular invitations, multiple roles and selected project access ($role)",+ async ({ role }) => {+ const ctx = await invitationSecurityFixture();+ const created = await ctx.invite(ctx.actor.cookies, role, {+ projectAccess: "selected",+ projectIds: [ctx.project.id],+ });+ expect(created.status).toBe(200);+ const invitation = (await created.json()) as { id: string; role: string };+ const expected = role === "member" ? "member" : "member,recruiter";+ expect(invitation.role).toBe(expected);+ const { response, invitee } = await ctx.accept(invitation.id);+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ member: { role: expected },+ });+ const access = await readMemberAccessRows(+ ctx.workspace.id,+ invitee.userId,+ );+ expect(access.rules.map((row) => row.projectAccess)).toEqual([+ "selected",+ ]);+ expect(access.grants.map((row) => row.projectId)).toEqual([+ ctx.project.id,+ ]);+ expect(+ (+ await ctx.app.request(`/api/project/${ctx.project.id}`, {+ method: "DELETE",+ headers: { cookie: invitee.cookies },+ })+ ).status,+ ).toBe(403);+ },+ );++ it("normalizes ownership before enforcing the owner project-access invariant", async () => {+ const ctx = await invitationSecurityFixture();+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ const response = await ctx.invite(+ ctx.owner.cookies,+ ["member", " owner "],+ {+ projectAccess: "selected",+ projectIds: [ctx.project.id],+ },+ );+ expect(response.status).toBe(400);+ expect(await db.select().from(schema.invitationTable)).toEqual([]);+ expect(send).not.toHaveBeenCalled();+ });++ it.each(+ [null, 3, { role: "owner" }, ["member", 3]].map((role) => ({ role })),+ )(+ "retains provider validation for malformed role shapes ($role)",+ async ({ role }) => {+ const ctx = await invitationSecurityFixture();+ const send = vi.spyOn(email, "sendWorkspaceInvitationEmail");+ expect((await ctx.invite(ctx.actor.cookies, role)).status).toBe(400);+ expect(await db.select().from(schema.invitationTable)).toEqual([]);+ expect(send).not.toHaveBeenCalled();+ },+ );+});diff --git a/tests/api/user/account-deletion.test.ts b/tests/api/user/account-deletion.test.tsindex 37d1ff978..f709b74fa 100644--- a/tests/api/user/account-deletion.test.ts+++ b/tests/api/user/account-deletion.test.ts@@ -26,7 +26,18 @@ describe("hasOwnerRole", () => {it("matches owner inside a comma separated role list", () => {expect(hasOwnerRole("admin,owner")).toBe(true);- expect(hasOwnerRole("member, Owner ")).toBe(true);+ expect(hasOwnerRole("member,owner")).toBe(true);+ });++ it("does not count ambiguous or differently cased grants as replacement owners", () => {+ for (const role of [+ "member, owner",+ " Owner ",+ "OWNER",+ "member,\u00a0owner",+ ]) {+ expect(hasOwnerRole(role)).toBe(false);+ }});it("does not match other roles", () => {diff --git a/tests/e2e/pnpm-lock.yaml b/tests/e2e/pnpm-lock.yamlindex c366f4ac7..391f9e8c3 100644--- a/tests/e2e/pnpm-lock.yaml+++ b/tests/e2e/pnpm-lock.yaml@@ -164,6 +164,9 @@ settings:overrides:get-uri>basic-ftp: 6.2.3+ minimatch: 11.0.4+ glob: 14.0.3+ follow-redirects: 1.16.2patchedDependencies:[email protected]: 10f814373e15493e8a475041e5ecf67775717842648b0879b8c6c26055cfcfe9@@ -295,9 +298,8 @@ packages:peerDependencies:'@grpc/grpc-js': ^1.8.21- '@isaacs/[email protected]':- resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}- engines: {node: '>=12'}+ '@isaacs/[email protected]':+ resolution: {integrity: sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==}'@js-sdsl/[email protected]':resolution: {integrity: sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==}@@ -342,10 +344,6 @@ packages:resolution: {integrity: sha512-DGi23l8EnLqSwkluyqJCUlW58EZpOL5gFMKdlRDTp+0Ukg/v7JXZ6hcaOq//12Nio62Dt0Df+tH09e0U2xU69Q==}engines: {node: '>=14'}- '@pkgjs/[email protected]':- resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}- engines: {node: '>=14'}-'@playwright/[email protected]':resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==}engines: {node: '>=20'}@@ -407,6 +405,7 @@ packages:'@smithy/[email protected]':resolution: {integrity: sha512-oRw0rB9QSUiCZfEs23G5F4Af+b2rQt1lItIICWu5IejFNd+uPM8SWqiKLMpQ6bX1Q7slsLbjuoE2niErFtkVPQ==}engines: {node: '>=18.0.0'}+ deprecated: Deprecated due to a bug in custom logger data redaction. See https://github.com/aws/aws-sdk-js-v3/issues/8393.'@smithy/[email protected]':resolution: {integrity: sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==}@@ -539,8 +538,9 @@ packages:react-native-b4a:optional: true- resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}+ resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}+ engines: {node: 18 || 20 || >=22}resolution: {integrity: sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==}@@ -606,8 +606,9 @@ packages:resolution: {integrity: sha512-2hCgjEmP8YLWQ130n2FerGv7rYpfBmnmp9Uy2Le1vge6X3gZIfSmEzP5QTDElFxcvVcXlEn8Aq6MU/PZygIOog==}engines: {node: '>=14.16'}- resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==}+ resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}+ engines: {node: 20 || >=22}resolution: {integrity: sha512-WExfBqEId4t0pmJqmskrdV26OUXxcWEu3ciEbPV6RWY1ZoiofoV5+vEJT7fNXqghxA7iqDiIorsegPpvuxWdOQ==}@@ -941,8 +942,8 @@ packages:resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==}- resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==}+ resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}engines: {node: '>=4.0'}peerDependencies:debug: '*'@@ -950,10 +951,6 @@ packages:debug:optional: true- resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==}- engines: {node: '>=14'}-resolution: {integrity: sha512-yDYSgNMraqvnxiEXO4hi88+YZxaHC6QKzb5N84iRCTDeRO7ZALpir/lVmf/uXUhnwUr2O4HU8s/n6x+yNjQkHw==}engines: {node: '>= 14.17'}@@ -1018,10 +1015,9 @@ packages:resolution: {integrity: sha512-qoerOEliJn3z+Zyn1HW2F6eoYJqKwS6MgC9cztTLUB/xLWX8gD/6T60pKn4+t/d6tP7JlybI7Z3z+I572CR/Vg==}- resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}- deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]- hasBin: true+ resolution: {integrity: sha512-A1vjIwC3qpdCso45Iw127gnp7sPhqgY8lUQhDrArIs+GbmfaaVPFuoyy7WyLT9EPZCRZ7j7aLdwUhQmHWesEow==}+ engines: {node: 18 || 20 || >=22}resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==}@@ -1218,9 +1214,6 @@ packages:peerDependencies:ws: '*'- resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}-resolution: {integrity: sha512-CqRA220YV/6jCo8VWvAt1KKx6eek1VIHMPeLEbpcfSfkEeWyBNppynM/o6q+Wmw+sOhos2ml34wZbSX3G13//g==}engines: {node: ^12.13.0 || ^14.15.0 || ^16.10.0 || >=17.0.0}@@ -1302,8 +1295,9 @@ packages:resolution: {integrity: sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}- resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}+ resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==}+ engines: {node: 20 || >=22}resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}@@ -1340,13 +1334,9 @@ packages:resolution: {integrity: sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg==}engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}- resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==}- engines: {node: '>=16 || 14 >=14.17'}+ resolution: {integrity: sha512-/UJ1dEoVQTjPNDh6SGlUo+ueLMmoHTas4q+8yaAR/5t6nLAIiBDJtoYUh20IYleix7ehiQkgczb84PE3uzHkxg==}+ engines: {node: 20 || >=22}resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}@@ -1453,9 +1443,6 @@ packages:resolution: {integrity: sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==}engines: {node: '>= 14'}- resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}-resolution: {integrity: sha512-cbH9IAIJHNj9uXi196JVsRlt7cHKak6u/e6AkL/bkRelZ7rlL3X1YKxsZwa36xipOEKAsdtmaG6aAJoM1fx2zA==}engines: {node: '>=14.16'}@@ -1470,9 +1457,9 @@ packages:resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}engines: {node: '>=8'}- resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}- engines: {node: '>=16 || 14 >=14.18'}+ resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==}+ engines: {node: 18 || 20 || >=22}resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}@@ -1646,10 +1633,6 @@ packages:resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}- resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}- engines: {node: '>=14'}-resolution: {integrity: sha512-l0sIsv9VrPwovKELFDBOj/lhmIcbMvxBk2B+hRhsMM4/VL3gKtuZvYnBNixVo+N/0HnqQx2cBdLvxnAbygHpqA==}@@ -2121,14 +2104,7 @@ snapshots:'@grpc/proto-loader': 0.7.15protobufjs: 7.6.6- '@isaacs/[email protected]':- dependencies:- string-width: 5.1.2- string-width-cjs: [email protected]- strip-ansi: 7.2.0- strip-ansi-cjs: [email protected]- wrap-ansi: 8.1.0- wrap-ansi-cjs: [email protected]+ '@isaacs/[email protected]': {}'@js-sdsl/[email protected]': {}@@ -2203,9 +2179,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@pkgjs/[email protected]':- optional: true-'@playwright/[email protected]':dependencies:playwright: 1.64.1@@ -2373,7 +2346,7 @@ snapshots:dependencies:- glob: 10.5.0+ glob: 14.0.3graceful-fs: 4.2.11is-stream: 2.0.1lazystream: 1.0.1@@ -2409,7 +2382,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -2465,9 +2438,9 @@ snapshots:widest-line: 4.0.1wrap-ansi: 8.1.0dependencies:- balanced-match: 1.0.2+ balanced-match: 4.0.4dependencies:@@ -2497,7 +2470,7 @@ snapshots:cheerio: 1.0.0-rc.11dotenv: 16.6.1emittery: 0.11.0- follow-redirects: 1.16.1([email protected]([email protected]))+ follow-redirects: 1.16.2([email protected]([email protected]))form-data: 4.0.6getos: 3.2.1git-last-commit: 1.0.1@@ -2876,15 +2849,10 @@ snapshots:optionalDependencies:debug: 4.4.3([email protected])- dependencies:- cross-spawn: 7.0.6- signal-exit: 4.1.0-@@ -2972,14 +2940,11 @@ snapshots:dependencies:ini: 1.3.8dependencies:- foreground-child: 3.3.1- jackspeak: 3.4.3- minimatch: 9.0.9+ minimatch: 11.0.4minipass: 7.1.3- package-json-from-dist: 1.0.1- path-scurry: 1.11.1+ path-scurry: 3.0.0dependencies:@@ -3203,12 +3168,6 @@ snapshots:dependencies:ws: 8.21.0- dependencies:- '@isaacs/cliui': 8.0.2- optionalDependencies:- '@pkgjs/parseargs': 0.11.0-dependencies:'@types/node': 26.6.5@@ -3290,7 +3249,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:@@ -3314,13 +3273,10 @@ snapshots:dependencies:- brace-expansion: 2.1.7-- dependencies:- brace-expansion: 2.1.7+ '@isaacs/nonrecursive-glob-match': 1.0.3+ brace-expansion: 5.0.12@@ -3418,8 +3374,6 @@ snapshots:degenerator: 5.0.1netmask: 2.1.1- [email protected]: {}-dependencies:got: 12.6.1@@ -3438,9 +3392,9 @@ snapshots:dependencies:- lru-cache: 10.4.3+ lru-cache: 11.5.3minipass: 7.1.3@@ -3532,7 +3486,7 @@ snapshots:dependencies:- minimatch: 5.1.9+ minimatch: 11.0.4@@ -3571,7 +3525,7 @@ snapshots:dependencies:- glob: 10.5.0+ glob: 14.0.3dependencies:@@ -3636,8 +3590,6 @@ snapshots:- [email protected]: {}-dependencies:'@kwsites/file-exists': 1.1.1([email protected])diff --git a/tests/e2e/pnpm-workspace.yaml b/tests/e2e/pnpm-workspace.yamlindex f886df57c..f5454cf55 100644--- a/tests/e2e/pnpm-workspace.yaml+++ b/tests/e2e/pnpm-workspace.yaml@@ -5,8 +5,13 @@ packages:# get-uri still requests basic-ftp 5.x; 6.2.3 fixes its listing parser DoS.minimumReleaseAgeExclude:overrides:"get-uri>basic-ftp": 6.2.3+ minimatch: 11.0.4+ glob: 14.0.3+ follow-redirects: 1.16.2allowBuilds:protobufjs: falsepatchedDependencies:diff --git a/tests/e2e/security/dependency-upgrades.test.mjs b/tests/e2e/security/dependency-upgrades.test.mjsnew file mode 100644index 000000000..624f45825--- /dev/null+++ b/tests/e2e/security/dependency-upgrades.test.mjs@@ -0,0 +1,88 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { createRequire } from "node:module";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { runInNewContext } from "node:vm";+import test from "node:test";++const require = createRequire(import.meta.url);+const sdkRequire = createRequire(require.resolve("browserstack-node-sdk"));++test("the browser-test HTTP client strips cross-realm custom credentials on redirects", async () => {+ const { http } = sdkRequire("follow-redirects");+ const destination = createServer((req, res) =>+ res.end(JSON.stringify(req.headers)),+ );+ const source = createServer((_req, res) => {+ res.writeHead(302, {+ location: `http://127.0.0.1:${destination.address().port}/`,+ });+ res.end();+ });+ const listen = (server) =>+ new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+ try {+ await listen(destination);+ await listen(source);+ const headers = await new Promise((resolve, reject) => {+ http+ .get(+ `http://127.0.0.1:${source.address().port}/`,+ {+ headers: {+ "x-kaneo-test-secret": "synthetic",+ "x-kaneo-test-public": "kept",+ },+ sensitiveHeaders: runInNewContext("['x-kaneo-test-secret']"),+ },+ (response) => {+ let body = "";+ response.setEncoding("utf8");+ response.on("data", (chunk) => {+ body += chunk;+ });+ response.on("end", () => resolve(JSON.parse(body)));+ },+ )+ .on("error", reject);+ });+ assert.equal(headers["x-kaneo-test-secret"], undefined);+ assert.equal(headers["x-kaneo-test-public"], "kept");+ } finally {+ source.closeAllConnections();+ destination.closeAllConnections();+ await Promise.all(+ [source, destination].map(+ (s) => new Promise((resolve) => s.close(resolve)),+ ),+ );+ }+});++test("BrowserStack's archiver retains glob matching and ignore rules after the dependency upgrades", async () => {+ const archive = sdkRequire("archiver")("zip");+ const directory = await mkdtemp(join(tmpdir(), "kaneo-archive-security-"));+ try {+ await mkdir(join(directory, "nested"));+ await mkdir(join(directory, "skip"));+ await writeFile(join(directory, "top.txt"), "one");+ await writeFile(join(directory, "nested", "included.txt"), "two");+ await writeFile(join(directory, "nested", "excluded.log"), "three");+ await writeFile(join(directory, "skip", "ignored.txt"), "four");+ const entries = [];+ archive.on("entry", (entry) => entries.push(entry.name));+ const ended = new Promise((resolve, reject) => {+ archive.on("end", resolve);+ archive.on("error", reject);+ });+ archive.resume();+ archive.glob("**/*.txt", { cwd: directory, ignore: "skip/**" });+ await archive.finalize();+ await ended;+ assert.deepEqual(entries.sort(), ["nested/included.txt", "top.txt"]);+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});