Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: CodeQL

on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
# Re-scan main weekly so newly-disclosed CodeQL rules catch dormant issues.
- cron: '23 5 * * 1'

permissions:
contents: read
security-events: write
actions: read

jobs:
analyze:
name: Analyze (${{ matrix.language }})
runs-on: ubuntu-latest
timeout-minutes: 30

strategy:
fail-fast: false
matrix:
language: [javascript-typescript]

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
queries: security-and-quality

- name: Perform CodeQL analysis
uses: github/codeql-action/analyze@v3
with:
category: '/language:${{ matrix.language }}'
85 changes: 85 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@

# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.

## Our Standards

Examples of behavior that contributes to a positive environment for our community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior include:

* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.

Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at hosting@hdnet.de. All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].

For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,10 @@ lives in **[docs/DEPLOYMENT.md](docs/DEPLOYMENT.md)**.
```bash
npm test # run all tests
npm run test:watch # watch mode
npm run coverage # run tests with v8 coverage report (HTML + lcov under ./coverage)
```

More than 210 tests across 25 test files including property-based tests (fast-check), unit tests covering crypto, webhooks, BunnyCDN API, auth, validation, scope, membership, security headers, health checks, i18n, and E2E smoke tests.
More than 220 tests across 25 test files including property-based tests (fast-check), unit tests covering crypto, webhooks, BunnyCDN API, auth, validation, scope, membership, security headers, health checks, i18n, and E2E smoke tests.

## Architecture

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"start": "node .output/server/index.mjs",
"test": "vitest run",
"test:watch": "vitest",
"coverage": "vitest run --coverage",
"dev:iframe": "npm run build && node --env-file=.env .output/server/index.mjs",
"routes:generate": "tsr generate",
"typecheck": "npm run routes:generate && tsc --noEmit",
Expand Down
19 changes: 19 additions & 0 deletions src/server/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,25 @@ export function requireScope(db: AppDatabase, instanceId: string, scope: string)
}
}

/**
* Confirms the instance row exists; for read-only server functions whose
* downstream code doesn't follow up with `requireScope` / `requireEnabled`.
* Unlike `requireEnabled`, this deliberately does *not* check the paused
* flag — reads stay available while the extension is paused so the UI can
* still render the paused banner. Returns the row so callers that already
* needed to fetch it can skip a second query.
*/
export function requireInstanceExists(db: AppDatabase, instanceId: string) {
const instance = db.select().from(extensionInstances).where(eq(extensionInstances.id, instanceId)).get()
if (!instance) {
throw createAppError(ErrorType.AUTH_ERROR, 'Extension-Instanz nicht gefunden.', {
retryable: false,
code: 'INSTANCE_NOT_FOUND',
})
}
return instance
}

/**
* Blocks mutations when the extension instance is paused in mStudio.
* mittwald sets `state.enabled = false` via webhook when the user deactivates
Expand Down
10 changes: 3 additions & 7 deletions src/serverFunctions/api-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { decrypt, encrypt } from '~/server/crypto'
import { getDb } from '~/server/db/index'
import { extensionInstances } from '~/server/db/schema'
import { createLogger } from '~/server/logger.js'
import { requireEnabled } from '~/server/scope'
import { requireEnabled, requireInstanceExists } from '~/server/scope'
import { createAppError, ErrorType } from '~/shared/errors'
import { validateNonEmpty } from '~/shared/validation'

Expand Down Expand Up @@ -54,12 +54,8 @@ export const deleteApiKeyFn = createServerFn({ method: 'POST' })
export const getApiKeyStatusFn = createServerFn({ method: 'GET' })
.middleware([authMiddleware])
.handler(async ({ context }: { context: { extensionInstanceId: string } }) => {
const instance = getDb()
.select()
.from(extensionInstances)
.where(eq(extensionInstances.id, context.extensionInstanceId))
.get()
if (!instance?.encryptedApiKey) return { hasApiKey: false, last4: null }
const instance = requireInstanceExists(getDb(), context.extensionInstanceId)
if (!instance.encryptedApiKey) return { hasApiKey: false, last4: null }
try {
const key = decrypt(instance.encryptedApiKey)
return { hasApiKey: true, last4: key.slice(-4) }
Expand Down
3 changes: 3 additions & 0 deletions src/serverFunctions/permissions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { MittwaldAPIV2Client } from '@mittwald/api-client'
import { createServerFn } from '@tanstack/react-start'
import { authMiddlewareWithAccessToken } from '~/middleware/auth'
import { getDb } from '~/server/db/index'
import { getProjectRole } from '~/server/membership'
import { requireInstanceExists } from '~/server/scope'

export const checkPermissionsFn = createServerFn({ method: 'GET' })
.middleware([authMiddlewareWithAccessToken])
Expand All @@ -11,6 +13,7 @@ export const checkPermissionsFn = createServerFn({ method: 'GET' })
}: {
context: { extensionInstanceId: string; contextId: string; mittwaldClient: MittwaldAPIV2Client }
}) => {
requireInstanceExists(getDb(), context.extensionInstanceId)
const { role, allowed } = await getProjectRole(context.mittwaldClient, context.contextId)
return { role, allowed }
},
Expand Down
105 changes: 105 additions & 0 deletions tests/unit/bunnycdn-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,108 @@ describe('setupFullSiteCdn', () => {
expect(urls[2]).toContain('loadFreeCertificate')
})
})

describe('createPullZone — adoption flow', () => {
// bunny.net pull-zone names are globally unique. When POST returns the
// `pullzone.name_taken` error, createPullZone calls findPullZoneByName to
// see whether the existing zone lives in *our* account, and adopts it if so.

it('adopts an existing pull zone when name is taken in our account and origins match', async () => {
mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({ ErrorKey: 'pullzone.name_taken' }), { status: 400 }))
mockFetch.mockResolvedValueOnce(
new Response(
JSON.stringify([
{
Id: 9001,
Name: 'testzone',
Hostnames: [{ Value: 'testzone.b-cdn.net', HasCertificate: true }],
OriginUrl: 'https://example.com',
Enabled: true,
EnableGeoZoneEU: true,
EnableGeoZoneUS: true,
EnableGeoZoneASIA: true,
EnableGeoZoneSA: true,
EnableGeoZoneAF: true,
},
]),
{ status: 200 },
),
)

const result = await createPullZone({ name: 'testzone', originUrl: 'https://example.com', apiKey: 'key' })

expect(result).toEqual({
id: 9001,
name: 'testzone',
cdnDomain: 'testzone.b-cdn.net',
adopted: true,
})
})

it('throws PULL_ZONE_ORIGIN_MISMATCH when the existing zone has a different origin', async () => {
mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({ ErrorKey: 'pullzone.name_taken' }), { status: 400 }))
mockFetch.mockResolvedValueOnce(
new Response(
JSON.stringify([
{
Id: 9002,
Name: 'testzone',
Hostnames: [{ Value: 'testzone.b-cdn.net' }],
OriginUrl: 'https://different.com',
Enabled: true,
EnableGeoZoneEU: true,
EnableGeoZoneUS: true,
EnableGeoZoneASIA: true,
EnableGeoZoneSA: true,
EnableGeoZoneAF: true,
},
]),
{ status: 200 },
),
)

await expect(
createPullZone({ name: 'testzone', originUrl: 'https://example.com', apiKey: 'key' }),
).rejects.toMatchObject({ code: 'PULL_ZONE_ORIGIN_MISMATCH', type: ErrorType.BUNNY_API_ERROR })
})

it('throws PULL_ZONE_NAME_GLOBAL_TAKEN when the name is taken outside our account', async () => {
mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({ ErrorKey: 'pullzone.name_taken' }), { status: 400 }))
// Search returns empty — name is taken globally but not by us.
mockFetch.mockResolvedValueOnce(new Response(JSON.stringify([]), { status: 200 }))

await expect(
createPullZone({ name: 'globaltaken', originUrl: 'https://example.com', apiKey: 'key' }),
).rejects.toMatchObject({ code: 'PULL_ZONE_NAME_GLOBAL_TAKEN', type: ErrorType.BUNNY_API_ERROR })
})

it('rethrows non-name-taken errors unchanged', async () => {
mockFetch.mockResolvedValueOnce(new Response('Server Error', { status: 500 }))

await expect(
createPullZone({ name: 'whatever', originUrl: 'https://example.com', apiKey: 'key' }),
).rejects.toMatchObject({ code: 'BUNNY_API_ERROR', type: ErrorType.BUNNY_API_ERROR })
})
})

describe('bunnyFetch / bunnyRequest edge cases', () => {
it('createPullZone surfaces BUNNY_TIMEOUT when fetch aborts', async () => {
// Simulate AbortController firing — global fetch rejects with an
// AbortError instance.
const abortError = Object.assign(new Error('aborted'), { name: 'AbortError' })
mockFetch.mockRejectedValue(abortError)

await expect(createPullZone({ name: 'x', originUrl: 'https://example.com', apiKey: 'key' })).rejects.toMatchObject({
code: 'BUNNY_TIMEOUT',
type: ErrorType.NETWORK_ERROR,
})
})

it('purgeCache succeeds even when the response body is empty (200 + no body)', async () => {
mockFetch.mockResolvedValue(new Response('', { status: 200 }))

// No throw, undefined return — exercises the `if (!text) return undefined`
// branch in bunnyRequest.
await expect(purgeCache(42, 'key')).resolves.toBeUndefined()
})
})
Loading
Loading