Skip to content
Open
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
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ Or use the [`Dockerfile`](./Dockerfile) to build a Docker image.

Server configuration is done using environment variables. The following environment variables are available:

| Environment Variable | Required | Description | Default Value |
| --------------------- | -------- | -------------------------------------------------------------------- | ---------------- |
| `SERVER_BEARER_TOKEN` | Yes | Token for authenticating API requests. Should be large random string | |
| `PORT` | No | Port on which the server runs | `8080` |
| `SERVER_NAME` | No | Friendly server name, seen by users when adding server | `CoMapeo Server` |
| `ALLOWED_PROJECTS` | No | Number of projects allowed to register with the server | `1` |
| `STORAGE_DIR` | No | Path for storing app & project data | `$CWD/data` |
| Environment Variable | Required | Description | Default Value |
| ----------------------------- | -------- | ---------------------------------------------------------------------------------------------------- | ---------------- |
| `SERVER_BEARER_TOKEN` | Yes | Archive-wide token for authenticating API requests. Should be a large random string | |
| `PROJECT_ACCESS_TOKEN_SECRET` | No | Enables project-scoped REST credentials. Must be exactly 32 random bytes encoded as canonical base64 | |
| `PORT` | No | Port on which the server runs | `8080` |
| `SERVER_NAME` | No | Friendly server name, seen by users when adding server | `CoMapeo Server` |
| `ALLOWED_PROJECTS` | No | Number of projects allowed to register with the server | `1` |
| `STORAGE_DIR` | No | Path for storing app & project data | `$CWD/data` |

`SERVER_BEARER_TOKEN` remains the archive-wide credential and can access every bearer-protected REST project route. To enable project-scoped invitations, configure `PROJECT_ACCESS_TOKEN_SECRET` with a separate signing key generated with `openssl rand -base64 32`. The server can then mint a project-only bearer credential through `POST /projects/:projectPublicId/accessTokens`; that credential makes `GET /projects` return only its authorized project and returns the normal project-not-found response for any other project. Rotating the signing key revokes all previously minted project credentials. Project-scoped credentials do not change `/sync/:projectPublicId` or CoMapeo membership/replication semantics.

If you are using Nginx to act as a reverse proxy for your CoMapeo Cloud server, ensure your proxy headers are configured to support WebSockets.

Expand Down
7 changes: 7 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import createFastifyPlugin from 'fastify-plugin'
import allowedHostsPlugin from './allowed-hosts-plugin.js'
import baseUrlPlugin from './base-url-plugin.js'
import comapeoPlugin from './comapeo-plugin.js'
import { decodeProjectTokenKey } from './project-access-token.js'
import routes from './routes.js'

const PROJECT_TOKEN_KEY_ENV = ['PROJECT', 'ACCESS', 'TOKEN', 'SECRET'].join('_')

/** @import { FastifyPluginAsync } from 'fastify' */
/** @import { ComapeoPluginOptions } from './comapeo-plugin.js' */
/** @import { RouteOptions } from './routes.js' */
Expand All @@ -27,11 +30,14 @@ async function comapeoServer(
{
serverBearerToken,
serverName,
projectTokenKey,
allowedHosts,
allowedProjects,
...comapeoPluginOpts
},
) {
projectTokenKey ??= decodeProjectTokenKey(process.env[PROJECT_TOKEN_KEY_ENV])

fastify.register(fastifyWebsocket)
fastify.register(fastifySensible, { sharedSchemaId: 'HttpError' })
fastify.register(allowedHostsPlugin, { allowedHosts })
Expand All @@ -40,6 +46,7 @@ async function comapeoServer(
fastify.register(routes, {
serverBearerToken,
serverName,
projectTokenKey,
allowedProjects,
})
}
Expand Down
14 changes: 14 additions & 0 deletions src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ export const badRequestError = (message) =>
export const invalidBearerToken = () =>
new HttpError(401, 'UNAUTHORIZED', 'Invalid bearer token')

export const projectAccessTokensUnavailable = () =>
new HttpError(
501,
'PROJECT_ACCESS_TOKENS_UNAVAILABLE',
'Project access tokens are not configured on this server',
)

export const archiveCredentialRequired = () =>
new HttpError(
403,
'ARCHIVE_CREDENTIAL_REQUIRED',
'Archive-wide credential required',
)

export const projectNotInAllowlist = () =>
new HttpError(403, 'PROJECT_NOT_IN_ALLOWLIST', 'Project not allowed')

Expand Down
128 changes: 128 additions & 0 deletions src/project-access-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import crypto from 'node:crypto'

const TOKEN_PREFIX = 'cpat1'
const TOKEN_VERSION = 1

/**
* @typedef {object} ProjectAccessTokenPayload
* @prop {1} v
* @prop {string} projectId
* @prop {string} nonce
*/

/**
* @param {Buffer} secret
* @param {string} projectId
* @returns {string}
*/
export function createProjectAccessToken(secret, projectId) {
assertSecret(secret)
const payload = /** @type {ProjectAccessTokenPayload} */ ({
v: TOKEN_VERSION,
projectId,
nonce: crypto.randomBytes(16).toString('base64url'),
})
const encodedPayload = Buffer.from(JSON.stringify(payload)).toString(
'base64url',
)
const signature = sign(secret, encodedPayload).toString('base64url')
return `${TOKEN_PREFIX}.${encodedPayload}.${signature}`
}

/**
* Return the scoped project ID when the token is structurally valid and signed
* by `secret`. Invalid/tampered tokens intentionally collapse to `null` so the
* caller can return the same 401 response as any other invalid bearer token.
*
* @param {Buffer} secret
* @param {string} token
* @returns {string | null}
*/
export function verifyProjectAccessToken(secret, token) {
assertSecret(secret)
const parts = token.split('.')
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX) return null
const encodedPayload = parts[1]
const encodedSignature = parts[2]
if (!encodedPayload || !encodedSignature) return null

let suppliedSignature
try {
suppliedSignature = Buffer.from(encodedSignature, 'base64url')
} catch {
return null
}

const expectedSignature = sign(secret, encodedPayload)
if (
suppliedSignature.toString('base64url') !== encodedSignature ||
suppliedSignature.length !== expectedSignature.length ||
!crypto.timingSafeEqual(suppliedSignature, expectedSignature)
) {
return null
}

let payload
try {
const rawPayload = Buffer.from(encodedPayload, 'base64url').toString('utf8')
payload = JSON.parse(rawPayload)
} catch {
return null
}

if (
!payload ||
typeof payload !== 'object' ||
payload.v !== TOKEN_VERSION ||
typeof payload.projectId !== 'string' ||
payload.projectId.length === 0 ||
typeof payload.nonce !== 'string' ||
payload.nonce.length === 0
) {
return null
}

return payload.projectId
}

/**
* Decode the optional env/config value and enforce exactly 32 random bytes.
* The base64 round-trip check rejects permissive decoder inputs that are not
* actually canonical base64 strings.
*
* @param {string} [value]
* @returns {Buffer | undefined}
*/
export function decodeProjectTokenKey(value) {
if (typeof value === 'undefined') return
if (value.length === 0) {
throw new Error(
'PROJECT_ACCESS_TOKEN_SECRET must be 32 bytes encoded as base64',
)
}

const secret = Buffer.from(value, 'base64')
const canonical = secret.toString('base64')
const normalizedInput = value.replace(/\s+/gu, '')
if (secret.length !== 32 || canonical !== normalizedInput) {
throw new Error(
'PROJECT_ACCESS_TOKEN_SECRET must be 32 bytes encoded as base64',
)
}
return secret
}

/** @param {Buffer} secret */
function assertSecret(secret) {
if (!Buffer.isBuffer(secret) || secret.length !== 32) {
throw new TypeError('Project access token secret must be 32 bytes')
}
}

/**
* @param {Buffer} secret
* @param {string} encodedPayload
*/
function sign(secret, encodedPayload) {
return crypto.createHmac('sha256', secret).update(encodedPayload).digest()
}
Loading
Loading