Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(worker): support Access-protected portal gateways
Timothy Yin41c5dd7408fc
diff --git a/apps/worker/compose.access.yaml b/apps/worker/compose.access.yamlnew file mode 100644index 00000000..5fd92f6f--- /dev/null+++ b/apps/worker/compose.access.yaml@@ -0,0 +1,6 @@+# Optional overlay for a portal protected by Cloudflare Access Service Auth.+# Keep the Cloudflare-issued credentials in a separate private file, outside Git.+services:+ worker:+ env_file:+ - ${CHRONOFRAME_WORKER_ACCESS_ENV_FILE:?Set the path to the private Access credential file}diff --git a/apps/worker/src/gateway.ts b/apps/worker/src/gateway.tsnew file mode 100644index 00000000..305579cf--- /dev/null+++ b/apps/worker/src/gateway.ts@@ -0,0 +1,87 @@+type WorkerAction =+ | 'claim'+ | 'heartbeat'+ | 'grant'+ | 'complete'+ | 'fail'+ | 'cleanup'+interface GatewayConfig {+ origin: string+ secret: string+ accessClientId?: string+ accessClientSecret?: string+}+/** Service credentials belong only on the fixed portal gateway, never on S3 grants. */+export function createWorkerGateway(+ config: GatewayConfig,+ transport: typeof fetch = fetch,+) {+ const {+ origin,+ secret,+ accessClientId = '',+ accessClientSecret = '',+ } = config+ let validOrigin = false+ try {+ const url = new URL(origin)+ validOrigin = url.protocol === 'https:' && url.origin === origin+ } catch {+ /* Report configuration errors without reflecting input values. */+ }+ if (!validOrigin || secret.length < 32)+ throw new Error(+ 'Configure an HTTPS portal origin and generated worker credential',+ )+ if (Boolean(accessClientId) !== Boolean(accessClientSecret))+ throw new Error(+ 'Configure both Cloudflare Access service credentials or neither',+ )+ for (const value of [accessClientId, accessClientSecret]) {+ if (+ value.length > 2048 ||+ Array.from(value).some(+ (char) => char.charCodeAt(0) <= 32 || char.charCodeAt(0) > 126,+ )+ )+ throw new Error('Invalid Cloudflare Access service credential')+ }+ const headers: Record<string, string> = {+ Authorization: 'Bearer ' + secret,+ 'Content-Type': 'application/json',+ ...(accessClientId+ ? {+ 'CF-Access-Client-Id': accessClientId,+ 'CF-Access-Client-Secret': accessClientSecret,+ }+ : {}),+ }+ return async function rpc<T>(+ action: WorkerAction,+ body: unknown,+ signal?: AbortSignal,+ ): Promise<T> {+ if (+ !['claim', 'heartbeat', 'grant', 'complete', 'fail', 'cleanup'].includes(+ action,+ )+ )+ throw new Error('Invalid worker gateway action')+ const response = await transport(+ origin + '/api/internal/worker/' + action,+ {+ method: 'POST',+ redirect: 'error',+ headers,+ body: JSON.stringify(body),+ signal: signal ?? AbortSignal.timeout(30000),+ },+ )+ if (!response.ok) throw new Error('portal_request_failed')+ try {+ return (await response.json()) as T+ } catch {+ throw new Error('portal_response_invalid')+ }+ }+}diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.tsindex f249206e..d5de173d 100644--- a/apps/worker/src/index.ts+++ b/apps/worker/src/index.ts@@ -1,19 +1,15 @@import { randomUUID } from 'node:crypto'+import { createWorkerGateway } from './gateway.ts'import { setTimeout as delay } from 'node:timers/promises'import { processWork, WorkerProcessingError, type WorkItem } from './process.ts'import type { CloudMediaResult } from '@chronoframe/core'-const origin = process.env.CHRONOFRAME_PORTAL_ORIGIN ?? ''-const secret = process.env.CHRONOFRAME_WORKER_SECRET ?? ''const workerId = process.env.CHRONOFRAME_WORKER_ID ?? randomUUID()-if (- !origin ||- new URL(origin).protocol !== 'https:' ||- new URL(origin).origin !== origin ||- secret.length < 32-)- throw new Error(- 'Configure an HTTPS portal origin and generated worker credential',- )+const rpc = createWorkerGateway({+ origin: process.env.CHRONOFRAME_PORTAL_ORIGIN ?? '',+ secret: process.env.CHRONOFRAME_WORKER_SECRET ?? '',+ accessClientId: process.env.CHRONOFRAME_ACCESS_CLIENT_ID,+ accessClientSecret: process.env.CHRONOFRAME_ACCESS_CLIENT_SECRET,+})let stopping = falseconst shutdown = new AbortController()for (const signal of ['SIGINT', 'SIGTERM'] as const)@@ -21,24 +17,6 @@ for (const signal of ['SIGINT', 'SIGTERM'] as const)stopping = trueshutdown.abort()})-async function rpc<T>(- action: string,- body: unknown,- signal?: AbortSignal,-): Promise<T> {- const response = await fetch(origin + '/api/internal/worker/' + action, {- method: 'POST',- redirect: 'error',- headers: {- Authorization: 'Bearer ' + secret,- 'Content-Type': 'application/json',- },- body: JSON.stringify(body),- signal: signal ?? AbortSignal.timeout(30000),- })- if (!response.ok) throw new Error('portal_request_failed')- return response.json() as Promise<T>-}while (!stopping) {try {const item = await rpc<WorkItem | { lease: null }>('claim', { workerId })diff --git a/tests/worker-gateway.test.ts b/tests/worker-gateway.test.tsnew file mode 100644index 00000000..d88c0c94--- /dev/null+++ b/tests/worker-gateway.test.ts@@ -0,0 +1,92 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { createWorkerGateway } from '../apps/worker/src/gateway.ts'++const origin = 'https://staging.portal.example'+const secret = 'fake-worker-credential-'.repeat(3)+test('Worker gateway scopes optional Access credentials to fixed portal actions and forbids redirects', async () => {+ const requests: Request[] = []+ const transport = (async (input, init) => {+ requests.push(new Request(input, init))+ return Response.json({ ok: true })+ }) as typeof fetch+ const rpc = createWorkerGateway(+ {+ origin,+ secret,+ accessClientId: 'test-client.access',+ accessClientSecret: 'test-access-secret',+ },+ transport,+ )+ const controller = new AbortController()+ for (const action of [+ 'claim',+ 'heartbeat',+ 'grant',+ 'complete',+ 'fail',+ 'cleanup',+ ] as const)+ assert.deepEqual(await rpc(action, { test: true }, controller.signal), {+ ok: true,+ })+ for (const request of requests) {+ assert.equal(new URL(request.url).origin, origin)+ assert.equal(request.method, 'POST')+ assert.equal(request.redirect, 'error')+ assert.equal(request.headers.get('authorization'), 'Bearer ' + secret)+ assert.equal(+ request.headers.get('cf-access-client-id'),+ 'test-client.access',+ )+ assert.equal(+ request.headers.get('cf-access-client-secret'),+ 'test-access-secret',+ )+ assert.deepEqual(await request.json(), { test: true })+ }+ await assert.rejects(+ rpc('https://storage.example/key' as any, {}),+ /Invalid worker gateway action/,+ )+ assert.equal(+ requests.length,+ 6,+ 'an invalid action cannot move credentials to another destination',+ )+ const ordinary = createWorkerGateway({ origin, secret }, transport)+ await ordinary('claim', {})+ assert.equal(requests.at(-1)!.headers.has('cf-access-client-secret'), false)+})+test('Gateway rejects incomplete or unsafe credentials and reports fixed transport errors without reflection', async () => {+ for (const config of [+ { origin: 'http://portal.example', secret },+ { origin: 'https://user:[email protected]', secret },+ { origin, secret: 'short' },+ { origin, secret, accessClientId: 'client' },+ { origin, secret, accessClientSecret: 'only-secret' },+ {+ origin,+ secret,+ accessClientId: 'client',+ accessClientSecret: 'bad\nheader',+ },+ ])+ assert.throws(() => createWorkerGateway(config))+ const denied = createWorkerGateway(+ { origin, secret },+ (async () =>+ new Response('private provider detail', { status: 403 })) as typeof fetch,+ )+ await assert.rejects(denied('claim', {}), {+ message: 'portal_request_failed',+ })+ const accessLogin = createWorkerGateway(+ { origin, secret },+ (async () => new Response('<html>Access login</html>')) as typeof fetch,+ )+ await assert.rejects(accessLogin('claim', {}), {+ message: 'portal_response_invalid',+ })+})