diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..aed5c1e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,18 @@ +.git +**/node_modules +**/.next +**/dist +**/.env +**/.env.* +**/.wishforge +**/.data +**/*.log +**/*.pem +**/*.key +**/*.p12 +**/*.tsbuildinfo +**/test-results +**/coverage +apps/ide +infra/oct +**/.DS_Store diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b502b00 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +node_modules/ +.next/ +dist/ +/apps/ide/lib/ +coverage/ +.env +.env.local +.env.*.local +*.tsbuildinfo +.wishforge/ +.data/ +playwright-report/ +test-results/ +.DS_Store +*.log diff --git a/README.md b/README.md index 5651136..2069c54 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,76 @@ -# wishforge-ide -Remote intent-driven IDE with a backend RSI agent loop for implementation and deployment, designed to integrate WorkBuddy, Codex, and other agents +# WishForge + +远程许愿 → 隔离 Agent 实现 → 独立验证 → 不可变产物 → 审批与自动部署。 + +TypeScript 单仓库,包含 Next.js 管理台、NestJS 控制面、PostgreSQL/RLS、Temporal 工作流、Theia 云 IDE、MCP 连接器、Codex/CodeBuddy 适配器、私有 Git/S3 检查点、签名 Runner 和受控 RSI 评估。 + +**当前是可运行的开发版本。** 本地控制面、持久化、IDE、Git、对象存储和发布适配器分别有验证证据;这不代表真实模型、客户 Kubernetes/Kata、生产密钥系统或商业 SLO 已通过验收。未配置的能力会返回明确的等待/未配置状态,不能以 Agent 文本宣布交付成功。 + +本次实现范围、实际测试与未完成条件见 [实施与验收记录](docs/implementation-status-2026-10-17.md)。 + +## 本地启动 + +需要 Node.js 22+、npm、Git 和 Docker Compose。Theia 独立安装与构建,避免主工作区安装时隐式下载完整 IDE。 + +```sh +npm ci --ignore-scripts +npm run setup:local +docker compose -f infra/compose.yaml up -d +npm run db:migrate +npm run db:seed +npm run dev:all +``` + +使用 Colima 时,为 Docker 命令增加 `--context colima`,不用改变全局 Docker context。 + +- 管理台:[http://localhost:3000](http://localhost:3000) +- 控制 API:[http://127.0.0.1:4000/health](http://127.0.0.1:4000/health) +- Temporal:[http://127.0.0.1:8233](http://127.0.0.1:8233) +- 本地 Git:`127.0.0.1:4504`,所有仓库请求需要短期仓库凭据。 + +`setup:local` 生成仅本地使用的随机凭据,文件权限为 0600,已有配置不被重置。管理台不获得数据库、验证器、部署器或签名私钥。开发模式无需把 Bearer Token 粘贴到浏览器;生产必须配置 OIDC,不能启用开发令牌。 + +管理台可以创建项目、连接租户自己的模型凭据、定义保护性验证命令和部署目标、提交/暂停/继续愿望、查看代码与证据、审批具体发布、登记 Runner、查询用量,以及提交内容寻址的 RSI 候选。新项目自动使用平台 Git 存储;已有 HTTPS 仓库可以导入(SSH/SCP 接入未启用)。外部私有仓库还需要其授权接入。 + +## 执行与部署 + +生产任务由显式配置的 Kubernetes/Kata provisioner 启动,每个 run 和 generation 使用独立执行器/验证器工作区和短期身份。验证器从内容校验过的 Git bundle 恢复,不能直接读取仍在运行的 Builder 工作目录。缺少沙箱配置时,任务等待 `sandbox_provisioner`,不会在控制 API 宿主机执行租户代码。 + +配置步骤与环境变量见 [运行手册](docs/operations.md)、[worker](apps/worker/README.md)、[Runner/Kubernetes](infra/k8s/README.md) 和 [私有产物存储](docs/artifact-storage.md)。 + +- Codex 使用官方 SDK;生产通过[模型凭据代理](docs/provider-proxy.md)隔离长期 BYOK,短期令牌绑定任务、代次和租约。CodeBuddy 开发执行器独立配置,生产执行在其凭据隔离协议完成验证前关闭。 +- WorkBuddy 与 Codex 的 MCP 入口见 [connectors](connectors/README.md)。WorkBuddy Cloud 的编码能力维持关闭,直到真实账号完成导出、取消和恢复契约验证。 +- 生产[独立验收配置](docs/verification-profiles.md)由平台安装并固定脚本摘要,仓库测试只作补充;缺少配置时拒绝以仓库自身测试宣布验证通过。 +- [wishforge.yaml](docs/repository-contract.md)从精确 Git SHA 读取;测试只能追加,构建/健康配置须匹配控制面,资源请求不能扩大配额。 +- Release 绑定需求版本、Git SHA、镜像 digest、架构、配置、密钥引用和证据。生产高风险审批只能由交互用户确认。 +- Compose/Kubernetes 适配器进行候选验证与蓝绿切流;Runner 校验 Ed25519 签名、环境身份、过期和重放,未知结果先对账。 +- 生产 S3 必须使用 HTTPS 与 SSE-KMS。[部署密钥](docs/deployment-secrets.md)通过独立 Vault KV v2 broker 解析固定版本,绑定发布策略摘要;缺少配置时拒绝发布,不会忽略引用。 +- [GitHub App 适配器](packages/github/README.md)提供单仓库权限、PR 创建/对账、精确版本合并授权和最终 SHA 重新验证;使用运营侧明确的安装映射,不读取宿主 `gh` 登录缓存。真实 GitHub 账户联调尚待完成。 + +## 云 IDE 与 RSI + +完整 Theia 安装、鉴权网关及隔离协作说明见 [IDE](apps/ide/README.md) 和 [协作](apps/ide/collaboration/README.md)。OCT 房间按 workspace 隔离、经网关检查项目权限;房间状态仍在内存中,重启后需重新创建/加入。保存文件与未确认编辑的恢复能力须按验收表分别核对。 + +[RSI 评估器](packages/evolution/README.md)要求独立 benchmark、执行环境和 Ed25519 签名。候选只能在验证、影子和完整灰度窗口后影响新任务,旧任务继续使用固定 Bundle。客户数据默认不参与平台全局演进,平台代码与信任根升级保留独立发布通道。 + +元循环支持一次显式 `tick`:聚合平台自身失败、冻结来源和基线、使用平台专属预算生成候选,再由独立验证器提取。默认不安装定时任务、不运行模型;需要运营者配置系统租户、项目、执行环境和评估语料。 + +提示词与编排候选按固定 Bundle 评估;工具和平台代码生成绑定精确检查点的源代码提案。平台代码的灰度与回滚必须收到独立发布系统的签名回执,首版晋升仍需维护者确认。`npm run rsi:rollout` 提供显式晋升检查,配置缺失时不执行。 + +已实现[工作区保存交接](docs/workspace-handoff.md)、[租户 IDE 网关路由](docs/runbooks/tenant-ide-gateways.md)、[工作区休眠与恢复](docs/runbooks/workspace-lifecycle.md),以及[套餐、资源授权和账单导出](docs/billing-entitlements.md)。未接入的 CPU/存储时长计量显示为未知,人工结算记录不触发真实扣款。 + +## 检查与验收 + +```sh +npm run typecheck +npm test +npm run test:integration +npm run test:ide +npm run test:preview +npm run build +node scripts/smoke-control.mjs +``` + +网络/容器集成测试需要本机监听权限。Temporal、MinIO、真实 Compose 和浏览器验收有独立执行开关,见 [需求与验收追踪](docs/acceptance-traceability.md);默认跳过这些测试不等于通过。 + +[系统设计](docs/system-design.md) · [界面与浏览器验证](docs/ui-design.md) · [运行手册](docs/operations.md) · [备份恢复](docs/recovery.md) · [观测](docs/observability.md) diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..1dfaf2a --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1 @@ +{"name":"@wishforge/api","version":"0.1.0","private":true,"type":"module","scripts":{"dev":"tsx watch --env-file=../../.env.local src/main.ts","start":"tsx src/main.ts","typecheck":"tsc --noEmit","build":"tsc --noEmit"},"dependencies":{"@modelcontextprotocol/sdk":"^1.26.0","@nestjs/common":"^12.1.3","@nestjs/core":"^12.1.3","@nestjs/platform-express":"^12.1.3","@opentelemetry/api":"1.9.1","@opentelemetry/exporter-trace-otlp-http":"0.223.0","@opentelemetry/sdk-node":"0.223.0","@prometheus-io/client":"0.16.1","@temporalio/client":"^1.13.0","@wishforge/contracts":"*","jose":"^6.0.0","pg":"^8.16.0","reflect-metadata":"^0.2.2","rxjs":"^7.8.2","zod":"^3.25.0"},"devDependencies":{"@types/express":"^5.0.0"}} \ No newline at end of file diff --git a/apps/api/src/audit-context.ts b/apps/api/src/audit-context.ts new file mode 100644 index 0000000..49c2835 --- /dev/null +++ b/apps/api/src/audit-context.ts @@ -0,0 +1,2 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +export const auditContext = new AsyncLocalStorage<{ actorId: string }>(); diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts new file mode 100644 index 0000000..75d8281 --- /dev/null +++ b/apps/api/src/auth.ts @@ -0,0 +1,62 @@ +import {resolveGatewayTarget} from './domain/gateway-target.js'; +import { createRemoteJWKSet, jwtVerify } from 'jose'; +import { DomainError, type Actor } from '@wishforge/contracts'; +import { sameSecret } from './domain/policy.js'; +import type { Store } from './db/store.js'; +import { ServiceTokens } from './service-tokens.js'; + +export class Authenticator { + private jwks; + constructor(private store: Store, private env = process.env) { + if (env.OIDC_ISSUER) { + let issuer: URL; + try { issuer = new URL(env.OIDC_ISSUER); } catch { throw new Error('OIDC issuer URL is invalid'); } + if (issuer.username || issuer.password || issuer.search || issuer.hash || !['https:', 'http:'].includes(issuer.protocol) || (env.NODE_ENV === 'production' && issuer.protocol !== 'https:')) throw new Error('OIDC issuer must be HTTPS in production and contain no credentials, query or fragment'); + this.jwks = createRemoteJWKSet(new URL(`${env.OIDC_ISSUER.replace(/\/$/, '')}/protocol/openid-connect/certs`)); + } + if (env.NODE_ENV === 'production' && env.WF_DEV_AUTH_TOKEN) throw new Error('Development authentication cannot be configured in production'); + } + async authenticate(authorization?: string): Promise { + if (!authorization?.startsWith('Bearer ')) throw new DomainError('UNAUTHENTICATED', 'Sign in to continue', 401); + const token = authorization.slice(7); + if (this.env.NODE_ENV !== 'production' && this.env.WF_DEV_AUTH_TOKEN && sameSecret(token, this.env.WF_DEV_AUTH_TOKEN)) { + return this.member('demo', '11111111-1111-4111-8111-111111111111', 'human', 'wishforge-web'); + } + if (!this.jwks || !this.env.OIDC_ISSUER || !this.env.OIDC_AUDIENCE) throw new DomainError('UNAUTHENTICATED', 'OIDC is not configured', 401); + try { + const { payload } = await jwtVerify(token, this.jwks, { issuer: this.env.OIDC_ISSUER, audience: this.env.OIDC_AUDIENCE, algorithms: ['RS256', 'ES256'] }); + if (typeof payload.sub !== 'string' || typeof payload.tenant_id !== 'string' || typeof payload.exp !== 'number' || !Number.isFinite(payload.exp) || payload.exp * 1000 <= Date.now()) throw new Error('Missing identity claims'); + const clientId = typeof payload.azp === 'string' ? payload.azp : undefined; + return { ...await this.member(payload.tenant_id, payload.sub, clientId === this.env.WF_WEB_CLIENT_ID ? 'human' : 'connector', clientId), authExpiresAt: payload.exp * 1000 }; + } catch (error) { + if (error instanceof DomainError) throw error; + throw new DomainError('UNAUTHENTICATED', 'Access token is invalid or expired', 401); + } + } + private async member(tenantId: string, userId: string, kind: Actor['kind'], clientId?: string): Promise { + const role = await this.store.transaction(tenantId, tx => tx.membership(userId)); + if (!role) throw new DomainError('FORBIDDEN', 'Tenant membership is missing or revoked', 403); + return { tenantId, userId, role, kind, clientId }; + } + async internal(authorization: string | undefined, tenant: string | undefined): Promise { + if (!tenant || !(this.env.WF_DISPATCH_TENANTS ?? '').split(',').includes(tenant)) throw new DomainError('FORBIDDEN', 'Service identity is not assigned to this tenant', 403); + const token = authorization?.startsWith('Bearer ') ? authorization.slice(7) : ''; + const scoped = await new ServiceTokens(this.env.WF_INTERNAL_TOKEN_KEY).verify(token); + if (scoped && scoped.tenantId === tenant) { + const run = await this.store.transaction(tenant, tx => tx.get('run', scoped.runId!)); + if (run && run.executionGeneration === scoped.credentialId && !['paused', 'canceled', 'succeeded', 'failed'].includes(String(run.status))) return scoped; + throw new DomainError('UNAUTHENTICATED', 'Execution credential was revoked or superseded', 401); + } + const gateway=await resolveGatewayTarget(this.env,tenant);if(gateway&&sameSecret(token,gateway.token))return{tenantId:tenant,userId:'workspace-gateway',role:'admin',kind:'worker'}; + for (const [name, kind] of [['WF_WORKER_TOKEN', 'worker'], ['WF_VERIFIER_TOKEN', 'verifier'], ['WF_DEPLOYER_TOKEN', 'deployer'], ['WF_EVALUATOR_TOKEN', 'evaluator']] as const) { + if (this.env[name] && sameSecret(token, this.env[name]!)) return { tenantId: tenant, userId: kind, role: 'admin', kind }; + } + const { createHash } = await import('node:crypto'); + if (token.length >= 32) { + const hash = createHash('sha256').update(token).digest('hex'); + const registration = await this.store.transaction(tenant, async tx => (await tx.list('runner')).find(r => r.tokenHash === hash && r.status === 'active')); + if (registration) return { tenantId: tenant, userId: `runner:${registration.environmentId}`, role: 'deployer', kind: 'deployer', clientId: registration.id }; + } + throw new DomainError('UNAUTHENTICATED', 'Invalid service identity', 401); + } +} diff --git a/apps/api/src/db/001_initial.sql b/apps/api/src/db/001_initial.sql new file mode 100644 index 0000000..1f4e6c4 --- /dev/null +++ b/apps/api/src/db/001_initial.sql @@ -0,0 +1,80 @@ +CREATE TABLE IF NOT EXISTS tenants ( + id text PRIMARY KEY, name text NOT NULL, region text NOT NULL, + max_concurrent_runs integer NOT NULL DEFAULT 2 CHECK(max_concurrent_runs>0), + token_limit bigint NOT NULL DEFAULT 2000000 CHECK(token_limit>=0) +); +CREATE TABLE IF NOT EXISTS memberships ( + tenant_id text NOT NULL REFERENCES tenants(id), user_id text NOT NULL, + role text NOT NULL CHECK(role IN ('owner','admin','developer','deployer','viewer')), + active boolean NOT NULL DEFAULT true, PRIMARY KEY(tenant_id,user_id) +); +CREATE TABLE IF NOT EXISTS entities ( + tenant_id text NOT NULL REFERENCES tenants(id), kind text NOT NULL, id text NOT NULL, + version integer NOT NULL CHECK(version>0), data jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(tenant_id,kind,id), + CHECK(data->>'tenantId'=tenant_id AND data->>'id'=id) +); +CREATE INDEX IF NOT EXISTS entities_by_project ON entities(tenant_id,kind,(data->>'projectId')); +CREATE INDEX IF NOT EXISTS entities_by_run_status ON entities(tenant_id,kind,(data->>'status')); +CREATE TABLE IF NOT EXISTS run_events ( + tenant_id text NOT NULL REFERENCES tenants(id), id text NOT NULL, run_id text NOT NULL, + seq bigint NOT NULL, event jsonb NOT NULL, PRIMARY KEY(tenant_id,run_id,seq), UNIQUE(tenant_id,id) +); +CREATE TABLE IF NOT EXISTS idempotency ( + tenant_id text NOT NULL REFERENCES tenants(id), key text NOT NULL, digest text NOT NULL, + response jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(tenant_id,key) +); +CREATE TABLE IF NOT EXISTS outbox ( + tenant_id text NOT NULL REFERENCES tenants(id), id text NOT NULL, type text NOT NULL, + payload jsonb NOT NULL, attempts integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(), + delivered_at timestamptz, PRIMARY KEY(tenant_id,id) +); +CREATE INDEX IF NOT EXISTS outbox_pending ON outbox(tenant_id,created_at) WHERE delivered_at IS NULL; +ALTER TABLE outbox ADD COLUMN IF NOT EXISTS next_attempt_at timestamptz NOT NULL DEFAULT now(); +CREATE TABLE IF NOT EXISTS usage_ledger ( + tenant_id text NOT NULL REFERENCES tenants(id), id text NOT NULL, run_id text, + tokens bigint NOT NULL DEFAULT 0 CHECK(tokens>=0), compute_seconds double precision NOT NULL DEFAULT 0 CHECK(compute_seconds>=0), + storage_bytes bigint NOT NULL DEFAULT 0 CHECK(storage_bytes>=0), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(tenant_id,id) +); +CREATE INDEX IF NOT EXISTS usage_by_period ON usage_ledger(tenant_id,created_at); +CREATE TABLE IF NOT EXISTS audit_events ( + id bigserial PRIMARY KEY, tenant_id text NOT NULL REFERENCES tenants(id), + actor_id text NOT NULL, entity_kind text NOT NULL, entity_id text NOT NULL, + operation text NOT NULL, entity_version integer NOT NULL, created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS audit_tenant_time ON audit_events(tenant_id,created_at DESC); +CREATE OR REPLACE FUNCTION public.audit_entity_change() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public AS $$ +BEGIN + IF TG_OP='DELETE' THEN + INSERT INTO public.audit_events(tenant_id,actor_id,entity_kind,entity_id,operation,entity_version) VALUES(OLD.tenant_id,COALESCE(NULLIF(current_setting('app.actor_id',true),''),'operator'),OLD.kind,OLD.id,TG_OP,OLD.version); + RETURN OLD; + ELSE + INSERT INTO public.audit_events(tenant_id,actor_id,entity_kind,entity_id,operation,entity_version) VALUES(NEW.tenant_id,COALESCE(NULLIF(current_setting('app.actor_id',true),''),'operator'),NEW.kind,NEW.id,TG_OP,NEW.version); + RETURN NEW; + END IF; +END $$; +DROP TRIGGER IF EXISTS entities_audit ON entities; +CREATE TRIGGER entities_audit AFTER INSERT OR UPDATE OR DELETE ON entities FOR EACH ROW EXECUTE FUNCTION public.audit_entity_change(); +DO $$ DECLARE t text; BEGIN + FOREACH t IN ARRAY ARRAY['memberships','entities','run_events','idempotency','outbox','usage_ledger','audit_events'] LOOP + EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY',t); + EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY',t); + IF NOT EXISTS(SELECT 1 FROM pg_policies WHERE tablename=t AND policyname='tenant_isolation') THEN + EXECUTE format('CREATE POLICY tenant_isolation ON %I USING(tenant_id=(SELECT current_setting(''app.tenant_id'',true))) WITH CHECK(tenant_id=(SELECT current_setting(''app.tenant_id'',true)))',t); + END IF; + END LOOP; +END $$; +ALTER TABLE tenants ENABLE ROW LEVEL SECURITY; +ALTER TABLE tenants FORCE ROW LEVEL SECURITY; +DO $$ BEGIN + IF NOT EXISTS(SELECT 1 FROM pg_policies WHERE tablename='tenants' AND policyname='tenant_isolation') THEN + CREATE POLICY tenant_isolation ON tenants USING(id=(SELECT current_setting('app.tenant_id',true))) WITH CHECK(id=(SELECT current_setting('app.tenant_id',true))); + END IF; +END $$; + +-- Backward-compatible pilot entitlements. Existing tenants remain explicitly legacy. +ALTER TABLE tenants ADD COLUMN IF NOT EXISTS plan_id text NOT NULL DEFAULT 'legacy'; +ALTER TABLE tenants ADD COLUMN IF NOT EXISTS plan_version text NOT NULL DEFAULT 'legacy-v1'; +ALTER TABLE tenants ADD COLUMN IF NOT EXISTS entitlements jsonb; +ALTER TABLE usage_ledger ADD COLUMN IF NOT EXISTS measurement_source text NOT NULL DEFAULT 'legacy'; +ALTER TABLE usage_ledger ADD COLUMN IF NOT EXISTS measured_dimensions jsonb NOT NULL DEFAULT '[]'::jsonb; diff --git a/apps/api/src/db/migrate.ts b/apps/api/src/db/migrate.ts new file mode 100644 index 0000000..40dd749 --- /dev/null +++ b/apps/api/src/db/migrate.ts @@ -0,0 +1,28 @@ +import pg from 'pg'; +import { readFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; + +export async function migrate(url: string, appPassword: string) { + if (!appPassword || appPassword.length < 16) throw new Error('WF_DATABASE_APP_PASSWORD must be at least 16 characters'); + const c = new pg.Client({ connectionString: url }); await c.connect(); + try { + await c.query('BEGIN'); + await c.query('SELECT pg_advisory_xact_lock(9184721)'); + await c.query(await readFile(new URL('./001_initial.sql', import.meta.url), 'utf8')); + await c.query("DO $$ BEGIN IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='wishforge_app') THEN CREATE ROLE wishforge_app LOGIN NOSUPERUSER NOBYPASSRLS; END IF; END $$"); + // Password is supplied out of band and escaped as a SQL literal, never logged. + await c.query(`ALTER ROLE wishforge_app PASSWORD '${appPassword.replaceAll("'", "''")}'`); + await c.query('GRANT USAGE ON SCHEMA public TO wishforge_app'); + await c.query('REVOKE CREATE ON SCHEMA public FROM PUBLIC'); + await c.query('GRANT SELECT,INSERT,UPDATE,DELETE ON tenants,memberships,entities,run_events,idempotency,outbox,usage_ledger TO wishforge_app'); + await c.query('REVOKE INSERT,UPDATE,DELETE ON tenants FROM wishforge_app'); + await c.query('GRANT SELECT ON audit_events TO wishforge_app'); + await c.query('REVOKE INSERT,UPDATE,DELETE,TRUNCATE ON audit_events FROM wishforge_app'); + await c.query('COMMIT'); + } catch (error) { await c.query('ROLLBACK'); throw error; } finally { await c.end(); } +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (process.env.NODE_ENV !== 'production') { try { process.loadEnvFile('.env.local'); } catch {} } + await migrate(process.env.DATABASE_ADMIN_URL ?? '', process.env.WF_DATABASE_APP_PASSWORD ?? ''); + console.log('Database migration applied; runtime role enforces RLS.'); +} diff --git a/apps/api/src/db/seed.ts b/apps/api/src/db/seed.ts new file mode 100644 index 0000000..5b2f704 --- /dev/null +++ b/apps/api/src/db/seed.ts @@ -0,0 +1,10 @@ +import pg from 'pg'; +if (process.env.NODE_ENV === 'production') throw new Error('Development seed is disabled in production'); +try { process.loadEnvFile('.env.local'); } catch {} +const c = new pg.Client({ connectionString: process.env.DATABASE_ADMIN_URL }); +await c.connect(); +try { + await c.query("INSERT INTO tenants(id,name,region) VALUES('demo','Local workspace',$1) ON CONFLICT(id) DO NOTHING", [process.env.WF_REGION ?? 'local']); + await c.query("INSERT INTO memberships(tenant_id,user_id,role) VALUES('demo','11111111-1111-4111-8111-111111111111','owner') ON CONFLICT DO NOTHING"); + console.log('Local tenant and owner seeded. No projects, runs, evidence or deployments are fabricated.'); +} finally { await c.end(); } diff --git a/apps/api/src/db/store.ts b/apps/api/src/db/store.ts new file mode 100644 index 0000000..4e0fd12 --- /dev/null +++ b/apps/api/src/db/store.ts @@ -0,0 +1,86 @@ +import { randomUUID } from 'node:crypto'; +import pg from 'pg'; +import type { Entity, EntityKind, Role, RunEvent, TenantEntitlementSnapshot } from '@wishforge/contracts'; +import { auditContext } from '../audit-context.js'; + +export interface Tenant { id: string; name: string; maxConcurrentRuns: number; tokenLimit: number; region: string; planId?: string; planVersion?: string; entitlements?: TenantEntitlementSnapshot | null } +export interface Meter { id: string; runId?: string; tokens: number; computeSeconds: number; storageBytes: number; at: string; source?: 'provider_proxy' | 'artifact_service' | 'executor_reported' | 'legacy'; measuredDimensions?: string[] } +export interface Membership { userId: string; role: Role; active: boolean } +export function normalizeMeter(entry: Meter): Meter { const source = entry.source ?? (entry.id.startsWith('provider-proxy:') ? 'provider_proxy' : entry.id.startsWith('storage:artifact-') ? 'artifact_service' : 'executor_reported'); return { ...entry, source, measuredDimensions: entry.measuredDimensions ?? (source === 'provider_proxy' ? ['model_tokens'] : source === 'artifact_service' ? ['artifact_bytes_added'] : []) }; } +export interface OutboxItem { id: string; type: string; payload: Record; attempts: number } +export interface Transaction { + tenant(): Promise; + membership(userId: string): Promise; + members(): Promise; + putMembership(member: Membership): Promise; + get(kind: EntityKind, id: string): Promise; + list(kind: EntityKind): Promise; + put(kind: EntityKind, value: Entity): Promise; + event(runId: string, type: string, message: string, data?: Record): Promise; + events(runId: string, after?: number): Promise; + idempotency(key: string): Promise<{ digest: string; response: unknown } | undefined>; + remember(key: string, digest: string, response: unknown): Promise; + enqueue(type: string, payload: Record, id?: string): Promise; + outbox(): Promise; + acknowledge(id: string): Promise; + defer(id: string, seconds: number): Promise; + meter(entry: Meter): Promise; + usage(since: string): Promise; +} +export interface Store { transaction(tenantId: string, work: (tx: Transaction) => Promise): Promise; close(): Promise } + +export class PgStore implements Store { + readonly pool: pg.Pool; + constructor(url: string) { this.pool = new pg.Pool({ connectionString: url, max: 15, connectionTimeoutMillis: 5000, idleTimeoutMillis: 30000 }); } + async assertSafeRole() { + const result = await this.pool.query('SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname=current_user'); + if (result.rows[0]?.rolsuper || result.rows[0]?.rolbypassrls) throw new Error('DATABASE_URL must use a non-superuser, NOBYPASSRLS application role. Run db:migrate first.'); + } + async transaction(tenantId: string, work: (tx: Transaction) => Promise): Promise { + const c = await this.pool.connect(); + try { + await c.query('BEGIN'); + await c.query("SELECT set_config('app.tenant_id',$1,true), set_config('statement_timeout','10000',true)", [tenantId]); + await c.query("SELECT set_config('app.actor_id',$1,true)", [auditContext.getStore()?.actorId ?? 'platform']); + // Serializes tenant quota/state changes, never external network or model work. + await c.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))', [tenantId]); + const value = await work(new PgTransaction(c, tenantId)); + await c.query('COMMIT'); + return value; + } catch (error) { await c.query('ROLLBACK'); throw error; } + finally { c.release(); } + } + async close() { await this.pool.end(); } +} + +class PgTransaction implements Transaction { + constructor(private c: pg.PoolClient, private tenantId: string) {} + async tenant(): Promise { + const { rows } = await this.c.query('SELECT id,name,max_concurrent_runs AS "maxConcurrentRuns",token_limit AS "tokenLimit",region,plan_id AS "planId",plan_version AS "planVersion",entitlements FROM tenants WHERE id=$1', [this.tenantId]); + if (!rows[0]) throw new Error('Tenant does not exist'); + return { ...rows[0], tokenLimit: Number(rows[0].tokenLimit) }; + } + async membership(userId: string) { const r = await this.c.query('SELECT role FROM memberships WHERE tenant_id=$1 AND user_id=$2 AND active=true', [this.tenantId, userId]); return r.rows[0]?.role as Role | undefined; } + async members(): Promise { const result = await this.c.query('SELECT user_id AS "userId",role,active FROM memberships WHERE tenant_id=$1 ORDER BY user_id', [this.tenantId]); return result.rows; } + async putMembership(member: Membership) { await this.c.query('INSERT INTO memberships(tenant_id,user_id,role,active) VALUES($1,$2,$3,$4) ON CONFLICT(tenant_id,user_id) DO UPDATE SET role=EXCLUDED.role,active=EXCLUDED.active', [this.tenantId, member.userId, member.role, member.active]); } + async get(kind: EntityKind, id: string): Promise { const r = await this.c.query('SELECT data FROM entities WHERE tenant_id=$1 AND kind=$2 AND id=$3', [this.tenantId, kind, id]); return r.rows[0]?.data; } + async list(kind: EntityKind): Promise { const r = await this.c.query('SELECT data FROM entities WHERE tenant_id=$1 AND kind=$2 ORDER BY created_at DESC', [this.tenantId, kind]); return r.rows.map(x => x.data); } + async put(kind: EntityKind, value: Entity) { + if (value.tenantId !== this.tenantId) throw new Error('Tenant mismatch'); + await this.c.query('INSERT INTO entities(tenant_id,kind,id,version,data,created_at) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_id,kind,id) DO UPDATE SET version=EXCLUDED.version,data=EXCLUDED.data', [this.tenantId, kind, value.id, value.version, value, value.createdAt]); + } + async event(runId: string, type: string, message: string, data?: Record): Promise { + const event = { id: randomUUID(), runId, type, message, time: new Date().toISOString(), data }; + const { rows } = await this.c.query('INSERT INTO run_events(tenant_id,id,run_id,seq,event) SELECT $1,$2,$3,COALESCE(MAX(seq),0)+1,$4 FROM run_events WHERE tenant_id=$1 AND run_id=$3 RETURNING seq', [this.tenantId, event.id, runId, event]); + return { ...event, seq: Number(rows[0].seq) }; + } + async events(runId: string, after = 0): Promise { const r = await this.c.query('SELECT seq,event FROM run_events WHERE tenant_id=$1 AND run_id=$2 AND seq>$3 ORDER BY seq LIMIT 1000', [this.tenantId, runId, after]); return r.rows.map(x => ({ ...x.event, seq: Number(x.seq) })); } + async idempotency(key: string) { const r = await this.c.query('SELECT digest,response FROM idempotency WHERE tenant_id=$1 AND key=$2', [this.tenantId, key]); return r.rows[0]; } + async remember(key: string, digest: string, response: unknown) { await this.c.query('INSERT INTO idempotency(tenant_id,key,digest,response) VALUES($1,$2,$3,$4)', [this.tenantId, key, digest, JSON.stringify(response)]); } + async enqueue(type: string, payload: Record, id = randomUUID()) { await this.c.query('INSERT INTO outbox(tenant_id,id,type,payload) VALUES($1,$2,$3,$4) ON CONFLICT(tenant_id,id) DO NOTHING', [this.tenantId, id, type, payload]); } + async outbox(): Promise { const r = await this.c.query("SELECT id,type,payload,attempts FROM outbox WHERE tenant_id=$1 AND delivered_at IS NULL AND next_attempt_at<=now() AND type IN ('run.start','run.signal','workspace.provision','workspace.reconcile') ORDER BY CASE WHEN type='run.signal' THEN 0 WHEN type='workspace.reconcile' THEN 1 ELSE 2 END,created_at LIMIT 50", [this.tenantId]); return r.rows; } + async acknowledge(id: string) { await this.c.query('UPDATE outbox SET delivered_at=now() WHERE tenant_id=$1 AND id=$2', [this.tenantId, id]); } + async defer(id: string, seconds: number) { await this.c.query("UPDATE outbox SET attempts=attempts+1,next_attempt_at=now()+$3*interval '1 second' WHERE tenant_id=$1 AND id=$2", [this.tenantId,id,seconds]); } + async meter(entry: Meter) { const measured = normalizeMeter(entry); await this.c.query('INSERT INTO usage_ledger(tenant_id,id,run_id,tokens,compute_seconds,storage_bytes,created_at,measurement_source,measured_dimensions) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT(tenant_id,id) DO NOTHING', [this.tenantId, entry.id, entry.runId, entry.tokens, entry.computeSeconds, entry.storageBytes, entry.at, measured.source, JSON.stringify(measured.measuredDimensions)]); } + async usage(since: string): Promise { const r = await this.c.query('SELECT id,run_id AS "runId",tokens,compute_seconds AS "computeSeconds",storage_bytes AS "storageBytes",created_at AS at,measurement_source AS source,measured_dimensions AS "measuredDimensions" FROM usage_ledger WHERE tenant_id=$1 AND created_at >= $2 ORDER BY created_at,id', [this.tenantId, since]); return r.rows.map(x => ({ ...x, at: new Date(x.at).toISOString(), tokens: Number(x.tokens), storageBytes: Number(x.storageBytes), computeSeconds: Number(x.computeSeconds) })); } +} diff --git a/apps/api/src/dispatcher.ts b/apps/api/src/dispatcher.ts new file mode 100644 index 0000000..7eb8495 --- /dev/null +++ b/apps/api/src/dispatcher.ts @@ -0,0 +1,91 @@ +import {resolveGatewayTarget} from './domain/gateway-target.js'; +import { Client, Connection, WorkflowIdReusePolicy } from '@temporalio/client'; +import type { ControlPlane } from './domain/control-plane.js'; +import { ServiceTokens } from './service-tokens.js'; +import { must, touch } from './domain/control-plane.js'; +import { DomainError, type Run } from '@wishforge/contracts'; +import { reserveExecutionGrant, recordAllocation } from './domain/entitlements.js'; +import { resolveProvisionerTarget, type ProvisionerTarget } from './domain/provisioner-target.js'; + +/** At-least-once outbox delivery; workflow IDs deduplicate starts after an ambiguous response. */ +export class Dispatcher { + private stopped = false; + private connection?: Connection; + constructor(private control: ControlPlane) {} + async start() { + while (!this.stopped) { + try { + this.connection ??= await Connection.connect({ address: this.control.env.TEMPORAL_ADDRESS ?? '127.0.0.1:7233' }); + const client = new Client({ connection: this.connection, namespace: this.control.env.TEMPORAL_NAMESPACE ?? 'default' }); + for (const tenant of (this.control.env.WF_DISPATCH_TENANTS ?? '').split(',').map(value => value.trim()).filter(Boolean)) { + // Tenant configuration failures must not tear down Temporal or prevent + // cancellation signals for already-running work. + let provisioner: ProvisionerTarget | undefined; + let provisionerError: unknown; + try { provisioner = await resolveProvisionerTarget(this.control.env, tenant); } + catch (error) { provisionerError = error; } + const pending = await this.control.store.transaction(tenant, tx => tx.outbox()); + for (const item of pending) { + if (item.type === 'workspace.provision') { + try { + if (provisionerError) throw provisionerError; + const gateway=await resolveGatewayTarget(this.control.env,tenant);if(!gateway){await this.control.store.transaction(tenant,tx=>tx.defer(item.id,60));continue;} + const currentWorkspace=await this.control.store.transaction(tenant,tx=>must(tx,'workspace',String(item.payload.workspaceId))); + if(currentWorkspace.lifecycle){await this.control.store.transaction(tenant,tx=>tx.acknowledge(item.id));continue;} + if (!provisioner) { await this.control.store.transaction(tenant, tx => tx.defer(item.id, 60)); continue; } + const response = await fetch(`${provisioner.url}/workspaces`, { method: 'POST', headers: { Authorization: `Bearer ${provisioner.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ tenantId: tenant, projectId: item.payload.projectId, workspaceId: item.payload.workspaceId }), signal: AbortSignal.timeout(30000) }); + if (!response.ok) throw new Error('WorkspaceProvisioningFailed'); + const state = await response.json() as { status: 'ready' | 'pending'; upstreamUrl: string; collaborationUpstreamUrl?: string }; + if (!['ready', 'pending'].includes(state.status)) throw new Error('InvalidWorkspaceReceipt'); + await this.control.store.transaction(tenant, async tx => { const w = await must(tx, 'workspace', String(item.payload.workspaceId)); if(w.lifecycle){await tx.acknowledge(item.id);return;} w.managedBy='wishforge-provisioner'; if(state.status==='ready')w.lastActivityAt=new Date().toISOString(); w.status = state.status === 'ready' ? 'ready' : 'requested'; w.reason = state.status === 'ready' ? undefined : 'Waiting for the isolated Theia instance to become ready.'; if (state.status === 'ready') { const target = new URL(state.upstreamUrl); if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error('InvalidWorkspaceTarget'); w.upstreamUrl = target.toString(); if (state.collaborationUpstreamUrl) { const collaboration = new URL(state.collaborationUpstreamUrl); if (collaboration.hostname !== target.hostname || collaboration.port !== '8100' || collaboration.username || collaboration.password || collaboration.pathname !== '/' || collaboration.search || collaboration.hash) throw new Error('InvalidCollaborationTarget'); w.collaborationUpstreamUrl = collaboration.toString(); } w.url = `${gateway.publicUrl}/workspaces/${w.id}/`; await tx.acknowledge(item.id); } await tx.put('workspace', touch(w)); }); + if (state.status === 'pending') await this.control.store.transaction(tenant, tx => tx.defer(item.id, 15)); + } catch (error) { await this.control.store.transaction(tenant, tx => tx.defer(item.id, 60)); console.error(`Workspace provisioning pending: ${error instanceof Error ? error.name : 'failure'}`); } + continue; + } + if (item.type !== 'run.start' && item.type !== 'run.signal') continue; + const workflowId = `wishforge:${tenant}:${String(item.payload.runId)}`; + try { + if (item.type === 'run.start') { + const runId = String(item.payload.runId); + const run = await this.control.store.transaction(tenant, tx => must(tx, 'run', runId)); + if (run.pendingStartId && run.pendingStartId !== item.id) { await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id)); continue; } + if (['canceled', 'failed', 'succeeded', 'paused'].includes(run.status)) { await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id)); continue; } + if (Number(item.payload.revision) !== run.revision) { await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id)); continue; } + const provisioningReasons = ['sandbox_provisioner','resource_signer_unconfigured','runtime_image_unconfigured','runtime_image_migration_required','resource_configuration_invalid','resource_plan_changed','resource_previous_generation']; + if (run.status === 'waiting' && run.executionGeneration === item.id && !provisioningReasons.includes(run.waitingReason ?? '')) { await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id)); continue; } + if (provisionerError) throw provisionerError; + if (!provisioner) { + await this.control.store.transaction(tenant, async tx => { const current = await must(tx, 'run', runId); if (current.waitingReason !== 'sandbox_provisioner') { current.status = 'waiting'; current.waitingReason = 'sandbox_provisioner'; await tx.put('run', touch(current)); await tx.event(runId, 'run.waiting', 'An isolated per-run sandbox provisioner must be connected before execution.'); } }); + await this.control.store.transaction(tenant, tx => tx.defer(item.id, 60)); + continue; + } + const tokens = new ServiceTokens(this.control.env.WF_INTERNAL_TOKEN_KEY); + const resourceGrant = await this.control.store.transaction(tenant, tx => reserveExecutionGrant(tx, runId, item.id, this.control.env)); + let provision: Response; + try { provision = await fetch(`${provisioner.url}/runs`, { method: 'POST', headers: { Authorization: `Bearer ${provisioner.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ tenantId: tenant, runId, generation: item.id, resourceGrant, executorToken: await tokens.issue(tenant, runId, 'worker', item.id), verifierToken: await tokens.issue(tenant, runId, 'verifier', item.id) }), signal: AbortSignal.timeout(15000) }); } + catch { await this.control.store.transaction(tenant, tx => recordAllocation(tx, runId, item.id, 'unknown')); throw new Error('SandboxProvisioningUnknown'); } + if (!provision.ok) { const body = await provision.json().catch(()=>({})) as {error?:string}; await this.control.store.transaction(tenant, tx => recordAllocation(tx, runId, item.id, 'unknown')); if (body.error === 'RUNTIME_IMAGE_MIGRATION_REQUIRED') throw new DomainError('RUNTIME_IMAGE_MIGRATION_REQUIRED','Pinned runtime image is outside the provisioner current/previous allowlist; authorize checkpoint migration'); throw new Error('SandboxProvisioningFailed'); } + const receipt = await provision.json() as { status: string; tenantId: string; runId: string; generation: string }; + if (receipt.tenantId !== tenant || receipt.runId !== runId || receipt.generation !== item.id) { await this.control.store.transaction(tenant, tx => recordAllocation(tx, runId, item.id, 'unknown')); throw new Error('SandboxReceiptScopeMismatch'); } + if (receipt.status !== 'provisioned') { await this.control.waitRun({ tenantId: tenant, userId: 'worker', role: 'admin', kind: 'worker' }, runId, 'sandbox_failed: the prior sandbox attempt ended; resume explicitly to create a new generation.', item.id); await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id)); continue; } + await this.control.store.transaction(tenant, tx => recordAllocation(tx, runId, item.id, 'provisioned')); + if (run.status === 'waiting' && provisioningReasons.includes(run.waitingReason ?? '')) await this.control.store.transaction(tenant, async tx => { const current = await must(tx, 'run', runId); if (current.status === 'waiting' && provisioningReasons.includes(current.waitingReason ?? '')) { current.status = 'queued'; current.waitingReason = undefined; await tx.put('run', touch(current)); } }); + await client.workflow.signalWithStart('runWorkflow', { workflowId, taskQueue: 'wishforge-runs', args: [{ tenantId: tenant, runId: item.payload.runId, generation: item.id }], signal: 'resume', signalArgs: [{ generation: item.id }], workflowIdReusePolicy: WorkflowIdReusePolicy.ALLOW_DUPLICATE }); + } else if (item.payload.action === 'cancel' || item.payload.action === 'pause') { + try { await client.workflow.getHandle(workflowId).cancel(); } catch (error) { if (!(error instanceof Error && error.name === 'WorkflowNotFoundError')) throw error; } + } else if (item.payload.action === 'completed') { + try { await client.workflow.getHandle(workflowId).signal('resume'); } catch (error) { if (!(error instanceof Error && error.name === 'WorkflowNotFoundError')) throw error; } + } + await this.control.store.transaction(tenant, tx => tx.acknowledge(item.id)); + } catch (error) { + if (item.type === 'run.start' && error instanceof DomainError && error.code !== 'EXECUTION_CAPACITY') await this.control.store.transaction(tenant, async tx => { const current = await must(tx, 'run', String(item.payload.runId)); if (!['canceled','failed','succeeded','paused'].includes(current.status)) { current.status='waiting'; current.waitingReason=error.code.toLowerCase(); await tx.put('run',touch(current)); await tx.event(current.id,'run.waiting',error.message); } }); + await this.control.store.transaction(tenant, tx => tx.defer(item.id, Math.min(120, 5 * 2 ** Math.min(item.attempts, 5)))); console.error(`Outbox ${item.type} pending: ${error instanceof DomainError ? error.code : error instanceof Error ? error.name : 'delivery failure'}`); + } + } + } + } catch (error) { console.error(`Temporal dispatcher reconnecting: ${error instanceof Error ? error.name : 'connection failure'}`); await this.connection?.close(); this.connection = undefined; } + await new Promise(resolve => setTimeout(resolve, 2000)); + } + } + async close() { this.stopped = true; await this.connection?.close(); } +} diff --git a/apps/api/src/domain/application-access.ts b/apps/api/src/domain/application-access.ts new file mode 100644 index 0000000..2116edb --- /dev/null +++ b/apps/api/src/domain/application-access.ts @@ -0,0 +1,9 @@ +import {DomainError,normalizeApplicationUrl,matchesApplicationAccess,type Environment,type Release} from '@wishforge/contracts'; +export function accessConfiguration(environment:Pick,env:NodeJS.ProcessEnv,additionalOrigins:string[]=[]){ + let applicationUrl:string|undefined; + if(environment.applicationUrl){try{applicationUrl=normalizeApplicationUrl(environment.applicationUrl,env.NODE_ENV!=='production'&&!environment.production);}catch{throw new DomainError('APPLICATION_URL_INVALID','Use an external HTTPS application URL without credentials, query or fragment; only development permits loopback HTTP',400);}} + if(applicationUrl){const origin=new URL(applicationUrl).origin;for(const configured of [env.WF_PUBLIC_URL,env.WF_API_PUBLIC_URL,env.WF_IDE_PUBLIC_URL,env.WF_WORKSPACE_GATEWAY_BASE,...additionalOrigins]){if(!configured)continue;let protectedOrigin:string;try{protectedOrigin=new URL(configured).origin;}catch{throw new DomainError('APPLICATION_ORIGIN_CONFIGURATION_INVALID','Platform identity origins must be configured correctly before assigning an application URL',503);}if(origin===protectedOrigin)throw new DomainError('APPLICATION_ORIGIN_CONFLICT','Applications must use an origin separate from the console, API and IDE authentication origins',400);}} + const visibility=environment.visibility??'private';return{applicationUrl,visibility,accessStatus:applicationUrl&&visibility==='public'?'configured' as const:'unconfigured' as const,accessReason:!applicationUrl?'Application URL has not been configured.':visibility==='private'?'Private application identity gateway is not integrated; deployment is blocked until independently validated.':undefined}; +} +export function assertApplicationConfigured(release:Pick,env:NodeJS.ProcessEnv){if(!release.applicationUrl){if(env.NODE_ENV==='production'||release.deliveryRequired)throw new DomainError('APPLICATION_URL_REQUIRED','Production delivery requires an explicit application URL and access acceptance',503);return;}if(release.visibility!=='public'&&!release.privateAccessPolicyDigest)throw new DomainError('PRIVATE_ACCESS_UNCONFIGURED','A real private application identity gateway is not integrated; private delivery is not enabled',503);} +export function assertApplicationAccepted(release:Pick,evidence:unknown,env:NodeJS.ProcessEnv){assertApplicationConfigured(release,env);if(!matchesApplicationAccess(release,evidence))throw new DomainError('APPLICATION_ACCESS_REQUIRED','Acceptance must bind the exact public application URL, stable origin and access probe');} diff --git a/apps/api/src/domain/artifacts.ts b/apps/api/src/domain/artifacts.ts new file mode 100644 index 0000000..dc45eb5 --- /dev/null +++ b/apps/api/src/domain/artifacts.ts @@ -0,0 +1,74 @@ +import { createHash } from 'node:crypto'; +import { DomainError, type Actor, type Entity, type Run } from '@wishforge/contracts'; +import { ArtifactError, MAX_ARTIFACT_BYTES, S3Artifacts, sha256, type StoredArtifact } from '../../../../packages/artifacts/src/index.js'; +import type { Store, Transaction } from '../db/store.js'; +import { must, record, projectAccess, executionLease, executionScope } from './control-plane.js'; + +export interface ArtifactRecord extends Entity { projectId: string; runId: string; kind: 'git-bundle'; sha256: string; size: number; contentType: string; object: StoredArtifact } +export class Artifacts { + readonly objects: S3Artifacts; + constructor(private store: Store, private env = process.env, objects?: S3Artifacts) { this.objects = objects ?? new S3Artifacts(env); } + private async authorize(tx: Transaction, actor: Actor, artifact: ArtifactRecord) { + if (artifact.tenantId !== actor.tenantId) throw new DomainError('NOT_FOUND', 'Artifact not found', 404); + const run = await must(tx, 'run', artifact.runId); + if (run.projectId !== artifact.projectId || artifact.object.runId !== run.id || artifact.object.tenantId !== run.tenantId || artifact.object.projectId !== run.projectId || artifact.object.sha256 !== artifact.sha256 || artifact.object.size !== artifact.size) throw new DomainError('ARTIFACT_SCOPE_MISMATCH', 'Artifact ownership record is inconsistent'); + if (['human', 'connector'].includes(actor.kind)) await projectAccess(tx, actor, run.projectId); + else { if (!['worker', 'verifier'].includes(actor.kind)) throw new DomainError('FORBIDDEN', 'Source artifacts require a project member or assigned execution identity', 403); executionScope(actor, run); } + } + private visible(record: ArtifactRecord) { return { id: record.id, tenantId: record.tenantId, projectId: record.projectId, runId: record.runId, kind: record.kind, sha256: record.sha256, size: record.size, contentType: record.contentType, createdAt: record.createdAt, downloadUrl: `/v1/artifacts/${record.id}/download` }; } + async metadata(actor: Actor, id: string) { return this.store.transaction(actor.tenantId, async tx => { const artifact = await must(tx, 'artifact', id); await this.authorize(tx, actor, artifact); return this.visible(artifact); }); } + async download(actor: Actor, id: string) { + const artifact = await this.store.transaction(actor.tenantId, async tx => { const found = await must(tx, 'artifact', id); await this.authorize(tx, actor, found); return found; }); + let body: Buffer; + try { body = await this.objects.get(artifact.object); } catch (error) { throw this.storageError(error); } + // Recheck membership/revocation and object identity after external I/O. + await this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'artifact', id); await this.authorize(tx, actor, current); if (current.version !== artifact.version || current.sha256 !== artifact.sha256) throw new DomainError('ARTIFACT_CHANGED', 'Artifact record changed while reading'); if (['human', 'connector'].includes(actor.kind) && !await tx.membership(actor.userId)) throw new DomainError('FORBIDDEN', 'Tenant membership was revoked', 403); }); + return { metadata: this.visible(artifact), body }; + } + async uploadCheckpointBundle(actor: Actor, runId: string, leaseToken: number, input: Record): Promise> { + if (!['worker', 'verifier'].includes(actor.kind)) throw new DomainError('FORBIDDEN', 'Only an assigned worker/verifier can upload checkpoints', 403); + const run = await this.store.transaction(actor.tenantId, async tx => { const found = await must(tx, 'run', runId); executionLease(actor, found, leaseToken); return found; }); + if (input.gitBundleBase64 === undefined) { + if (typeof input.gitBundleArtifactId === 'string') { + const artifact = await this.store.transaction(actor.tenantId, async tx => { const value = await must(tx, 'artifact', String(input.gitBundleArtifactId)); await this.authorize(tx, actor, value); return value; }); + if (artifact.runId !== runId || artifact.sha256 !== input.gitBundleSha256) throw new DomainError('ARTIFACT_SCOPE_MISMATCH', 'Checkpoint artifact must belong to this exact run and digest'); + return { ...input }; + } + if (this.env.NODE_ENV === 'production') throw new DomainError('CHECKPOINT_ARTIFACT_REQUIRED', 'Production checkpoints require a durable source bundle'); + return { ...input }; + } + if (typeof input.gitBundleBase64 !== 'string' || input.gitBundleBase64.length > Math.ceil(MAX_ARTIFACT_BYTES / 3) * 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(input.gitBundleBase64) || typeof input.gitBundleSha256 !== 'string' || !/^[a-f0-9]{64}$/.test(input.gitBundleSha256)) throw new DomainError('CHECKPOINT_ARTIFACT_INVALID', 'Checkpoint bundle must be base64 with a SHA-256 hex digest and at most 4 MiB', 400); + const body = Buffer.from(input.gitBundleBase64, 'base64'); + if (!body.length || body.length > MAX_ARTIFACT_BYTES || body.toString('base64') !== input.gitBundleBase64 || sha256(body) !== input.gitBundleSha256) throw new DomainError('ARTIFACT_DIGEST_MISMATCH', 'Checkpoint bundle bytes do not match their declared digest or size', 400); + if (!this.objects.configured()) { + if (this.env.NODE_ENV === 'production') throw new DomainError('ARTIFACT_STORAGE_UNCONFIGURED', 'Production checkpoint storage requires configured S3 and SSE-KMS', 503); + return { ...input, artifactStorage: 'inline-development' }; + } + let object: StoredArtifact; + try { object = await this.objects.put({ tenantId: actor.tenantId, projectId: run.projectId, runId }, body, input.gitBundleSha256, 'application/x-git-bundle'); } catch (error) { throw this.storageError(error); } + const id = `artifact-${createHash('sha256').update(JSON.stringify([actor.tenantId, run.projectId, runId, object.sha256])).digest('hex')}`; + await this.store.transaction(actor.tenantId, async tx => { + const current = await must(tx, 'run', runId); executionLease(actor, current, leaseToken); + if (current.revision !== run.revision) throw new DomainError('STALE_CHECKPOINT', 'Requirement revision changed while uploading'); + const prior = await tx.get('artifact', id); + if (prior) { await this.authorize(tx, actor, prior); if (prior.sha256 !== object.sha256 || prior.size !== object.size) throw new DomainError('ARTIFACT_IMMUTABILITY_CONFLICT', 'Artifact record does not match its content address'); return; } + const artifact: ArtifactRecord = { ...record(actor.tenantId), id, projectId: run.projectId, runId, kind: 'git-bundle', sha256: object.sha256, size: object.size, contentType: object.contentType, object }; + await tx.put('artifact', artifact); + await tx.meter({ id: `storage:${id}`, runId, tokens: 0, computeSeconds: 0, storageBytes: object.size, at: new Date().toISOString() }); + await tx.event(runId, 'artifact.stored', 'Source bundle persisted in private content-addressed object storage.', { artifactId: id, sha256: object.sha256, size: object.size }); + }); + const { gitBundleBase64: _, ...checkpoint } = input; + return { ...checkpoint, gitBundleArtifactId: id, gitBundleSha256: object.sha256, artifactStorage: 's3' }; + } + async hydrateCheckpoint(actor: Actor, runId: string, checkpoint: Record): Promise> { + if (!checkpoint.gitBundleArtifactId) { + if (this.env.NODE_ENV === 'production' && checkpoint.gitBundleBase64) throw new DomainError('CHECKPOINT_ARTIFACT_REQUIRED', 'Inline development bundles cannot be used in production'); + return checkpoint; + } + if (typeof checkpoint.gitBundleArtifactId !== 'string') throw new DomainError('CHECKPOINT_ARTIFACT_INVALID', 'Invalid checkpoint artifact reference'); + const { metadata, body } = await this.download(actor, checkpoint.gitBundleArtifactId); + if (metadata.runId !== runId || metadata.sha256 !== checkpoint.gitBundleSha256) throw new DomainError('ARTIFACT_SCOPE_MISMATCH', 'Checkpoint reference does not match the requested run or digest'); + return { ...checkpoint, gitBundleBase64: body.toString('base64') }; + } + private storageError(error: unknown) { return error instanceof ArtifactError ? new DomainError(error.code, error.message, 503) : new DomainError('ARTIFACT_STORAGE_UNAVAILABLE', 'Private artifact storage is unavailable; the checkpoint was not marked durable', 503); } +} diff --git a/apps/api/src/domain/billing.ts b/apps/api/src/domain/billing.ts new file mode 100644 index 0000000..b0e9c32 --- /dev/null +++ b/apps/api/src/domain/billing.ts @@ -0,0 +1,64 @@ +import { z } from 'zod'; +import { DomainError, type Actor, type BillingInvoice, type BillingUsageLine, type TenantEntitlementSnapshot } from '@wishforge/contracts'; +import type { Meter, Store, Transaction } from '../db/store.js'; +import { idempotent, record, touch } from './control-plane.js'; +import { digest, requireRole } from './policy.js'; +import { effectiveEntitlements, requireBillingOperator } from './entitlements.js'; + +export function billingPeriod(period?: string) { + const selected = period ?? new Date().toISOString().slice(0, 7); + if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(selected)) throw new DomainError('INVALID_BILLING_PERIOD', 'Use a UTC calendar month in YYYY-MM format', 400); + const [year, month] = selected.split('-').map(Number); if (year! < 2000 || year! > 9998) throw new DomainError('INVALID_BILLING_PERIOD', 'Billing year is out of range', 400); + return { period: selected, periodStart: new Date(Date.UTC(year!, month! - 1, 1)).toISOString(), periodEnd: new Date(Date.UTC(year!, month!, 1)).toISOString() }; +} +function line(entry: Meter): BillingUsageLine { + const source = entry.source ?? 'legacy'; + const provider = source === 'provider_proxy', artifact = source === 'artifact_service' && entry.measuredDimensions?.includes('artifact_bytes_added'); + return { id: entry.id, runId: entry.runId, at: entry.at, source, modelTokens: provider || entry.tokens > 0 ? entry.tokens : null, modelMeasurement: provider ? 'provider_reported' : source === 'artifact_service' ? 'not_applicable' : source === 'executor_reported' && entry.tokens > 0 ? 'executor_reported' : 'unknown', reportedComputeSeconds: entry.computeSeconds > 0 ? entry.computeSeconds : null, artifactBytesAdded: artifact ? entry.storageBytes : null, platformComputeMeasurement: 'unmeasured', platformStorageMeasurement: artifact ? 'partial' : 'unmeasured' }; +} +export class Billing { + constructor(private store: Store, private env = process.env) {} + private readable(actor: Actor) { requireRole(actor, ['owner', 'admin']); } + private async report(tx: Transaction, period?: string): Promise<{ invoice: BillingInvoice; lines: BillingUsageLine[] }> { + const window = billingPeriod(period), tenant = await tx.tenant(); + const lines = (await tx.usage(window.periodStart)).filter(entry => entry.at < window.periodEnd).map(line).sort((a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id)); + const unresolved = (await tx.list('provider_proxy_request')).filter(request => request.createdAt < window.periodEnd && ['unknown', 'dispatched'].includes(String(request.status)) && request.path === '/responses'); + const tokenLines = lines.filter(entry => entry.modelTokens !== null), artifactLines = lines.filter(entry => entry.artifactBytesAdded !== null); + const hasUnknown = unresolved.length > 0 || lines.some(entry => ['unknown', 'executor_reported'].includes(entry.modelMeasurement)); + const active = effectiveEntitlements(tenant); + const assignments = (await tx.list('entitlement_event')).filter(event => ['plan.assigned', 'tenant.provisioned'].includes(String(event.action)) && event.createdAt < window.periodEnd && event.entitlements).sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + const historical = assignments[0]?.entitlements as TenantEntitlementSnapshot | undefined; + const planId = historical?.planId ?? ((!active.assignedAt || active.assignedAt < window.periodEnd) ? active.planId : 'unknown'); + const planVersion = historical?.planVersion ?? ((!active.assignedAt || active.assignedAt < window.periodEnd) ? active.planVersion : 'unrecorded'); + const summary = { tenantId: tenant.id, ...window, timezone: 'UTC' as const, planId, planVersion, model: { charge: 'external' as const, reportedTokens: tokenLines.length ? tokenLines.reduce((sum, entry) => sum + entry.modelTokens!, 0) : null, measurement: tokenLines.length ? hasUnknown ? 'partial' as const : 'reported' as const : 'unknown' as const, unresolvedRequests: unresolved.length, amount: null }, platform: { computeSeconds: null, computeMeasurement: 'unmeasured' as const, artifactBytesAdded: artifactLines.length ? artifactLines.reduce((sum, entry) => sum + entry.artifactBytesAdded!, 0) : null, storageByteHours: null, storageMeasurement: artifactLines.length ? 'partial' as const : 'unmeasured' as const, amount: null }, currency: null, amountDue: null, lineCount: lines.length }; + const checksum = digest({ summary, lines, unresolvedRequestIds: unresolved.map(request => request.id).sort() }); + const record = await tx.get('billing_period', `billing-${window.period}`); const settlement = record?.settlement as BillingInvoice['settlement']; + const invoice: BillingInvoice = { ...summary, digest: checksum, status: settlement ? settlement.invoiceDigest === checksum ? settlement.status : 'needs_reconciliation' : 'unreviewed', ...(settlement ? { settlement } : {}) }; + return { invoice, lines }; + } + async usage(actor: Actor, period?: string) { this.readable(actor); return this.store.transaction(actor.tenantId, async tx => { const result = await this.report(tx, period); return { period: result.invoice.period, periodStart: result.invoice.periodStart, periodEnd: result.invoice.periodEnd, timezone: 'UTC', lines: result.lines, coverage: { model: result.invoice.model.measurement, compute: 'unmeasured', storage: result.invoice.platform.storageMeasurement }, supplierCharges: 'external', priced: false }; }); } + async invoice(actor: Actor, period?: string) { this.readable(actor); return this.store.transaction(actor.tenantId, async tx => (await this.report(tx, period)).invoice); } + async exportCsv(actor: Actor, period?: string) { + this.readable(actor); const report = await this.store.transaction(actor.tenantId, tx => this.report(tx, period)); + const cell = (value: unknown) => { let text = value === null || value === undefined ? '' : String(value); if (/^[\s\u0000-\u001f]*[=+\-@]/.test(text) || /^[\t\r\n]/.test(text)) text = `'${text}`; return `"${text.replaceAll('"', '""')}"`; }; + const rows: unknown[][] = [['period', 'entry_id', 'run_id', 'recorded_at', 'source', 'model_tokens_reported', 'model_measurement', 'supplier_charge', 'platform_compute_seconds', 'compute_measurement', 'artifact_bytes_added', 'storage_measurement', 'amount_due', 'currency', 'invoice_status']]; + for (const value of report.lines) rows.push([report.invoice.period, value.id, value.runId, value.at, value.source, value.modelTokens, value.modelMeasurement, 'external', null, 'unmeasured', value.artifactBytesAdded, value.platformStorageMeasurement, null, null, report.invoice.status]); + if (!report.lines.length) rows.push([report.invoice.period, '', '', '', 'no_measurements', null, 'unknown', 'external', null, 'unmeasured', null, 'unmeasured', null, null, report.invoice.status]); + return { filename: `wishforge-invoice-${report.invoice.period}.csv`, content: `\ufeff${rows.map(row => row.map(cell).join(',')).join('\r\n')}\r\n`, digest: report.invoice.digest }; + } + async settle(actor: Actor, period: string, input: unknown, key?: string): Promise { + requireBillingOperator(actor, this.env); + const data = z.object({ action: z.enum(['review', 'record_settled', 'void']), invoiceDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/), reference: z.string().trim().min(3).max(200), note: z.string().trim().min(10).max(2000), acknowledgeUnmeasured: z.literal(true) }).strict().parse(input); + return this.store.transaction(actor.tenantId, tx => idempotent(tx, key, { operation: 'billing.settlement', period, ...data }, async () => { + const { invoice } = await this.report(tx, period); + if (invoice.digest !== data.invoiceDigest) throw new DomainError('INVOICE_CHANGED', 'Usage or entitlement evidence changed; inspect the current invoice before recording settlement'); + if (data.action === 'record_settled' && Date.parse(invoice.periodEnd) > Date.now()) throw new DomainError('BILLING_PERIOD_OPEN', 'Record usage-period settlement only after the UTC month closes'); + const status = data.action === 'review' ? 'reviewed' : data.action === 'record_settled' ? 'settled_recorded' : 'voided'; + const settlement: NonNullable = { status, reference: data.reference, note: data.note, actorId: actor.userId, at: new Date().toISOString(), invoiceDigest: invoice.digest, acknowledgedUnmeasured: true }; + const current = await tx.get('billing_period', `billing-${period}`); const value = current ? touch(current) : { ...record(actor.tenantId), id: `billing-${period}` }; + await tx.put('billing_period', { ...value, period, settlement }); + await tx.put('billing_event', { ...record(actor.tenantId), period, action: data.action, actorId: actor.userId, reference: data.reference, note: data.note, invoiceDigest: invoice.digest, acknowledgedUnmeasured: true, amount: null, currency: null }); + return { ...invoice, status, settlement }; + })); + } +} diff --git a/apps/api/src/domain/connections.ts b/apps/api/src/domain/connections.ts new file mode 100644 index 0000000..3e2717e --- /dev/null +++ b/apps/api/src/domain/connections.ts @@ -0,0 +1,66 @@ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; +import { z } from 'zod'; +import { DomainError, providers, type Actor, type Entity, type Run } from '@wishforge/contracts'; +import type { Store } from '../db/store.js'; +import { record, touch, must, executionLease } from './control-plane.js'; +import { requireRole } from './policy.js'; +import { ProviderProxy } from './provider-proxy.js'; + +/** Production uses a Vault transit key. The development AES key never enters source control. */ +export class CredentialVault { + constructor(private env = process.env) {} + async seal(tenantId: string, value: string): Promise { + if (this.env.VAULT_ADDR) return this.transit('encrypt', tenantId, value); + if (this.env.NODE_ENV === 'production') throw new DomainError('VAULT_UNCONFIGURED', 'Production requires an external Vault transit service', 503); + const key = this.key(), iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(Buffer.from(tenantId)); + const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]); return `local:${iv.toString('base64url')}:${cipher.getAuthTag().toString('base64url')}:${ciphertext.toString('base64url')}`; + } + async open(tenantId: string, encrypted: string): Promise { + if (encrypted.startsWith('vault:')) return this.transit('decrypt', tenantId, encrypted); + if (this.env.NODE_ENV === 'production') throw new DomainError('VAULT_UNCONFIGURED', 'Local credential envelopes are not accepted in production', 503); + const [, iv, tag, payload] = encrypted.split(':'); const decipher = createDecipheriv('aes-256-gcm', this.key(), Buffer.from(iv, 'base64url')); decipher.setAAD(Buffer.from(tenantId)); decipher.setAuthTag(Buffer.from(tag, 'base64url')); + return Buffer.concat([decipher.update(Buffer.from(payload, 'base64url')), decipher.final()]).toString('utf8'); + } + private key() { const hex = this.env.WF_VAULT_KEY ?? ''; if (!/^[0-9a-f]{64}$/i.test(hex)) throw new DomainError('VAULT_UNCONFIGURED', 'Credential encryption has not been configured', 503); return Buffer.from(hex, 'hex'); } + private async transit(operation: 'encrypt' | 'decrypt', tenant: string, value: string) { + if (!this.env.VAULT_ADDR?.startsWith('https://') || !this.env.VAULT_TOKEN || !this.env.VAULT_TRANSIT_KEY) throw new DomainError('VAULT_UNCONFIGURED', 'Vault HTTPS URL, token and transit key are required', 503); + const response = await fetch(`${this.env.VAULT_ADDR}/v1/transit/${operation}/${encodeURIComponent(this.env.VAULT_TRANSIT_KEY)}`, { method: 'POST', headers: { 'X-Vault-Token': this.env.VAULT_TOKEN, 'Content-Type': 'application/json' }, body: JSON.stringify({ context: Buffer.from(tenant).toString('base64'), ...(operation === 'encrypt' ? { plaintext: Buffer.from(value).toString('base64') } : { ciphertext: value }) }), signal: AbortSignal.timeout(10000) }); + if (!response.ok) throw new DomainError('VAULT_UNAVAILABLE', 'Credential service is unavailable', 503); + const body = await response.json() as { data: { ciphertext: string; plaintext: string } }; return operation === 'encrypt' ? body.data.ciphertext : Buffer.from(body.data.plaintext, 'base64').toString('utf8'); + } +} +const inputSchema = z.object({ provider: z.enum(providers), label: z.string().trim().min(1).max(120), apiKey: z.string().min(8).max(16000) }).strict(); +export class Connections { + readonly vault: CredentialVault; + constructor(private store: Store, private env = process.env) { this.vault = new CredentialVault(env); } + list(actor: Actor) { requireRole(actor, ['owner', 'admin']); return this.store.transaction(actor.tenantId, async tx => (await tx.list('provider_connection')).map(({ ciphertext: _, ...publicFields }) => publicFields)); } + async create(actor: Actor, input: unknown) { + requireRole(actor, ['owner', 'admin']); const data = inputSchema.parse(input); + const ciphertext = await this.vault.seal(actor.tenantId, data.apiKey); // Network outside DB transaction. + return this.store.transaction(actor.tenantId, async tx => { + for (const old of await tx.list('provider_connection')) if (old.provider === data.provider && old.status === 'active') await tx.put('provider_connection', { ...touch(old), status: 'revoked', ciphertext: null }); + const connection = { ...record(actor.tenantId), provider: data.provider, label: data.label, status: 'active', ciphertext }; + await tx.put('provider_connection', connection); const { ciphertext: _, ...publicFields } = connection; return publicFields; + }); + } + revoke(actor: Actor, id: string) { requireRole(actor, ['owner', 'admin']); return this.store.transaction(actor.tenantId, async tx => { const c = await must(tx, 'provider_connection', id); await tx.put('provider_connection', { ...touch(c), status: 'revoked', ciphertext: null }); return { revoked: true }; }); } + async forRun(actor: Actor, run: Run) { + if (actor.kind !== 'worker' || actor.tenantId !== run.tenantId || !run.lease) return undefined; + const connection = await this.store.transaction(actor.tenantId, async tx => { + const current = await must(tx, 'run', run.id); + if (current.status !== 'running' || !current.lease || Date.parse(current.lease.expiresAt) <= Date.now() || current.lease.token !== run.lease!.token || current.leaseOwnerId !== actor.userId || current.leaseOwnerKind !== actor.kind) return undefined; + executionLease(actor, current, run.lease!.token); + return (await tx.list('provider_connection')).find(c => c.provider === current.provider && c.status === 'active'); + }); + if (!connection?.ciphertext) return undefined; + if (this.env.NODE_ENV === 'production' || this.env.WF_PROVIDER_PROXY_ENABLED === 'true') { if (run.provider !== 'codex') throw new DomainError('PROVIDER_PROXY_UNSUPPORTED', 'This provider has no verified credential-isolation proxy in production', 503); return { ...(await new ProviderProxy(this.store, this.env, { vault: this.vault }).credential(actor, run)), model: typeof run.providerModel === 'string' ? run.providerModel : undefined }; } + const apiKey = await this.vault.open(actor.tenantId, String(connection.ciphertext)); + // Vault I/O runs outside the transaction. Re-check revocation and lease after decrypting. + return this.store.transaction(actor.tenantId, async tx => { + const current = await must(tx, 'run', run.id); executionLease(actor, current, run.lease!.token); + const active = await tx.get('provider_connection', connection.id); + if (current.status !== 'running' || active?.status !== 'active' || active.version !== connection.version) return undefined; + return { apiKey }; + }); + } +} diff --git a/apps/api/src/domain/control-plane.ts b/apps/api/src/domain/control-plane.ts new file mode 100644 index 0000000..fb8c913 --- /dev/null +++ b/apps/api/src/domain/control-plane.ts @@ -0,0 +1,284 @@ +import { randomUUID } from 'node:crypto'; +import { DomainError, stages, projectInput, wishInput, commandInput, transitionInput, evidenceInput, type Actor, type Entity, type EntityKind, type Project, type Wish, type Run, type Evidence, type Release, type Environment, type ProviderInfo, type UsageSummary } from '@wishforge/contracts'; +import type { Store, Transaction } from '../db/store.js'; +import { checkLease, digest, redact, requireRole } from './policy.js'; +import { GitStorage } from './git-storage.js'; +import { requireCapacity, effectiveEntitlements } from './entitlements.js'; +import { validateRepositoryUrl } from '../../../../packages/runtime/src/git.js'; +import { resolveBundle } from './evolution.js'; +import { selectBundle } from './evolution.js'; +import { Artifacts } from './artifacts.js'; +import { providerProxyConfigured } from './provider-proxy.js'; +import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js'; +import { WorkspaceIntegration } from './workspace-integration.js'; + +export const now = () => new Date().toISOString(); +export function record(tenantId: string): Entity { const time = now(); return { id: randomUUID(), tenantId, version: 1, createdAt: time, updatedAt: time }; } +export function touch(value: T): T { return { ...value, version: value.version + 1, updatedAt: now() }; } +export async function must(tx: Transaction, kind: EntityKind, id: string): Promise { const v = await tx.get(kind, id); if (!v) throw new DomainError('NOT_FOUND', 'Resource not found', 404); return v; } +export async function projectAccess(tx: Transaction, actor: Actor, projectId: string): Promise { + const p = await must(tx, 'project', projectId); + if (['human', 'connector'].includes(actor.kind) && !['owner', 'admin'].includes(actor.role) && !p.memberIds.includes(actor.userId)) throw new DomainError('NOT_FOUND', 'Project not found', 404); + return p; +} +export async function idempotent(tx: Transaction, key: string | undefined, input: unknown, fn: () => Promise): Promise { + if (!key || key.length < 8 || key.length > 200) throw new DomainError('IDEMPOTENCY_REQUIRED', 'Provide an Idempotency-Key of 8–200 characters', 400); + const hash = digest(input), previous = await tx.idempotency(key); + if (previous) { if (previous.digest !== hash) throw new DomainError('IDEMPOTENCY_CONFLICT', 'This key was already used with a different request'); return previous.response as T; } + const result = await fn(); await tx.remember(key, hash, result); return result; +} +export const terminal = (run: Run) => ['succeeded', 'failed', 'canceled'].includes(run.status); +export function executionScope(actor: Actor, run: Run) { + if (!['worker', 'verifier', 'deployer'].includes(actor.kind) || actor.tenantId !== run.tenantId || (actor.runId && actor.runId !== run.id)) throw new DomainError('FORBIDDEN', 'Execution identity is not assigned to this run', 403); + if (actor.credentialId && run.executionGeneration !== actor.credentialId) throw new DomainError('EXECUTION_REVOKED', 'Execution credential was replaced', 403); +} +export function executionLease(actor: Actor, run: Run, token: number) { + executionScope(actor, run); checkLease(run, token, Date.now()); + if (run.leaseOwnerId !== actor.userId || run.leaseOwnerKind !== actor.kind) throw new DomainError('LEASE_IDENTITY_MISMATCH', 'The authenticated principal does not own this execution lease', 403); +} + +export class ControlPlane { + readonly artifacts: Artifacts; + readonly workspaceIntegration: WorkspaceIntegration; + constructor(readonly store: Store, readonly env = process.env) { this.artifacts = new Artifacts(store, env); this.workspaceIntegration=new WorkspaceIntegration(store,env); } + async projects(actor: Actor) { return this.store.transaction(actor.tenantId, async tx => (await tx.list('project')).filter(p => ['owner', 'admin'].includes(actor.role) || p.memberIds.includes(actor.userId))); } + async createProject(actor: Actor, input: unknown) { + requireRole(actor, ['owner', 'admin', 'developer']); const data = projectInput.parse(input); + if (!/^[\w][\w./-]*$/.test(data.targetBranch) || /\.\.|\/\.|\.lock$|\/$|\/\//.test(data.targetBranch)) throw new DomainError('INVALID_BRANCH', 'Invalid target branch', 400); + if (data.repositoryUrl) { + try { validateRepositoryUrl(data.repositoryUrl, { allowLocalHttp: this.env.WF_GIT_ALLOW_LOCAL_HTTP === 'true', production: this.env.NODE_ENV === 'production' }); } + catch (error) { throw new DomainError('INVALID_REPOSITORY', error instanceof Error ? error.message : 'Use an HTTPS repository URL; SSH is not supported', 400); } + } + const project = await this.store.transaction(actor.tenantId, async tx => { + await requireCapacity(tx, 'project'); + const project = { ...record(actor.tenantId), ...data, memberIds: [actor.userId], autoDeploy: false, repositoryStorage: data.repositoryUrl ? 'external' : 'platform', repositoryStatus: data.repositoryUrl ? 'ready' : 'unconfigured' } as Project; + await tx.put('project', project); return project; + }); + if (!project.repositoryUrl) return this.provisionRepository(actor, project.id); + return project; + } + async provisionRepository(actor: Actor, projectId: string) { + requireRole(actor, ['owner', 'admin', 'developer']); + const project = await this.store.transaction(actor.tenantId, tx => projectAccess(tx, actor, projectId)); + if (project.repositoryUrl) return project; + const git = new GitStorage(this.env); + if (!git.configured()) return project; + let repository: Awaited>; + try { repository = await git.provision(project); } catch (error) { + return this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'project', projectId); current.repositoryStatus = 'unavailable'; current.repositoryError = error instanceof DomainError ? error.message : 'Repository provisioning failed'; await tx.put('project', touch(current)); return current; }); + } + return this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'project', projectId); if (current.repositoryUrl) return current; Object.assign(current, { repositoryUrl: repository.repositoryUrl, sourceCommit: repository.initialCommit, targetBranch: repository.defaultBranch, repositoryStatus: 'ready', repositoryError: undefined }); await tx.put('project', touch(current)); return current; }); + } + async providers(actor: Actor): Promise { return this.store.transaction(actor.tenantId, tx => this.providerInfo(tx)); } + async providerInfo(tx: Transaction): Promise { + const connections = await tx.list('provider_connection'); + const connected = (id: string) => connections.some(c => c.provider === id && c.status === 'active'); + return ([['codex', 'Codex'], ['codebuddy', 'CodeBuddy'], ['workbuddy_cloud', 'WorkBuddy Cloud']] as const).map(([id, name]) => { + const configured = connected(id); + const productionAllowed = this.env.NODE_ENV !== 'production' || (id === 'codex' && providerProxyConfigured(this.env)); + const enabled = configured && productionAllowed && id !== 'workbuddy_cloud' && (id !== 'codebuddy' || !!this.env.WF_CODEBUDDY_BIN); + const reason = !productionAllowed ? 'Production execution requires a verified credential-isolation proxy and approved model configuration; raw BYOK is never sent to a production job.' : !configured ? 'Connect a tenant-owned provider credential to execute tasks.' : id === 'workbuddy_cloud' ? 'Cloud coding is gated until export, recovery and cancellation contracts are verified.' : id === 'codebuddy' && !this.env.WF_CODEBUDDY_BIN ? 'CodeBuddy executable is not configured on the worker.' : 'Available for worker preflight; account/model access is checked when a task starts.'; + return { id, name, configured, enabled, reason, capabilities: { codeExport: enabled, resume: enabled, cancel: enabled, eventReplay: false, usage: id === 'codex' && enabled, cloud: id === 'workbuddy_cloud' } }; + }); + } + async submit(actor: Actor, projectId: string, input: unknown, key?: string, metadata?: { purpose: 'evolution'; noDeployment: true; sourceRunIds: string[]; baselineBundle: string; evolutionScope: 'prompt' | 'orchestration' | 'tool' | 'platform'; metaTaskId: string }) { + requireRole(actor, ['owner', 'admin', 'developer']); const data = wishInput.parse(input); if (metadata && (actor.kind !== 'evaluator' || actor.tenantId !== this.env.WF_SYSTEM_TENANT)) throw new DomainError('FORBIDDEN', 'Evolution metadata is restricted to the configured system evaluator', 403); + this.validateKey(key); + return this.store.transaction(actor.tenantId, async tx => { + const project = await projectAccess(tx, actor, projectId); + return idempotent(tx, `wish:${actor.userId}:${projectId}:${key ?? ''}`, key ? { projectId, ...data, ...(metadata ? { metadata } : {}) } : await this.missingKey(), async () => { + const tenant = await tx.tenant(); const runs = await tx.list('run'); const usage = await tx.usage(this.period()); + const reserved = runs.reduce((sum, run) => sum + run.reservedTokens, 0); + if (reserved + usage.reduce((n, x) => n + x.tokens, 0) + data.budget.maxTokens > effectiveEntitlements(tenant).limits.monthlyModelTokens) throw new DomainError('QUOTA_EXCEEDED', 'Tenant token reservation limit is exhausted', 429); + const provider = (await this.providerInfo(tx)).find(p => p.id === data.provider)!; + const runnable = provider.enabled && !!project.repositoryUrl; + const wish = { ...record(actor.tenantId), projectId, revision: 1, goal: data.goal, acceptanceCriteria: data.acceptanceCriteria } as Wish; + const identity = record(actor.tenantId); + if (metadata && metadata.baselineBundle !== String((await tx.get('policy', 'evolution-routing-v1'))?.stableVersion ?? 'baseline-v1')) throw new DomainError('BASELINE_CHANGED', 'Meta generation must use the current stable bundle'); + const bundle = metadata ? { version: metadata.baselineBundle, config: await resolveBundle(tx, metadata.baselineBundle), candidateId: undefined } : await selectBundle(tx, { tenantId: actor.tenantId, projectId, runId: identity.id, canaryOptIn: project.canaryOptIn === true, internalProject: actor.tenantId === this.env.WF_SYSTEM_TENANT }); + const run = { ...identity, ...(metadata ?? {}), projectId, wishId: wish.id, revision: 1, ...data, stage: 'clarify', status: runnable ? 'queued' : 'waiting', waitingReason: !provider.enabled ? 'credentials' : !project.repositoryUrl ? 'git_storage' : undefined, pendingStartId: runnable ? randomUUID() : undefined, repairCount: 0, bundleVersion: bundle.version, providerModel: bundle.config.model ?? (data.provider === 'codex' ? this.env.WF_CODEX_DEFAULT_MODEL ?? this.env.WF_PROVIDER_PROXY_ALLOWED_MODELS?.split(',')[0]?.trim() : undefined), evolutionCandidateId: bundle.candidateId, policyVersion: 'policy-v1', reservedTokens: data.budget.maxTokens, usedTokens: 0, activeMilliseconds: 0 } as Run; + await tx.put('wish', wish); await tx.put('run', run); + await tx.event(run.id, 'wish.submitted', 'Wish accepted and acceptance criteria recorded.', { revision: 1 }); + if (runnable) await tx.enqueue('run.start', { runId: run.id, revision: 1 }, String(run.pendingStartId)); + else await tx.event(run.id, 'run.waiting', !provider.enabled ? provider.reason : 'Provision durable Git storage or connect a repository before execution.', { reason: run.waitingReason }); + return { wish_id: wish.id, run_id: run.id, status_url: `/runs/${run.id}` }; + }); + }); + } + private async missingKey(): Promise { throw new DomainError('IDEMPOTENCY_REQUIRED', 'Provide Idempotency-Key', 400); } + private validateKey(key?: string) { if (!key || key.length < 8 || key.length > 200) throw new DomainError('IDEMPOTENCY_REQUIRED', 'Provide an Idempotency-Key of 8–200 characters', 400); } + async runs(actor: Actor) { return this.store.transaction(actor.tenantId, async tx => { const accessible = new Set((await tx.list('project')).filter(p => ['owner', 'admin'].includes(actor.role) || p.memberIds.includes(actor.userId)).map(p => p.id)); return (await tx.list('run')).filter(r => accessible.has(r.projectId)); }); } + async run(actor: Actor, id: string) { return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); await projectAccess(tx, actor, run.projectId); return run; }); } + async events(actor: Actor, id: string, after = 0) { return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); await projectAccess(tx, actor, run.projectId); return tx.events(id, after); }); } + async command(actor: Actor, id: string, input: unknown, key?: string) { + requireRole(actor, ['owner', 'admin', 'developer']); const data = commandInput.parse(input); + this.validateKey(key); + return this.store.transaction(actor.tenantId, async tx => { + let run = await must(tx, 'run', id); const project = await projectAccess(tx, actor, run.projectId); + return idempotent(tx, `command:${actor.userId}:${id}:${key}`, data, async () => { + if (terminal(run)) throw new DomainError('TERMINAL_RUN', 'Submit a new wish to change a completed task'); + if (run.purpose === 'evolution' && run.generatedEvolutionCandidateId && ['resume', 'answer'].includes(data.action)) throw new DomainError('EVOLUTION_GENERATION_COMPLETE', 'The candidate is already recorded; use its evaluation and promotion actions'); + if (data.action === 'resume' && (run.status === 'queued' || (run.status === 'running' && run.lease && Date.parse(run.lease.expiresAt) > Date.now()))) return run; + this.accountTime(run); + run = touch(run); run.lease = run.lease ? { ...run.lease, token: run.lease.token + 1, expiresAt: now() } : undefined; + if (data.action === 'cancel') { run.status = 'canceled'; if (!run.providerProxyActiveRequest) run.reservedTokens = 0; run.waitingReason = undefined; } + else if (data.action === 'pause') { run.status = 'paused'; run.waitingReason = 'user'; } + else { + if (data.action === 'answer') { + if (!data.message) throw new DomainError('ANSWER_REQUIRED', 'Provide the additional requirement', 400); + const wish = touch(await must(tx, 'wish', run.wishId)); wish.revision += 1; wish.goal = `${wish.goal}\n\n${data.message}`; + if (data.acceptanceCriteria) wish.acceptanceCriteria = data.acceptanceCriteria; + await tx.put('wish', wish); run.revision = wish.revision; run.goal = wish.goal; run.acceptanceCriteria = wish.acceptanceCriteria; run.stage = 'plan'; run.verifiedCommit = undefined; + for (const approval of await tx.list('approval')) { + const release = await tx.get('release', String(approval.releaseId)); + if (release?.runId === run.id && ['pending', 'approved'].includes(String(approval.status))) await tx.put('approval', { ...touch(approval), status: 'invalidated' }); + } + } + const provider = (await this.providerInfo(tx)).find(p => p.id === run.provider)!; + if (run.activeMilliseconds >= run.budget.maxMinutes * 60_000) throw new DomainError('EXECUTION_BUDGET_EXHAUSTED', 'Active execution time budget is exhausted'); + if (run.usedTokens >= run.budget.maxTokens) throw new DomainError('TOKEN_BUDGET_EXHAUSTED', 'Token budget is exhausted'); + const runnable = provider.enabled && !!project.repositoryUrl; + run.status = runnable ? 'queued' : 'waiting'; run.waitingReason = !provider.enabled ? 'credentials' : !project.repositoryUrl ? 'git_storage' : undefined; + if (runnable) { run.pendingStartId = randomUUID(); await tx.enqueue('run.start', { runId: id, revision: run.revision }, String(run.pendingStartId)); } + } + await tx.put('run', run); await tx.event(id, `run.${data.action}`, data.message ? redact(data.message) : `Run ${data.action} requested.`, { revision: run.revision }); + await tx.enqueue('run.signal', { runId: id, action: data.action }); return run; + }); + }); + } + async lease(actor: Actor, id: string, workerId: string, generation?: string): Promise { + if (!['worker', 'verifier', 'deployer'].includes(actor.kind)) throw new DomainError('FORBIDDEN', 'Execution identity required', 403); + return this.store.transaction(actor.tenantId, async tx => { + let run = await must(tx, 'run', id); const tenant = await tx.tenant(); const time = Date.now(); + executionScope(actor, run); + if (run.executionGeneration && generation !== run.executionGeneration) throw new DomainError('STALE_GENERATION', 'A newer execution generation superseded this worker'); + if (!['queued', 'running'].includes(run.status)) throw new DomainError('RUN_NOT_RUNNABLE', `Run is ${run.status}`); + if (run.lease && Date.parse(run.lease.expiresAt) > time) { if (run.lease.workerId === workerId && run.leaseOwnerId === actor.userId && run.leaseOwnerKind === actor.kind) return run; throw new DomainError('LEASE_HELD', 'A live worker already owns this run'); } + const occupied = (await tx.list('run')).filter(r => r.id !== id && r.status === 'running' && r.lease && Date.parse(r.lease.expiresAt) > time).length; + if (occupied >= effectiveEntitlements(tenant).limits.maxConcurrentRuns) throw new DomainError('CONCURRENCY_LIMIT', 'Tenant execution slots are occupied', 429); + this.accountTime(run); if (run.activeMilliseconds >= run.budget.maxMinutes * 60000) throw new DomainError('EXECUTION_BUDGET_EXHAUSTED', 'Run time limit reached'); + if (run.usedTokens >= run.budget.maxTokens) throw new DomainError('TOKEN_BUDGET_EXHAUSTED', 'Token budget is exhausted'); + run = touch(run); run.status = 'running'; run.lastActiveAt = now(); run.lease = { token: (run.lease?.token ?? 0) + 1, workerId, expiresAt: new Date(time + 60000).toISOString() }; + run.leaseOwnerId = actor.userId; run.leaseOwnerKind = actor.kind; + await tx.put('run', run); await tx.event(id, 'run.leased', 'Worker acquired an execution lease.', { fencingToken: run.lease.token }); return run; + }); + } + async heartbeat(actor: Actor, id: string, token: number) { + return this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', id); executionLease(actor, run, token); if (run.status !== 'running') throw new DomainError('RUN_NOT_RUNNING', 'Run is no longer running'); + this.accountTime(run); if (run.activeMilliseconds >= run.budget.maxMinutes * 60000) { run.status = 'waiting'; run.waitingReason = 'budget'; run.lease!.expiresAt = now(); } + else { run.lastActiveAt = now(); run.lease!.expiresAt = new Date(Date.now() + 60000).toISOString(); } + await tx.put('run', run.status === 'waiting' ? touch(run) : run); return run; + }); + } + async releaseLease(actor: Actor, id: string, token: number) { + return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); executionLease(actor, run, token); this.accountTime(run); run.lease!.expiresAt = now(); await tx.put('run', touch(run)); return run; }); + } + async waitRun(actor: Actor, id: string, reason: string, expectedGeneration?: string) { + if (actor.kind !== 'worker' || actor.runId) throw new DomainError('FORBIDDEN', 'Trusted workflow coordinator required', 403); + return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); if (terminal(run) || run.status === 'paused' || (expectedGeneration && run.executionGeneration !== expectedGeneration)) return run; if (run.lease && Date.parse(run.lease.expiresAt) > Date.now()) throw new DomainError('LEASE_HELD', 'Execution is still active'); const message = redact(reason).slice(0, 2000); if (run.status === 'waiting' && run.waitingReason === message) return run; this.accountTime(run); run.status = 'waiting'; run.waitingReason = message; await tx.put('run', touch(run)); await tx.event(id, 'run.waiting', run.waitingReason); return run; }); + } + async transition(actor: Actor, id: string, input: unknown) { + const data = transitionInput.parse(input); + if (!['worker', 'verifier', 'deployer'].includes(actor.kind)) throw new DomainError('FORBIDDEN', 'Execution identity required', 403); + if(['integrate','build'].includes(data.stage)&&data.status==='running')await this.workspaceIntegration.enforce(actor,id,data.leaseToken); + return this.store.transaction(actor.tenantId, async tx => { + let run = await must(tx, 'run', id); executionLease(actor, run, data.leaseToken); + if (terminal(run) || run.status === 'paused') throw new DomainError('RUN_NOT_RUNNABLE', 'Run is stopped'); + if (data.expectedVersion && data.expectedVersion !== run.version) throw new DomainError('VERSION_CONFLICT', 'Run version changed'); + if (data.status === 'succeeded' || data.stage === 'accept') throw new DomainError('DELIVERY_EVIDENCE_REQUIRED', 'Only verified release acceptance can complete a run'); + if (data.sourceCommit && run.verifiedCommit && data.sourceCommit !== run.verifiedCommit && !data.repair) throw new DomainError('COMMIT_MISMATCH', 'A different commit must be independently verified before progressing'); + const previous = stages.indexOf(run.stage), next = stages.indexOf(data.stage); + if (next < previous && !(data.repair && data.stage === 'implement')) throw new DomainError('INVALID_TRANSITION', 'Cannot move backward without a repair attempt'); + if (next > previous + 1) throw new DomainError('INVALID_TRANSITION', 'Execution stages cannot be skipped'); + if (data.repair) { if (run.repairCount >= run.budget.maxRepairRounds) throw new DomainError('REPAIR_LIMIT', 'Repair budget exhausted'); run.repairCount++; run.verifiedCommit = undefined; } + if (['integrate', 'build', 'preview', 'release'].includes(data.stage) && !run.verifiedCommit) throw new DomainError('VERIFICATION_REQUIRED', 'Trusted verification of this revision is required'); + this.accountTime(run); run = touch(run); + if (run.activeMilliseconds >= run.budget.maxMinutes * 60000 || run.usedTokens >= run.budget.maxTokens) { run.status = 'waiting'; run.waitingReason = 'budget'; run.lease!.expiresAt = now(); await tx.put('run', run); await tx.event(id, 'run.waiting', 'Execution budget exhausted.'); return run; } + run.stage = data.stage; run.status = data.status; run.waitingReason = data.waitingReason; + if (data.sourceCommit) run.sourceCommit = data.sourceCommit; + if (data.status === 'failed') run.error = redact(data.message).slice(0, 5000); + if (data.checkpointId) { const checkpoint = await must(tx, 'checkpoint', data.checkpointId); if (checkpoint.runId !== id) throw new DomainError('CHECKPOINT_MISMATCH', 'Checkpoint belongs to another run'); run.checkpointId = data.checkpointId; } + if (run.status === 'running') run.lastActiveAt = now(); else run.lastActiveAt = undefined; + if (terminal(run) && !run.providerProxyActiveRequest) run.reservedTokens = 0; + await tx.put('run', run); await tx.event(id, 'run.transition', redact(data.message), { stage: run.stage, status: run.status, revision: run.revision }); return run; + }); + } + async evidence(actor: Actor, input: unknown) { + const data = evidenceInput.parse(input); + if ((data.type === 'deployment' && actor.kind !== 'deployer') || (data.type !== 'deployment' && actor.kind !== 'verifier')) throw new DomainError('FORBIDDEN', 'An independent verifier/deployer identity must submit evidence', 403); + if(data.type==='build'&&data.passed)await this.workspaceIntegration.enforce(actor,data.runId,data.leaseToken??0); + return this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', data.runId); if (run.revision !== data.revision || terminal(run)) throw new DomainError('STALE_EVIDENCE', 'Evidence does not match the active requirement revision'); + executionScope(actor, run); + if (data.type !== 'deployment') { + executionLease(actor, run, data.leaseToken ?? 0); + if (run.status !== 'running') throw new DomainError('STALE_EVIDENCE', 'Verification requires an active execution'); + if (run.activeMilliseconds + (run.lastActiveAt ? Math.max(0, Date.now() - Date.parse(run.lastActiveAt)) : 0) >= run.budget.maxMinutes * 60000) throw new DomainError('EXECUTION_BUDGET_EXHAUSTED', 'Run time limit reached'); + } else { + if (!data.releaseId || !data.environmentId || !data.bindingDigest) throw new DomainError('DEPLOYMENT_BINDING_REQUIRED', 'Deployment evidence must bind a release, environment and binding digest', 400); + const release = await must(tx, 'release', data.releaseId), environment = await must(tx, 'environment', data.environmentId); + if (actor.userId.startsWith('runner:') && actor.userId !== `runner:${environment.id}`) throw new DomainError('FORBIDDEN', 'Runner cannot attest another environment', 403); + if (release.runId !== run.id || release.revision !== run.revision || release.environmentId !== environment.id || environment.activeReleaseId !== release.id || !['deploying', 'unknown'].includes(release.status) || release.bindingDigest !== data.bindingDigest || release.sourceCommit !== data.sourceCommit || release.imageDigest !== data.imageDigest) throw new DomainError('STALE_EVIDENCE', 'Deployment evidence does not match the active release'); + } + const project = await must(tx, 'project', run.projectId); + if (data.passed && data.type !== 'deployment') { + assertVerificationProfile(project, this.env); + if (project.verificationProfile && data.verificationProfileDigest !== digest(project.verificationProfile)) throw new DomainError('STALE_EVIDENCE', 'Evidence must bind the installed independent acceptance profile'); + } + if (data.type === 'verification' && data.passed) { + const requiredCommands = [...project.verificationCommands, ...(project.verificationProfile?.commands ?? [])]; + if (!requiredCommands.length || !data.commands?.length || data.commands.some(c => c.exitCode !== 0) || requiredCommands.some(argv => !data.commands!.some(c => digest(c.argv) === digest(argv)))) throw new DomainError('INCOMPLETE_VERIFICATION', 'All protected verification commands must pass'); + run.sourceCommit = data.sourceCommit; run.verifiedCommit = data.sourceCommit; run.verifiedPolicyDigest = verificationPolicyDigest(project); await tx.put('run', touch(run)); + } + if (data.type === 'build' && data.passed && (!data.imageDigest || run.verifiedCommit !== data.sourceCommit || (project.verificationProfile && run.verifiedPolicyDigest !== verificationPolicyDigest(project)))) throw new DomainError('UNVERIFIED_BUILD', 'Build must bind the verified commit and an immutable image digest'); + const evidence = { ...record(actor.tenantId), ...data, issuer: actor.userId, verificationPolicyDigest: verificationPolicyDigest(project) } as Evidence; + if(data.type==='deployment'&&data.passed){const release=await must(tx,'release',data.releaseId!);if(release.visibility==='private'&&release.applicationUrl)throw new DomainError('PRIVATE_RUNNER_RECEIPT_REQUIRED','Private deployment evidence must be submitted through the bound signed Runner task receipt');} + await tx.put('evidence', evidence); await tx.event(run.id, 'evidence.recorded', `${data.type} evidence ${data.passed ? 'passed' : 'failed'}.`, { evidenceId: evidence.id, sourceCommit: data.sourceCommit }); return evidence; + }); + } + async context(actor: Actor, id: string) { + const result = await this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', id); const project = await projectAccess(tx, actor, run.projectId); + const connection = (await tx.list('provider_connection')).find(c => c.provider === run.provider && c.status === 'active'); + const cp = run.checkpointId ? await tx.get('checkpoint', run.checkpointId) : undefined; + const evidence = (await tx.list('evidence')).filter(e => e.runId === id && e.revision === run.revision && e.sourceCommit === run.verifiedCommit && e.passed); + const release = (await tx.list('release')).find(r => r.runId === id && r.revision === run.revision && r.sourceCommit === run.verifiedCommit); + const deliveryConfig = project.deliveryConfig as { environmentId?: string } | undefined; + return { run, project, checkpoint: cp?.checkpoint ?? null, workspace: cp?.workspace, verificationCommands: project.verificationCommands, verificationProfile: project.verificationProfile, verificationProfileDigest: project.verificationProfile ? digest(project.verificationProfile) : undefined, verificationProfileRequired: this.env.NODE_ENV === 'production', connectionId: connection?.id ?? null, bundleConfig: await resolveBundle(tx, run.bundleVersion), delivery: { release, verificationEvidenceId: evidence.find(e => e.type === 'verification')?.id, buildEvidenceId: evidence.find(e => e.type === 'build')?.id, environmentId: release?.environmentId ?? deliveryConfig?.environmentId } }; + }); + if (result.checkpoint && ['worker', 'verifier'].includes(actor.kind)) result.checkpoint = await this.artifacts.hydrateCheckpoint(actor, id, result.checkpoint as Record); + return result; + } + async checkpoint(actor: Actor, id: string, input: Record, token: number, workspace?: string) { + const checkpoint = await this.artifacts.uploadCheckpointBundle(actor, id, token, input); + return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); executionLease(actor, run, token); const cp = { ...record(actor.tenantId), runId: id, revision: run.revision, checkpoint, workspace }; await tx.put('checkpoint', cp); run.checkpointId = cp.id; await tx.put('run', touch(run)); return cp; }); + } + async classify(actor: Actor, id: string, input: { leaseToken: number; sourceCommit: string; changedPaths: string[]; migration: boolean; permissionsExpanded: boolean }) { + if (actor.kind !== 'verifier') throw new DomainError('FORBIDDEN', 'Independent verifier required', 403); + return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); executionLease(actor, run, input.leaseToken); if (!run.checkpointId || run.verifiedCommit !== input.sourceCommit) throw new DomainError('VERIFICATION_REQUIRED', 'Classification must bind a verified checkpoint'); const cp = await must(tx, 'checkpoint', run.checkpointId); if (cp.revision !== run.revision || cp.runId !== run.id) throw new DomainError('STALE_CHECKPOINT', 'Classification requires a current revision checkpoint'); const { leaseToken: _, ...classification } = input; cp.trustedClassification = classification; await tx.put('checkpoint', touch(cp)); return { accepted: true }; }); + } + async providerEvent(actor: Actor, id: string, token: number, event: Record) { + return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); executionLease(actor, run, token); return tx.event(id, `provider.${String(event.type ?? 'progress')}`, redact(String(event.message ?? event.text ?? event.type ?? 'Provider progress')).slice(0, 5000), { sequence: event.sequence, provider: run.provider }); }); + } + period() { const date = new Date(); return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1)).toISOString(); } + async usage(actor: Actor): Promise { + return this.store.transaction(actor.tenantId, async tx => { const tenant = await tx.tenant(); const runs = await tx.list('run'); const usage = await tx.usage(this.period()); return { activeRuns: runs.filter(r => r.status === 'running').length, maxConcurrentRuns: tenant.maxConcurrentRuns, tokens: usage.reduce((n, u) => n + u.tokens, 0), reservedTokens: runs.reduce((n, r) => n + r.reservedTokens, 0), tokenLimit: tenant.tokenLimit, computeSeconds: usage.reduce((n, u) => n + u.computeSeconds, 0), storageBytes: usage.reduce((n, u) => n + u.storageBytes, 0), modelCost: 'external', periodStart: this.period() }; }); + } + async meter(actor: Actor, id: string, input: { operationId: string; tokens: number; computeSeconds: number; leaseToken: number }) { + if (!Number.isSafeInteger(input.tokens) || input.tokens < 0 || !Number.isFinite(input.computeSeconds) || input.computeSeconds < 0 || !input.operationId) throw new DomainError('INVALID_USAGE', 'Invalid usage measurement', 400); + return this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', id); executionScope(actor, run); + const { leaseToken, ...measurement } = input; + return idempotent(tx, `meter:${id}:${input.operationId}`, measurement, async () => { + executionLease(actor, run, leaseToken); this.accountTime(run); + run.usedTokens += input.tokens; run.reservedTokens = Math.max(0, run.reservedTokens - input.tokens); + await tx.meter({ id: `${id}:${input.operationId}`, runId: id, tokens: input.tokens, computeSeconds: input.computeSeconds, storageBytes: 0, at: now() }); + if (run.usedTokens >= run.budget.maxTokens || run.activeMilliseconds >= run.budget.maxMinutes * 60000) { run.status = 'waiting'; run.waitingReason = 'budget'; run.lease!.expiresAt = now(); } + else if (run.status === 'running') run.lastActiveAt = now(); + await tx.put('run', touch(run)); return { accepted: true, remaining: Math.max(0, run.budget.maxTokens - run.usedTokens) }; + }); + }); + } + private accountTime(run: Run) { if (run.lastActiveAt) { const end = Math.min(Date.now(), run.lease ? Date.parse(run.lease.expiresAt) : Date.now()); run.activeMilliseconds += Math.max(0, end - Date.parse(run.lastActiveAt)); run.lastActiveAt = undefined; } } +} diff --git a/apps/api/src/domain/deployment-secret-policy.ts b/apps/api/src/domain/deployment-secret-policy.ts new file mode 100644 index 0000000..51bfe16 --- /dev/null +++ b/apps/api/src/domain/deployment-secret-policy.ts @@ -0,0 +1,2 @@ +import {DomainError} from '@wishforge/contracts'; +export function requireDeploymentSecretPolicy(input:{secretVersionRefs?:string[];deploymentSecretPolicyDigest?:string}){if(input.secretVersionRefs?.length&&!/^sha256:[a-f0-9]{64}$/.test(input.deploymentSecretPolicyDigest??''))throw new DomainError('DEPLOYMENT_SECRET_POLICY_REQUIRED','Versioned application secrets require the operator-reviewed deployment secret policy digest',503);} diff --git a/apps/api/src/domain/entitlements.ts b/apps/api/src/domain/entitlements.ts new file mode 100644 index 0000000..42823c6 --- /dev/null +++ b/apps/api/src/domain/entitlements.ts @@ -0,0 +1,91 @@ +import { createHmac, randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { z } from 'zod'; +import { DomainError, roles, type Actor, type CommercialPlan, type EntitlementView, type ExecutionResourceGrant, type PlanLimits, type Run, type TenantEntitlementSnapshot } from '@wishforge/contracts'; +import type { Store, Tenant, Transaction } from '../db/store.js'; +import { idempotent, must, record, touch } from './control-plane.js'; +import { requireHuman } from './policy.js'; + +const positive = z.number().int().positive(); +export const planLimitsSchema = z.object({ maxMembers: positive.max(10000), maxProjects: positive.max(10000), maxWorkspaces: positive.max(10000), maxConcurrentRuns: positive.max(1000), monthlyModelTokens: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), execution: z.object({ cpuMilli: positive.min(100).max(64000), memoryMiB: positive.min(512).max(262144), storageMiB: positive.min(128).max(1048576) }).strict() }).strict(); +export const planSchema = z.object({ id: z.string().regex(/^[a-z0-9][a-z0-9-]{1,39}$/), version: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$/), name: z.string().trim().min(1).max(120), limits: planLimitsSchema }).strict(); +const entitlementSchema = z.object({ schemaVersion: z.literal(1), planId: planSchema.shape.id, planVersion: planSchema.shape.version, limits: planLimitsSchema, assignedAt: z.string().datetime(), assignedBy: z.string().min(1) }).strict(); +export const PILOT_PLAN: CommercialPlan = { id: 'pilot', version: 'pilot-v1', name: 'Invitation pilot', limits: { maxMembers: 10, maxProjects: 10, maxWorkspaces: 5, maxConcurrentRuns: 2, monthlyModelTokens: 2_000_000, execution: { cpuMilli: 2000, memoryMiB: 4096, storageMiB: 10240 } } }; +export async function configuredPlans(env = process.env): Promise { + if (!env.WF_PLAN_CATALOG_FILE) return [structuredClone(PILOT_PLAN)]; + const bytes = await readFile(env.WF_PLAN_CATALOG_FILE); if (bytes.length > 65536) throw new DomainError('PLAN_CONFIGURATION_INVALID', 'Plan catalog exceeds 64 KiB', 503); + const catalog = z.object({ schemaVersion: z.literal(1), plans: z.array(planSchema).min(1).max(100) }).strict().parse(JSON.parse(bytes.toString('utf8'))); + if (new Set(catalog.plans.map(plan => plan.id)).size !== catalog.plans.length) throw new DomainError('PLAN_CONFIGURATION_INVALID', 'Plan IDs must be unique', 503); + return catalog.plans; +} +export function effectiveEntitlements(tenant: Tenant): { planId: string; planVersion: string; limits: PlanLimits; legacy: boolean; assignedAt?: string; assignedBy?: string } { + if (tenant.entitlements) { + const parsed = entitlementSchema.safeParse(tenant.entitlements); if (!parsed.success) throw new DomainError('ENTITLEMENTS_INVALID', 'Operator entitlement snapshot requires reconciliation', 503); + return { ...parsed.data, legacy: false, limits: { ...parsed.data.limits, maxConcurrentRuns: Math.min(parsed.data.limits.maxConcurrentRuns, tenant.maxConcurrentRuns), monthlyModelTokens: Math.min(parsed.data.limits.monthlyModelTokens, tenant.tokenLimit) } }; + } + return { planId: 'legacy', planVersion: 'legacy-v1', legacy: true, limits: { ...structuredClone(PILOT_PLAN.limits), maxProjects: 20, maxWorkspaces: 10, maxConcurrentRuns: tenant.maxConcurrentRuns, monthlyModelTokens: tenant.tokenLimit } }; +} +export function requireBillingOperator(actor: Actor, env = process.env) { + requireHuman(actor); + if (actor.role !== 'admin' || !(env.WF_BILLING_OPERATOR_SUBJECTS ?? '').split(',').map(value => value.trim()).filter(Boolean).includes(actor.userId)) throw new DomainError('BILLING_OPERATOR_REQUIRED', 'A human admin explicitly assigned to billing operations is required', 403); +} +export async function requireCapacity(tx: Transaction, kind: 'project' | 'workspace') { + const limits = effectiveEntitlements(await tx.tenant()).limits; + const count = (await tx.list(kind)).filter(value => value.status !== 'deleted').length; + if (count >= (kind === 'project' ? limits.maxProjects : limits.maxWorkspaces)) throw new DomainError('ENTITLEMENT_LIMIT', `Tenant ${kind} allowance is exhausted`, 429); +} +export function heldAllocation(run: Run): boolean { const allocation = run.resourceAllocation as { status?: string } | undefined; return !!allocation && ['reserved', 'provisioned', 'unknown', 'releasing'].includes(String(allocation.status)); } +export function occupiesExecutionSlot(run: Run): boolean { return heldAllocation(run) || !!(run.status === 'running' && run.lease && Date.parse(run.lease.expiresAt) > Date.now()); } +export function resourceGrantPayload(grant: Omit) { return JSON.stringify({ schemaVersion: grant.schemaVersion, tenantId: grant.tenantId, runId: grant.runId, generation: grant.generation, planId: grant.planId, planVersion: grant.planVersion, image: grant.image, cpuMilli: grant.cpuMilli, memoryMiB: grant.memoryMiB, storageMiB: grant.storageMiB, issuedAt: grant.issuedAt, expiresAt: grant.expiresAt }); } +function configuredInteger(value: string | undefined, fallback: number, minimum: number) { const number = value === undefined ? fallback : Number(value); if (!Number.isSafeInteger(number) || number < minimum) throw new DomainError('RESOURCE_CONFIGURATION_INVALID', 'Execution resource default is below the supported provisioner minimum', 503); return number; } +/** Caller holds the tenant transaction lock; the claim survives uncertain provisioning. */ +export async function reserveExecutionGrant(tx: Transaction, runId: string, generation: string, env = process.env): Promise { + if (!env.WF_RESOURCE_GRANT_SECRET || env.WF_RESOURCE_GRANT_SECRET.length < 32) throw new DomainError('RESOURCE_SIGNER_UNCONFIGURED', 'Configure the independent resource-grant signing secret', 503); + const run = await must(tx, 'run', runId); const plan = effectiveEntitlements(await tx.tenant()); + if (['succeeded', 'failed', 'canceled', 'paused'].includes(run.status)) throw new DomainError('RUN_STOPPED', 'Stopped run cannot reserve a sandbox'); + const others = (await tx.list('run')).filter(other => other.id !== run.id && occupiesExecutionSlot(other)); + if (others.length >= plan.limits.maxConcurrentRuns) throw new DomainError('EXECUTION_CAPACITY', 'Execution slots are occupied; this request remains queued', 429); + if (!run.runtimeImage && run.checkpointId) throw new DomainError('RUNTIME_IMAGE_MIGRATION_REQUIRED', 'Legacy checkpoint has no pinned runtime image; authorize a checkpoint migration before resuming'); + const image = String(run.runtimeImage ?? env.WF_RUN_IMAGE ?? env.WF_RUN_WORKER_IMAGE ?? ''); + if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]*@sha256:[a-f0-9]{64}$/.test(image)) throw new DomainError('RUNTIME_IMAGE_UNCONFIGURED', 'An immutable approved runtime image digest is required', 503); + const previous = run.resourceAllocation as { generation?: string; grant?: ExecutionResourceGrant; status?: string } | undefined; + if (previous?.generation !== generation && heldAllocation(run)) throw new DomainError('RESOURCE_PREVIOUS_GENERATION', 'The previous sandbox allocation must be stopped and reconciled before a new generation can reserve resources'); + const requested = previous?.generation === generation && previous.grant ? previous.grant : { + cpuMilli: Math.min(plan.limits.execution.cpuMilli, configuredInteger(env.WF_DEFAULT_EXECUTION_CPU_MILLI, 2000, 100)), + memoryMiB: Math.min(plan.limits.execution.memoryMiB, configuredInteger(env.WF_DEFAULT_EXECUTION_MEMORY_MIB, 4096, 512)), + storageMiB: Math.min(plan.limits.execution.storageMiB, configuredInteger(env.WF_DEFAULT_EXECUTION_STORAGE_MIB, 10240, 128)), + }; + if (requested.cpuMilli > plan.limits.execution.cpuMilli || requested.memoryMiB > plan.limits.execution.memoryMiB || requested.storageMiB > plan.limits.execution.storageMiB) throw new DomainError('RESOURCE_PLAN_CHANGED', 'Existing sandbox grant exceeds current entitlements; reconcile before reprovisioning'); + const issuedAt = Math.floor(Date.now() / 1000); + const payload: Omit = { schemaVersion: 1, tenantId: run.tenantId, runId, generation, planId: plan.planId, planVersion: plan.planVersion, image, cpuMilli: requested.cpuMilli, memoryMiB: requested.memoryMiB, storageMiB: requested.storageMiB, issuedAt, expiresAt: issuedAt + 300 }; + const grant = { ...payload, signature: createHmac('sha256', env.WF_RESOURCE_GRANT_SECRET).update(resourceGrantPayload(payload)).digest('base64url') }; + run.runtimeImage = image; run.executionGeneration = generation; run.resourceAllocation = { generation, grant, status: previous?.generation === generation && previous.status && previous.status !== 'released' ? previous.status : 'reserved', updatedAt: new Date().toISOString() }; + await tx.put('run', touch(run)); return grant; +} +export async function recordAllocation(tx: Transaction, runId: string, generation: string, status: 'provisioned' | 'unknown' | 'releasing' | 'released') { + const run = await must(tx, 'run', runId); const current = run.resourceAllocation as { generation?: string; status?: string } | undefined; + if (current?.generation !== generation || current.status === status) return; + run.resourceAllocation = { ...current, status, updatedAt: new Date().toISOString() }; await tx.put('run', touch(run)); + await tx.event(run.id, `resources.${status}`, status === 'released' ? 'Provisioner confirmed compute Jobs stopped; retained persistent storage remains unmeasured.' : `Sandbox resource allocation ${status}.`, { generation }); +} +export class Entitlements { + constructor(private store: Store, private env = process.env) {} + async view(actor: Actor): Promise { return this.store.transaction(actor.tenantId, async tx => { const plan = effectiveEntitlements(await tx.tenant()); return { ...plan, counts: { members: (await tx.members()).filter(member => member.active).length, projects: (await tx.list('project')).filter(p => p.status !== 'deleted').length, workspaces: (await tx.list('workspace')).filter(w => w.status !== 'deleted').length, reservedExecutionSlots: (await tx.list('run')).filter(occupiesExecutionSlot).length } }; }); } + async plans(actor: Actor) { if (!['owner', 'admin'].includes(actor.role)) throw new DomainError('FORBIDDEN', 'Tenant owner/admin required', 403); return configuredPlans(this.env); } + async inviteMember(actor: Actor, input: unknown, key?: string) { + requireBillingOperator(actor, this.env); const data = z.object({ userId: z.string().trim().min(1).max(200), role: z.enum(roles) }).strict().parse(input); + return this.store.transaction(actor.tenantId, async tx => idempotent(tx, key, { operation: 'member.invite', ...data }, async () => { + const members = await tx.members(), current = members.find(member => member.userId === data.userId && member.active); const limit = effectiveEntitlements(await tx.tenant()).limits.maxMembers; + if (!current && members.filter(member => member.active).length >= limit) throw new DomainError('MEMBER_LIMIT', 'Tenant active-member allowance is exhausted', 429); + await tx.putMembership({ ...data, active: true }); await tx.put('entitlement_event', { ...record(actor.tenantId), action: 'member.invited', actorId: actor.userId, targetSubject: data.userId, role: data.role }); return { userId: data.userId, role: data.role, active: true }; + })); + } + async reconcileAllocation(actor: Actor, runId: string, input: unknown, key?: string) { + requireBillingOperator(actor, this.env); const data = z.object({ confirmedStopped: z.literal(true), reference: z.string().trim().min(3).max(200), note: z.string().trim().min(10).max(2000) }).strict().parse(input); + return this.store.transaction(actor.tenantId, tx => idempotent(tx, key, { operation: 'resources.reconcile', runId, ...data }, async () => { + const run = await must(tx, 'run', runId); const allocation = run.resourceAllocation as { generation?: string; status?: string; cleanupConfirmedAt?: string } | undefined; + if (!allocation?.generation || !['unknown', 'releasing'].includes(String(allocation.status)) || !allocation.cleanupConfirmedAt || ['running','queued'].includes(run.status) || (run.lease && Date.parse(run.lease.expiresAt) > Date.now())) throw new DomainError('RESOURCE_RECONCILIATION_REQUIRED', 'Only stopped runs with a provisioner cleanup receipt can be manually reconciled'); + await recordAllocation(tx, runId, allocation.generation, 'released'); await tx.put('entitlement_event', { ...record(actor.tenantId), action: 'resources.manually_reconciled', runId, actorId: actor.userId, reference: data.reference, note: data.note }); return { runId, status: 'released', basis: 'operator_record_after_cleanup', measuredBilling: false }; + })); + } +} diff --git a/apps/api/src/domain/evolution-source.ts b/apps/api/src/domain/evolution-source.ts new file mode 100644 index 0000000..17837a8 --- /dev/null +++ b/apps/api/src/domain/evolution-source.ts @@ -0,0 +1,29 @@ +import { DomainError, type Evidence, type Project, type Run } from '@wishforge/contracts'; +import type { Transaction } from '../db/store.js'; +import { must } from './control-plane.js'; +import { verificationPolicyDigest } from './verification-policy.js'; +import { contentDigest } from '../../../../packages/evolution/src/index.js'; + +export interface CodeCandidateSource { + schemaVersion: 1; scope: 'tool' | 'platform' | 'trust_root'; sourceCommit: string; + baseCommit: string; gitBundleSha256: string; checkpointId: string; + artifactId?: string; verificationEvidenceId: string; changedPaths: string[]; + parentBundle: string; candidateDigest: string; +} +// These paths are a protected platform policy, never accepted from a candidate. +const trustRootPath = /(^|\/)(auth\.ts|service-tokens\.ts|policy\.ts|provider-proxy\.ts|connections\.ts|entitlements\.ts|billing\.ts|runner-broker\.ts|releases\.ts|evolution\.ts|evolution-source\.ts|verification-policy\.ts|workspace-integration\.ts|store\.ts|001_initial\.sql|signing\.[^/]+)$|^(packages\/(evolution|contracts)\/|apps\/api\/src\/(auth|db)\/|infra\/k8s\/base\/)/; + +export async function codeCandidateSource(tx: Transaction, run: Run): Promise { + if (run.purpose !== 'evolution' || run.noDeployment !== true || !['tool', 'platform'].includes(String(run.evolutionScope)) || !run.verifiedCommit || !run.checkpointId) throw new DomainError('UNVERIFIED_CODE_CANDIDATE', 'A verified code-generation task and checkpoint are required'); + const saved = await must(tx, 'checkpoint', run.checkpointId); + const cp = saved.checkpoint as Record | undefined; + const classification = saved.trustedClassification as { sourceCommit?: string; changedPaths?: string[] } | undefined; + const project = await must(tx, 'project', run.projectId); + if (!cp || saved.revision !== run.revision || saved.runId !== run.id || cp.sourceCommit !== run.verifiedCommit || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(String(cp.baseCommit)) || !/^[a-f0-9]{64}$/.test(String(cp.gitBundleSha256)) || classification?.sourceCommit !== run.verifiedCommit || !Array.isArray(classification.changedPaths) || classification.changedPaths.length === 0 || classification.changedPaths.some(p => typeof p !== 'string' || !p || p.startsWith('/') || p.split('/').includes('..'))) throw new DomainError('CODE_SOURCE_REQUIRED', 'Code proposals require an exact durable checkpoint and independently classified nonempty source patch'); + const evidence = (await tx.list('evidence')).find(e => e.runId === run.id && e.revision === run.revision && e.sourceCommit === run.verifiedCommit && e.type === 'verification' && e.passed && e.verificationPolicyDigest === verificationPolicyDigest(project)); + if (!evidence || run.verifiedPolicyDigest !== verificationPolicyDigest(project)) throw new DomainError('STALE_EVIDENCE', 'Code proposal acceptance must match the current protected verification policy'); + const changedPaths = [...new Set(classification.changedPaths)].sort(); + const scope: CodeCandidateSource['scope'] = changedPaths.some(p => trustRootPath.test(p)) ? 'trust_root' : run.evolutionScope as 'tool' | 'platform'; + const binding = { schemaVersion: 1 as const, scope, sourceCommit: run.verifiedCommit, baseCommit: String(cp.baseCommit), gitBundleSha256: String(cp.gitBundleSha256), parentBundle: String(run.baselineBundle) }; + return { ...binding, checkpointId: saved.id, ...(typeof cp.gitBundleArtifactId === 'string' ? { artifactId: cp.gitBundleArtifactId } : {}), verificationEvidenceId: evidence.id, changedPaths, candidateDigest: contentDigest(binding) }; +} diff --git a/apps/api/src/domain/evolution.ts b/apps/api/src/domain/evolution.ts new file mode 100644 index 0000000..4a6baf9 --- /dev/null +++ b/apps/api/src/domain/evolution.ts @@ -0,0 +1,207 @@ +import { DomainError, evolutionInput, type Actor, type Entity, type EvolutionCandidate, type Run } from '@wishforge/contracts'; +import { bundleConfigSchema, bundleDigest, BASELINE_BUNDLE, canaryBucket, contentDigest, observationSchema, signedEvaluationSchema, verifyRecord, type AgentBundleConfig, type SignedEvaluationReport } from '../../../../packages/evolution/src/index.js'; +import type { Store, Transaction } from '../db/store.js'; +import { record, touch, must, executionLease } from './control-plane.js'; +import { codeCandidateSource, type CodeCandidateSource } from './evolution-source.js'; +import { evaluationGate, requireHuman, requireRole } from './policy.js'; + +export interface Candidate extends EvolutionCandidate { sourceArtifact?: CodeCandidateSource; bundleConfig?: AgentBundleConfig; evaluation?: SignedEvaluationReport; shadowVerified?: boolean; canaryAudience?: 'internal' | 'opt_in'; observedRunIds?: string[]; approvalDigest?: string; externalRelease?: unknown; externalAction?: { id: string; action: 'rollout' | 'rollback'; status: 'requested' | 'observed'; deploymentId: string; imageDigest: string; allocationPercent: number; audience?: string; stageStartedAt?: string }; } +interface Bundle extends Entity { config: AgentBundleConfig; digest: string; } +interface Routing extends Entity { stableVersion: string; previousStableVersion?: string; } +const ROUTING_ID = 'evolution-routing-v1'; +const candidateSchema = evolutionInput.extend({ bundleConfig: bundleConfigSchema.optional() }); + +export async function resolveBundle(tx: Transaction, version: string): Promise { + if (version === 'baseline-v1') return structuredClone(BASELINE_BUNDLE); + const bundle = await tx.get('bundle', version); + if (!bundle || bundleDigest(bundle.config) !== version || bundle.digest !== version) throw new DomainError('BUNDLE_UNAVAILABLE', 'Pinned AgentBundle is absent or its immutable content changed'); + return bundleConfigSchema.parse(bundle.config); +} +/** Called once when creating a run. Recovery resolves the saved version and never reselects. */ +export async function selectBundle(tx: Transaction, input: { tenantId: string; projectId: string; runId: string; canaryOptIn?: boolean; internalProject?: boolean }): Promise<{ version: string; config: AgentBundleConfig; candidateId?: string }> { + const stable = (await tx.get('policy', ROUTING_ID))?.stableVersion ?? 'baseline-v1'; + const candidates = (await tx.list('evolution')).filter(c => c.status === 'canary' && c.parentBundle === stable && c.bundleConfig && c.scope !== 'platform' && c.scope !== 'trust_root'); + const candidate = candidates.find(c => (c.canaryAudience === 'internal' ? input.internalProject : input.canaryOptIn || input.internalProject) && canaryBucket(input.tenantId,input.projectId,input.runId,c.candidateDigest) < c.canaryPercent); + const version = candidate?.candidateDigest ?? stable; + return { version, config: await resolveBundle(tx, version), ...(candidate ? { candidateId: candidate.id } : {}) }; +} + +export class Evolution { + constructor(private store: Store, private env = process.env, private clock: () => number = Date.now) {} + list(actor: Actor) { return this.store.transaction(actor.tenantId, tx => tx.list('evolution')); } + async createCodeCandidate(actor: Actor, runId: string, leaseToken: number) { + if (actor.kind !== 'verifier' || actor.tenantId !== this.env.WF_SYSTEM_TENANT) throw new DomainError('FORBIDDEN', 'System independent verifier required', 403); + const prepared = await this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', runId); executionLease(actor, run, leaseToken); + if (run.generatedEvolutionCandidateId) return { previous: await must(tx, 'evolution', String(run.generatedEvolutionCandidateId)) }; + if (run.status !== 'running') throw new DomainError('RUN_STOPPED', 'Candidate extraction requires an active verifier'); + return { run, artifact: await codeCandidateSource(tx, run) }; + }); + if (prepared.previous) return prepared.previous; + const { run, artifact } = prepared; + return this.create(actor, { name: `Verified ${artifact!.scope} patch ${run!.id.slice(0, 8)}`, hypothesis: run!.goal.slice(0, 4000), scope: artifact!.scope, parentBundle: artifact!.parentBundle, candidateDigest: artifact!.candidateDigest, targetMetric: 'success', dataScope: 'platform' }, { runId, leaseToken, codeArtifact: artifact! }); + } + create(actor: Actor, input: unknown, source?: { runId: string; leaseToken: number; codeArtifact?: CodeCandidateSource }) { + requireRole(actor, ['owner','admin']); const data = candidateSchema.parse(input); + if (data.dataScope === 'platform' && actor.tenantId !== this.env.WF_SYSTEM_TENANT) throw new DomainError('CROSS_TENANT_LEARNING_DISABLED', 'Global evolution requires the separately funded platform tenant',403); + if (data.bundleConfig) { + if (!['prompt','orchestration'].includes(data.scope)) throw new DomainError('BUNDLE_SCOPE', 'Executable code and trust roots cannot be installed through prompt bundle configuration'); + if (bundleDigest(data.bundleConfig) !== data.candidateDigest) throw new DomainError('BUNDLE_DIGEST_MISMATCH', 'Candidate digest must address the complete bundle configuration'); + if (data.bundleConfig.model && !(this.env.WF_EVOLUTION_ALLOWED_MODELS ?? '').split(',').map(v => v.trim()).includes(data.bundleConfig.model)) throw new DomainError('MODEL_NOT_PREAUTHORIZED', 'Candidate model requires operator preauthorization',403); + } + return this.store.transaction(actor.tenantId, async tx => { + let generationRun: Run | undefined; + if (source) { + if (actor.kind !== 'verifier' || actor.tenantId !== this.env.WF_SYSTEM_TENANT) throw new DomainError('FORBIDDEN', 'Candidate extraction requires the system verifier', 403); + generationRun = await must(tx, 'run', source.runId); executionLease(actor, generationRun, source.leaseToken); + if (generationRun.purpose !== 'evolution' || generationRun.noDeployment !== true || !generationRun.verifiedCommit || data.parentBundle !== generationRun.baselineBundle || data.scope !== (source.codeArtifact?.scope ?? generationRun.evolutionScope)) throw new DomainError('UNVERIFIED_CANDIDATE', 'Candidate must match the independently verified evolution task and fixed baseline'); + if (source.codeArtifact && contentDigest(await codeCandidateSource(tx, generationRun)) !== contentDigest(source.codeArtifact)) throw new DomainError('STALE_EVIDENCE', 'Code candidate source changed while recording'); + if (generationRun.generatedEvolutionCandidateId) { const previous = await must(tx, 'evolution', String(generationRun.generatedEvolutionCandidateId)); if (previous.candidateDigest !== data.candidateDigest) throw new DomainError('IDEMPOTENCY_CONFLICT', 'This generation task already produced a different candidate'); return previous; } + } + const stable = (await tx.get('policy',ROUTING_ID))?.stableVersion ?? 'baseline-v1'; + if (data.bundleConfig && data.parentBundle !== stable) throw new DomainError('BASELINE_CHANGED', 'Evaluate against the current stable bundle'); + if (data.bundleConfig) { + const existing = await tx.get('bundle',data.candidateDigest); + if (existing && contentDigest(existing.config) !== contentDigest(data.bundleConfig)) throw new DomainError('IMMUTABLE_BUNDLE', 'Bundle content is immutable'); + if (!existing) await tx.put('bundle',{ ...record(actor.tenantId),id: data.candidateDigest,digest:data.candidateDigest,config:data.bundleConfig }); + } + const c: Candidate = { ...record(actor.tenantId),...data,...(source?.codeArtifact ? { sourceArtifact: source.codeArtifact } : {}),status:'proposed',canaryPercent:0,canaryCompletedRuns:0,canaryFailures:0,observedRunIds:[] }; + await tx.put('evolution',c); + if (generationRun) { + if (generationRun.providerProxyActiveRequest) throw new DomainError('MODEL_USAGE_UNCONFIRMED', 'Model usage must settle before recording a generated candidate'); generationRun.generatedEvolutionCandidateId = c.id; generationRun.reservedTokens = 0; generationRun.status = 'waiting'; generationRun.waitingReason = 'evolution_evaluation'; + if (generationRun.lastActiveAt) generationRun.activeMilliseconds += Math.max(0, Math.min(this.clock(), Date.parse(generationRun.lease!.expiresAt)) - Date.parse(generationRun.lastActiveAt)); + generationRun.lastActiveAt = undefined; + await tx.put('run', touch(generationRun)); await tx.event(generationRun.id, 'evolution.candidate.generated', 'Verified candidate recorded; independent evaluation and promotion are still required.', { candidateId: c.id, candidateDigest: c.candidateDigest }); + } + return c; + }); + } + private verify(input: { signature: string; keyId: string; issuedAt: string; tenantId: string; candidateId: string; candidateDigest: string; [key: string]: unknown }, actor: Actor, candidate: Candidate, platform = false) { + let keys: Record = {}; + try { keys = JSON.parse((platform ? this.env.WF_PLATFORM_RELEASE_PUBLIC_KEYS : this.env.WF_EVALUATOR_PUBLIC_KEYS) ?? '{}'); } catch { throw new DomainError('EVALUATOR_UNCONFIGURED','Operator verification key configuration is invalid',503); } + const key = keys[input.keyId]; + if (!key) throw new DomainError('EVALUATOR_UNCONFIGURED','No trusted Ed25519 verification key is configured for this issuer',503); + if (!verifyRecord(input,key)) throw new DomainError('INVALID_EVALUATION_SIGNATURE','Independent evidence signature is invalid',403); + if (input.tenantId !== actor.tenantId || input.candidateId !== candidate.id || input.candidateDigest !== candidate.candidateDigest) throw new DomainError('EVIDENCE_BINDING_MISMATCH','Evidence is bound to a different tenant, candidate or version'); + const age = this.clock()-Date.parse(input.issuedAt); + if (age < -60_000 || age > 7*86400000) throw new DomainError('EVIDENCE_EXPIRED','Evidence must have been issued within the last seven days'); + } + evaluate(actor: Actor, id: string, input: unknown) { + if (actor.kind !== 'evaluator') throw new DomainError('FORBIDDEN','Independent evaluator identity required',403); + const report = signedEvaluationSchema.parse(input); + return this.store.transaction(actor.tenantId,async tx => { + const c = await must(tx,'evolution',id); this.verify(report,actor,c); + if(report.targetMetric!==c.targetMetric)throw new DomainError('EVIDENCE_BINDING_MISMATCH','Evaluation target metric differs from the declared hypothesis'); + if (!['proposed','evaluating','paused'].includes(c.status)) throw new DomainError('INVALID_CANDIDATE_STATE','Candidate is not awaiting evaluation'); + const failures = evaluationGate(report,c); c.evaluation=report; c.evaluationFailures=failures; c.status=failures.length?'rejected':'shadowing'; + c.shadowVerified=false; c.approvedBy=undefined; c.approvalDigest=undefined; + await tx.put('evolution',touch(c)); return c; + }); + } + private requestExternal(c: Candidate, action: 'rollout' | 'rollback') { + const release = c.externalRelease as { deploymentId: string; imageDigest: string; previousImageDigest?: string } | undefined; + if (!release || (action === 'rollback' && !release.previousImageDigest)) throw new DomainError('EXTERNAL_RELEASE_REQUIRED', 'Independent release identity and a compatible previous image are required'); + const request = { action, status: 'requested' as const, deploymentId: release.deploymentId, imageDigest: action === 'rollback' ? release.previousImageDigest! : release.imageDigest, allocationPercent: action === 'rollback' ? 0 : c.canaryPercent, audience: c.canaryAudience, stageStartedAt: c.canaryStartedAt }; + c.externalAction = { ...request, id: contentDigest([c.id, request]) }; + } + async rolloutTick(actor: Actor) { + if (!this.env.WF_SYSTEM_TENANT || actor.tenantId !== this.env.WF_SYSTEM_TENANT || actor.runId || !['human', 'evaluator'].includes(actor.kind)) throw new DomainError('FORBIDDEN', 'System operator or independent evaluator required', 403); + requireRole(actor, ['owner', 'admin']); + if (this.env.WF_EVOLUTION_AUTO_PROMOTION !== 'true') return { status: 'unconfigured', reason: 'Automatic promotion requires operator preauthorization', outcomes: [] }; + const candidates = (await this.list(actor)).filter(c => c.scope !== 'trust_root' && ['shadowing', 'canary'].includes(c.status)).slice(0, 50); + const outcomes = []; + for (const candidate of candidates) { + const action = candidate.status === 'shadowing' && candidate.shadowVerified ? 'start_canary' : candidate.status === 'canary' && candidate.canaryCompletedRuns >= 30 && candidate.canaryFailures === 0 && this.clock() - Date.parse(candidate.canaryStartedAt ?? '') >= 86400000 ? 'advance' : undefined; + if (!action) continue; + try { const updated = await this.command(actor, candidate.id, action); outcomes.push({ id: candidate.id, action, status: updated.status, percent: updated.canaryPercent }); } + catch (error) { if (!(error instanceof DomainError)) throw error; outcomes.push({ id: candidate.id, action, blocked: error.code }); } + } + return { status: 'processed', outcomes }; + } + private binding(c: Candidate) { return contentDigest({ candidateDigest:c.candidateDigest,parentBundle:c.parentBundle,evaluation:c.evaluation,externalRelease:c.externalRelease }); } + async command(actor: Actor,id: string,action: string) { + requireRole(actor,['owner','admin']); + return this.store.transaction(actor.tenantId,async tx => { + const c=await must(tx,'evolution',id); + if (action === 'approve') { requireHuman(actor); if(c.scope==='trust_root')throw new DomainError('EXTERNAL_TRUST_ROOT_RELEASE_REQUIRED','Trust root changes use the separate operator release channel'); c.approvedBy=actor.userId;c.approvalDigest=this.binding(c); } + else if(action === 'start_shadow') { if(!['proposed','evaluating','paused'].includes(c.status)||!c.evaluation||evaluationGate(c.evaluation,c).length)throw new DomainError('EVALUATION_REQUIRED','Independent evaluation must pass before shadowing');c.status='shadowing';c.shadowVerified=false; } + else if(action === 'start_canary') { + if(c.status!=='shadowing'||!c.shadowVerified||!c.evaluation||evaluationGate(c.evaluation,c).length)throw new DomainError('SHADOW_EVIDENCE_REQUIRED','Signed no-production-write shadow evidence and passing evaluation are required'); + if(c.scope==='trust_root')throw new DomainError('EXTERNAL_TRUST_ROOT_RELEASE_REQUIRED','Trust roots are outside the automatic rollout channel'); + if(!c.bundleConfig&&(!c.externalRelease||!c.approvedBy||c.approvalDigest!==this.binding(c)))throw new DomainError('EXTERNAL_RELEASE_REQUIRED','Code changes need independent release evidence and artifact-bound human approval'); + if(c.bundleConfig) { + const stable=(await tx.get('policy',ROUTING_ID))?.stableVersion??'baseline-v1'; + if(c.parentBundle!==stable)throw new DomainError('BASELINE_CHANGED','Reevaluate against the new stable version'); + if((await tx.list('evolution')).some(other=>other.id!==id&&other.status==='canary'))throw new DomainError('CANARY_BUSY','Another candidate already occupies the canary channel'); + } + if (!c.bundleConfig && !(c.externalRelease as {previousImageDigest?:string})?.previousImageDigest) throw new DomainError('EXTERNAL_RELEASE_REQUIRED', 'Code canary requires the preceding compatible stable image'); + c.status='canary';c.canaryPercent=5;c.canaryAudience='internal';c.canaryCompletedRuns=0;c.canaryFailures=0;c.observedRunIds=[];c.canaryStartedAt=new Date(this.clock()).toISOString(); + if (!c.bundleConfig) this.requestExternal(c, 'rollout'); + } else if(action==='advance') { + if(c.status!=='canary'||!c.canaryStartedAt||this.clock()-Date.parse(c.canaryStartedAt)<86400000||c.canaryCompletedRuns<30||c.canaryFailures>0)throw new DomainError('CANARY_EVIDENCE_REQUIRED','Each audience and percentage stage needs 24 hours, 30 accepted tasks and no gate failures'); + if(c.canaryAudience==='internal'){c.canaryAudience='opt_in';c.canaryPercent=5;} + else if(c.canaryPercent<100)c.canaryPercent=c.canaryPercent===5?25:100; + else { + c.status='promoted'; + if(c.bundleConfig){ const routing=await tx.get('policy',ROUTING_ID);await tx.put('policy',{...(routing?touch(routing):record(actor.tenantId)),id:ROUTING_ID,stableVersion:c.candidateDigest,previousStableVersion:c.parentBundle}); } + } + c.canaryCompletedRuns=0;c.canaryStartedAt=new Date(this.clock()).toISOString(); + if (!c.bundleConfig && c.status === 'canary') this.requestExternal(c, 'rollout'); + } else if(action==='rollback') { + if (!c.bundleConfig) { this.requestExternal(c, 'rollback'); c.status='paused'; c.canaryPercent=0; await tx.put('evolution',touch(c)); return c; } + c.status='rolled_back';c.canaryPercent=0; + const routing=await tx.get('policy',ROUTING_ID); + if(routing?.stableVersion===c.candidateDigest){routing.stableVersion=c.parentBundle;await resolveBundle(tx,routing.stableVersion);await tx.put('policy',touch(routing));} + } else throw new DomainError('INVALID_COMMAND','Unknown evolution action',400); + await tx.put('evolution',touch(c));return c; + }); + } + async observe(actor: Actor,id: string,input: unknown) { + if(actor.kind!=='evaluator')throw new DomainError('FORBIDDEN','Independent evaluator required',403); + const observation=observationSchema.parse(input); + return this.store.transaction(actor.tenantId,async tx=>{ + const c=await must(tx,'evolution',id);this.verify(observation,actor,c,observation.kind.startsWith('platform_')); + const key=`evolution:${id}:${observation.operationId}`,hash=contentDigest(observation),existing=await tx.idempotency(key); + if(existing){if(existing.digest!==hash)throw new DomainError('IDEMPOTENCY_CONFLICT','Observation ID reused with different evidence');return c;} + if(observation.kind==='shadow') { + if(c.status!=='shadowing')throw new DomainError('INVALID_CANDIDATE_STATE','Candidate is not shadowing'); + c.shadowVerified=observation.hardGateFailures===0;c.shadowEvidence=observation; + if(observation.hardGateFailures)c.status='rejected'; + } else if(observation.kind==='platform_release') { + if(c.bundleConfig||c.scope==='trust_root')throw new DomainError('INVALID_CANDIDATE_STATE','External code evidence cannot change bundle or trust-root permissions'); + if(c.sourceArtifact && observation.sourceCommit !== c.sourceArtifact.sourceCommit) throw new DomainError('EVIDENCE_BINDING_MISMATCH','Release must build the independently verified source proposal'); + if(observation.releaseDigest!==c.candidateDigest)throw new DomainError('EVIDENCE_BINDING_MISMATCH','External release digest differs from the candidate'); + c.externalRelease=observation;c.approvedBy=undefined;c.approvalDigest=undefined; + } else if (observation.kind === 'platform_canary') { + const release = c.externalRelease as { deploymentId: string; imageDigest: string; sourceCommit: string } | undefined; + if (c.bundleConfig || c.status !== 'canary' || !release || observation.deploymentId !== release.deploymentId || observation.imageDigest !== release.imageDigest || observation.sourceCommit !== release.sourceCommit || observation.stageStartedAt !== c.canaryStartedAt || observation.allocationPercent !== c.canaryPercent || observation.audience !== c.canaryAudience) throw new DomainError('STALE_CANARY_OBSERVATION', 'Independent code rollout evidence must bind this exact artifact, deployment and stage'); + const seen = new Set(c.observedRunIds ?? []); + for (const sample of observation.samples) { + if (seen.has(sample.id)) continue; + if (Date.parse(sample.startedAt) < Date.parse(c.canaryStartedAt!) || Date.parse(sample.completedAt) < Date.parse(sample.startedAt) || Date.parse(sample.completedAt) > Date.parse(observation.issuedAt)) throw new DomainError('INVALID_CANARY_RUN', 'External sample timestamps must be within this stage and evidence window'); + seen.add(sample.id); c.canaryCompletedRuns += sample.passed ? 1 : 0; c.canaryFailures += sample.passed ? 0 : 1; + } + c.observedRunIds = [...seen]; c.canaryFailures += observation.hardGateFailures; + if (c.externalAction?.action === 'rollout') c.externalAction.status = 'observed'; + if (c.canaryFailures > 0) { this.requestExternal(c, 'rollback'); c.status = 'paused'; c.canaryPercent = 0; } + } else if (observation.kind === 'platform_rollback') { + const action = c.externalAction; + if (c.bundleConfig || c.status !== 'paused' || !action || action.action !== 'rollback' || action.id !== observation.actionId || action.deploymentId !== observation.deploymentId || action.imageDigest !== observation.restoredImageDigest) throw new DomainError('EVIDENCE_BINDING_MISMATCH', 'Rollback receipt must match the pending independent rollback action'); + action.status = 'observed'; c.status = 'rolled_back'; c.canaryPercent = 0; c.externalRollbackEvidence = observation; + } else { + if(c.status!=='canary'||observation.stageStartedAt!==c.canaryStartedAt)throw new DomainError('STALE_CANARY_OBSERVATION','Observation is not for the active canary stage'); + if(!c.bundleConfig)throw new DomainError('EXTERNAL_CANARY_REQUIRED','Platform code rollout remains managed by the independent release system'); + const observed=new Set(c.observedRunIds??[]); + for(const runId of new Set(observation.runIds)) { + if(observed.has(runId))continue; + const run=await must(tx,'run',runId); + if(run.bundleVersion!==c.candidateDigest||run.evolutionCandidateId!==c.id||Date.parse(run.createdAt)0){c.status='rolled_back';c.canaryPercent=0;} + } + await tx.put('evolution',touch(c));await tx.remember(key,hash,{accepted:true});return c; + }); + } +} diff --git a/apps/api/src/domain/gateway-target.ts b/apps/api/src/domain/gateway-target.ts new file mode 100644 index 0000000..15d4629 --- /dev/null +++ b/apps/api/src/domain/gateway-target.ts @@ -0,0 +1,19 @@ +import {readFile} from 'node:fs/promises'; +import {z} from 'zod'; +import {DomainError} from '@wishforge/contracts'; +const entry=z.object({internalUrl:z.string().max(2048),publicUrl:z.string().max(2048),tokenEnv:z.string().regex(/^WF_[A-Z0-9_]{1,100}_TOKEN$/)}).strict(); +const schema=z.object({schemaVersion:z.literal(1),tenants:z.record(z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),entry)}).strict(); +export interface GatewayTarget{internalUrl:string;publicUrl:string;token:string} +function origin(raw:string,env:NodeJS.ProcessEnv){let value:URL;try{value=new URL(raw);}catch{throw new DomainError('GATEWAY_CONFIGURATION_INVALID','Gateway URL is invalid',503);}if(value.username||value.password||value.pathname!=='/'||value.search||value.hash||!(value.protocol==='https:'||(env.NODE_ENV!=='production'&&value.protocol==='http:'&&['127.0.0.1','localhost','[::1]'].includes(value.hostname))))throw new DomainError('GATEWAY_CONFIGURATION_INVALID','Gateway requires an HTTPS origin (development loopback excepted)',503);return value.origin;} +async function mapping(file:string){try{const bytes=await readFile(file);if(bytes.length>65536)throw Error();return schema.parse(JSON.parse(bytes.toString('utf8')));}catch{throw new DomainError('GATEWAY_CONFIGURATION_INVALID','Operator tenant gateway map is unreadable or invalid',503);}} +export async function resolveGatewayTarget(env:NodeJS.ProcessEnv,tenantId:string):Promise{ + if(!/^[A-Za-z0-9_-]{1,128}$/.test(tenantId))throw new DomainError('GATEWAY_CONFIGURATION_INVALID','Invalid gateway tenant scope',503); + let config:{internalUrl:string;publicUrl:string;tokenEnv:string}|undefined; + if(env.WF_WORKSPACE_GATEWAY_TARGETS_FILE){const map=await mapping(env.WF_WORKSPACE_GATEWAY_TARGETS_FILE);config=Object.prototype.hasOwnProperty.call(map.tenants,tenantId)?map.tenants[tenantId]:undefined;if(!config)return;for(const [otherId,other] of Object.entries(map.tenants)){if(otherId===tenantId)continue;if(origin(other.publicUrl,env)===origin(config.publicUrl,env)||(env[config.tokenEnv]&&env[config.tokenEnv]===env[other.tokenEnv]))throw new DomainError('GATEWAY_CONFIGURATION_INVALID','Tenant gateways require distinct public origins and service credentials',503);}} + else{if(!env.WF_WORKSPACE_GATEWAY_BASE&&!env.WF_WORKSPACE_GATEWAY_TOKEN)return;const tenants=[...new Set((env.WF_DISPATCH_TENANTS??'').split(',').map(x=>x.trim()).filter(Boolean))];const bound=env.WF_WORKSPACE_GATEWAY_TENANT_ID??(tenants.length===1?tenants[0]:undefined);if(!bound)throw new DomainError('GATEWAY_TENANT_BINDING_REQUIRED','A legacy gateway must be explicitly bound to one tenant; configure a tenant gateway map for multiple tenants',503);if(bound!==tenantId)return;config={internalUrl:env.WF_WORKSPACE_GATEWAY_BASE??'',publicUrl:env.WF_IDE_PUBLIC_URL??env.WF_WORKSPACE_GATEWAY_BASE??'',tokenEnv:'WF_WORKSPACE_GATEWAY_TOKEN'};} + const token=env[config.tokenEnv];if(!token||token.length<32)throw new DomainError('GATEWAY_CONFIGURATION_INVALID','Gateway requires a tenant-scoped service token',503); + return{internalUrl:origin(config.internalUrl,env),publicUrl:origin(config.publicUrl,env),token}; +} +/** All known platform gateway origins are protected from untrusted application hosting. */ +export async function gatewayIdentityOrigins(env:NodeJS.ProcessEnv):Promise{if(env.WF_WORKSPACE_GATEWAY_TARGETS_FILE){const map=await mapping(env.WF_WORKSPACE_GATEWAY_TARGETS_FILE);return[...new Set(Object.values(map.tenants).flatMap(item=>[origin(item.internalUrl,env),origin(item.publicUrl,env)]))];}return[env.WF_WORKSPACE_GATEWAY_BASE,env.WF_IDE_PUBLIC_URL].filter((value):value is string=>!!value).map(value=>origin(value,env));} +export function validateGatewayLaunch(target:GatewayTarget,payload:unknown){const value=payload as {launchUrl?:unknown;expiresIn?:unknown};let url:URL;try{if(typeof value?.launchUrl!=='string')throw Error();url=new URL(value.launchUrl);}catch{throw new DomainError('INVALID_GATEWAY_LAUNCH','Gateway did not return a valid one-time launch URL',502);}const keys=[...url.searchParams.keys()];if(url.origin!==target.publicUrl||url.pathname!=='/session'||url.username||url.password||url.hash||keys.length!==1||keys[0]!=='code'||!/^[A-Za-z0-9_-]{40,128}$/.test(url.searchParams.get('code')??'')||value.expiresIn!==30)throw new DomainError('INVALID_GATEWAY_LAUNCH','One-time launch URL does not match the assigned tenant gateway',502);return{launchUrl:url.toString(),expiresIn:30};} diff --git a/apps/api/src/domain/git-storage.ts b/apps/api/src/domain/git-storage.ts new file mode 100644 index 0000000..9c32e78 --- /dev/null +++ b/apps/api/src/domain/git-storage.ts @@ -0,0 +1,21 @@ +import { DomainError, type Actor, type Project, type Run } from '@wishforge/contracts'; + +/** Only the trusted control plane can provision repositories or mint repository-scoped access. */ +export class GitStorage { + constructor(private env = process.env, private fetcher: typeof fetch = fetch) {} + configured() { return Boolean(this.env.WF_GIT_SERVICE_URL && this.env.WF_GIT_ADMIN_TOKEN); } + private async request(route: string, body: unknown): Promise { + if (!this.configured()) throw new DomainError('GIT_STORAGE_UNCONFIGURED', 'Platform Git storage must be configured for new projects', 503); + const base = new URL(this.env.WF_GIT_SERVICE_URL!); + if (base.protocol !== 'https:' && !(this.env.NODE_ENV !== 'production' && ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname))) throw new DomainError('INSECURE_GIT_STORAGE', 'Git control transport requires HTTPS', 503); + const response = await this.fetcher(new URL(route, base), { method: 'POST', headers: { Authorization: `Bearer ${this.env.WF_GIT_ADMIN_TOKEN}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(15000) }); + if (!response.ok) throw new DomainError('GIT_STORAGE_UNAVAILABLE', 'Repository storage operation failed; retry provisioning after checking the service', 503); + return response.json() as Promise; + } + provision(project: Project) { return this.request<{ repositoryUrl: string; initialCommit: string; defaultBranch: string }>('/repos', { tenantId: project.tenantId, projectId: project.id, defaultBranch: project.targetBranch }); } + async credential(actor: Actor, project: Project, run: Run) { + if (project.repositoryStorage !== 'platform' || !['worker', 'verifier'].includes(actor.kind) || !run.lease || Date.parse(run.lease.expiresAt) <= Date.now() || run.status !== 'running') return undefined; + if (actor.runId && actor.runId !== run.id) throw new DomainError('FORBIDDEN', 'Git access is scoped to the assigned run', 403); + return this.request<{ token: string; expiresAt: string }>('/tokens', { tenantId: project.tenantId, projectId: project.id, runId: run.id, permission: actor.kind === 'verifier' ? 'write' : 'read', ttlSeconds: 900 }); + } +} diff --git a/apps/api/src/domain/github.ts b/apps/api/src/domain/github.ts new file mode 100644 index 0000000..2ef7c51 --- /dev/null +++ b/apps/api/src/domain/github.ts @@ -0,0 +1,171 @@ +import { createHash } from 'node:crypto'; +import { z } from 'zod'; +import { DomainError, type Actor, type Entity, type Project, type Run, type GitHubDeliveryState } from '@wishforge/contracts'; +import { GitHubApp, GitHubError, operationMarker, type PullRequestIntent, type PullRequestSnapshot, type RepositoryScope } from '../../../../packages/github/src/index.js'; +import type { Store, Transaction } from '../db/store.js'; +import { executionLease, executionScope, must, projectAccess, record, touch } from './control-plane.js'; +import { digest, requireHuman, requireRole } from './policy.js'; + +const createInput = z.object({ operationId: z.string().regex(/^[a-zA-Z0-9_-]{8,100}$/), title: z.string().trim().min(1).max(200), body: z.string().max(20000), headBranch: z.string().min(1).max(200), baseBranch: z.string().min(1).max(200), expectedHeadSha: z.string().regex(/^[a-f0-9]{40}$/), expectedBaseSha: z.string().regex(/^[a-f0-9]{40}$/) }).strict(); +export interface GitHubOperation extends Entity { projectId: string; runId: string; revision: number; repositoryUrl: string; scope: RepositoryScope; intent: PullRequestIntent; inputDigest: string; status: 'creating' | 'unknown' | 'open' | 'closed' | 'failed' | 'merging' | 'merge_unknown' | 'merge_pending' | 'merged' | 'reverification_required' | 'stale'; snapshot?: PullRequestSnapshot; mergeAttempted?: boolean; mergeApproval?: { actorId: string; headSha: string; baseSha: string; revision: number; grantedAt: string }; errorCode?: string } +export class GitHubIntegration { + readonly app: GitHubApp; + constructor(private store: Store, env = process.env, app?: GitHubApp) { this.app = app ?? new GitHubApp(env); } + async status(actor: Actor, projectId: string) { + const project = await this.store.transaction(actor.tenantId, tx => projectAccess(tx, actor, projectId)); + if (!this.app.configured()) return { configured: false, enabled: false, reason: 'GITHUB_UNCONFIGURED' }; + try { const scope = await this.app.scope(actor.tenantId, project.repositoryUrl ?? ''); return { configured: true, enabled: true, repository: `${scope.owner}/${scope.name}`, allowedBaseBranches: scope.allowedBaseBranches, allowAutomaticMerge: scope.allowAutomaticMerge === true }; } + catch (error) { if (error instanceof GitHubError) return { configured: true, enabled: false, reason: error.code }; throw error; } + } + async requiresPullRequest(project: Project): Promise { + if (project.repositoryStorage === 'platform' || !project.repositoryUrl) return false; + let url: URL; try { url = new URL(project.repositoryUrl); } catch { return false; } + if (url.hostname.toLowerCase() === 'github.com') return true; + if (!this.app.configured()) return false; + const configuration = await this.app.configuration(); + return url.origin === new URL(configuration.webOrigin ?? 'https://github.com').origin; + } + async credential(actor: Actor, project: Project, run: Run) { + if (!['worker', 'verifier'].includes(actor.kind) || !run.lease || run.status !== 'running' || Date.parse(run.lease.expiresAt) <= Date.now()) return undefined; + if (!await this.requiresPullRequest(project)) return undefined; + await this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'run', run.id); executionLease(actor, current, run.lease!.token); const saved = await must(tx, 'project', current.projectId); if (saved.id !== project.id || saved.repositoryUrl !== project.repositoryUrl) throw new DomainError('GITHUB_SCOPE_CHANGED', 'Repository changed'); }); + try { + const scope = await this.app.scope(actor.tenantId, project.repositoryUrl ?? ''); const credential = await this.app.token(scope, actor.kind === 'verifier' ? 'write' : 'read'); + await this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'run', run.id); executionLease(actor, current, run.lease!.token); if (current.status !== 'running') throw new DomainError('RUN_STOPPED', 'Run stopped while issuing repository credentials'); }); + return { ...credential, repositoryUrl: project.repositoryUrl!, username: 'x-access-token' }; + } catch (error) { throw this.error(error); } + } + private async access(tx: Transaction, actor: Actor, operation: GitHubOperation) { + await projectAccess(tx, actor, operation.projectId); + if (!['human', 'connector'].includes(actor.kind)) executionScope(actor, await must(tx, 'run', operation.runId)); + } + private writer(actor: Actor) { if (actor.kind === 'verifier') return; requireRole(actor, ['owner', 'admin', 'developer']); if (!['human', 'connector'].includes(actor.kind)) throw new DomainError('FORBIDDEN', 'Only a project developer or independent verifier may create a pull request', 403); } + private async currentScope(operation: GitHubOperation) { + const scope = await this.app.scope(operation.tenantId, operation.repositoryUrl); + if (scope.repositoryId !== operation.scope.repositoryId || scope.installationId !== operation.scope.installationId || scope.apiBaseUrl !== operation.scope.apiBaseUrl) throw new GitHubError('GITHUB_SCOPE_CHANGED', 'Operator repository mapping changed'); + return scope; + } + private async verifierLease(actor: Actor, runId: string, leaseToken: number) { + if (actor.kind !== 'verifier') throw new DomainError('FORBIDDEN', 'Independent verifier required for GitHub delivery', 403); + return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', runId); executionLease(actor, run, leaseToken); if (run.status !== 'running') throw new DomainError('RUN_STOPPED', 'GitHub delivery requires an active verifier'); return { run, project: await must(tx, 'project', run.projectId) }; }); + } + private deliveryOperation(operation: GitHubOperation): NonNullable { + return { id: operation.id, revision: operation.revision, status: operation.status, headBranch: operation.intent.headBranch, baseBranch: operation.intent.baseBranch, expectedHeadSha: operation.intent.expectedHeadSha, expectedBaseSha: operation.intent.expectedBaseSha, mergeApproved: !!operation.mergeApproval, mergeAttempted: operation.mergeAttempted === true, pullRequestUrl: operation.snapshot?.url, mergedCommitSha: operation.snapshot?.merged ? operation.snapshot.mergeCommitSha ?? undefined : undefined }; + } + async workerState(actor: Actor, runId: string, leaseToken: number): Promise { + const { run, project } = await this.verifierLease(actor, runId, leaseToken); + if (!await this.requiresPullRequest(project)) return { required: false, enabled: false }; + const status = await this.status(actor, project.id); + if (!status.enabled) return { required: true, enabled: false, reason: status.reason }; + const operation = await this.store.transaction(actor.tenantId, async tx => { + const pinned = run.githubOperationId ? await tx.get('github_operation', String(run.githubOperationId)) : undefined; + if (pinned?.runId === runId && pinned.revision === run.revision) return pinned; + return (await tx.list('github_operation')).filter(op => op.runId === runId && op.revision === run.revision).sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0]; + }); + return { required: true, enabled: true, allowAutomaticMerge: status.allowAutomaticMerge === true, ...(operation ? { operation: this.deliveryOperation(operation) } : {}) }; + } + async workerCreate(actor: Actor, runId: string, input: unknown): Promise { + const data = z.object({ leaseToken: z.number().int().positive(), candidateCommit: z.string().regex(/^[a-f0-9]{40}$/), expectedBaseCommit: z.string().regex(/^[a-f0-9]{40}$/), headBranch: z.string() }).strict().parse(input); + const { run, project } = await this.verifierLease(actor, runId, data.leaseToken); + if (data.headBranch !== `wishforge/${runId}/${data.candidateCommit}` || run.verifiedCommit !== data.candidateCommit) throw new DomainError('GITHUB_UNVERIFIED_HEAD', 'Only the verified immutable run review branch can be submitted'); + await this.store.transaction(actor.tenantId, async tx => { + const checkpoint = run.checkpointId ? await tx.get('checkpoint', run.checkpointId) : undefined; + const portable = checkpoint?.checkpoint as { sourceCommit?: string; baseCommit?: string } | undefined; + if (checkpoint?.runId !== runId || checkpoint.revision !== run.revision || portable?.sourceCommit !== data.candidateCommit || portable.baseCommit !== data.expectedBaseCommit) throw new DomainError('GITHUB_CHECKPOINT_MISMATCH', 'Review head and target must match the verified candidate checkpoint'); + }); + const current = await this.workerState(actor, runId, data.leaseToken); if (current.operation || !current.enabled) return current; + await this.createPullRequest(actor, runId, { operationId: `candidate-${run.revision}-${data.candidateCommit}`, title: `WishForge: ${run.goal.slice(0, 140)}`, body: `Verified candidate for requirement revision ${run.revision}. Independent verification must run again on the actual merge commit before build or release.`, headBranch: data.headBranch, baseBranch: project.targetBranch, expectedHeadSha: data.candidateCommit, expectedBaseSha: data.expectedBaseCommit }); + return this.workerState(actor, runId, data.leaseToken); + } + async workerAdvance(actor: Actor, runId: string, input: unknown): Promise { + const data = z.object({ leaseToken: z.number().int().positive(), operationId: z.string().min(1) }).strict().parse(input); + const { run } = await this.verifierLease(actor, runId, data.leaseToken); + const owned = await this.store.transaction(actor.tenantId, tx => must(tx, 'github_operation', data.operationId)); + if (owned.runId !== runId || owned.revision !== run.revision) throw new DomainError('GITHUB_OPERATION_SCOPE', 'Review belongs to another run or requirement revision', 403); + let operation = await this.reconcilePullRequest(actor, data.operationId); + await this.verifierLease(actor, runId, data.leaseToken); + if (!operation.snapshot?.merged && operation.status === 'open') { + try { operation = await this.merge(actor, operation.id); } + catch (error) { if (!(error instanceof DomainError && error.code === 'GITHUB_MERGE_NOT_AUTHORIZED')) throw error; return { ...(await this.workerState(actor, runId, data.leaseToken)), reason: 'github_merge_approval' }; } + } + return { ...(await this.workerState(actor, runId, data.leaseToken)), operation: this.deliveryOperation(operation), reason: operation.snapshot?.merged ? undefined : ['unknown', 'merge_unknown', 'creating', 'merging'].includes(operation.status) ? 'github_outcome_unknown' : operation.status === 'stale' ? 'github_candidate_stale' : 'github_merge_pending' }; + } + async createPullRequest(actor: Actor, runId: string, input: unknown) { + this.writer(actor); const data = createInput.parse(input); + const source = await this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', runId); const project = await projectAccess(tx, actor, run.projectId); if (actor.kind === 'verifier') executionScope(actor, run); return { run, project }; }); + let scope: RepositoryScope; try { scope = await this.app.scope(actor.tenantId, source.project.repositoryUrl ?? ''); } catch (error) { throw this.error(error); } + if (data.baseBranch !== source.project.targetBranch || !scope.allowedBaseBranches.includes(data.baseBranch) || !(data.headBranch === `wishforge/${runId}` || data.headBranch.startsWith(`wishforge/${runId}/`))) throw new DomainError('GITHUB_BRANCH_DENIED', 'PR must use this run branch and the protected project target'); + const id = `gh-${createHash('sha256').update(JSON.stringify([actor.tenantId, runId, data.operationId])).digest('hex')}`; + const prepared = await this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', runId); const project = await projectAccess(tx, actor, run.projectId); + const previous = await tx.get('github_operation', id); + if (previous) { if (previous.inputDigest !== digest(data)) throw new DomainError('IDEMPOTENCY_CONFLICT', 'GitHub operation ID was already used for a different candidate'); return { operation: previous, dispatch: false }; } + if (run.verifiedCommit !== data.expectedHeadSha || run.revision !== source.run.revision || ['paused', 'canceled', 'failed'].includes(run.status) || project.repositoryUrl !== source.project.repositoryUrl) throw new DomainError('GITHUB_UNVERIFIED_HEAD', 'PR creation requires this exact independently verified candidate'); + const { operationId: _, ...rest } = data; + const operation: GitHubOperation = { ...record(actor.tenantId), id, projectId: project.id, runId, revision: run.revision, repositoryUrl: project.repositoryUrl!, scope, inputDigest: digest(data), intent: { ...rest, operationMarker: operationMarker(actor.tenantId, runId, data.operationId) }, status: 'creating' }; + await tx.put('github_operation', operation); run.githubOperationId = id; await tx.put('run', touch(run)); await tx.event(runId, 'github.pr.requested', 'Pull request creation recorded before contacting GitHub.', { operationId: id }); return { operation, dispatch: true }; + }); + if (!prepared.dispatch) return this.reconcilePullRequest(actor, id); + try { return await this.recordSnapshot(actor, id, await this.app.createPullRequest(scope, prepared.operation.intent)); } + catch (error) { await this.failure(actor, id, error, false); throw this.error(error); } + } + async readPullRequest(actor: Actor, id: string) { return this.reconcilePullRequest(actor, id); } + async reconcilePullRequest(actor: Actor, id: string) { + const operation = await this.store.transaction(actor.tenantId, async tx => { const found = await must(tx, 'github_operation', id); await this.access(tx, actor, found); return found; }); + try { + const scope = await this.currentScope(operation); + const snapshot = operation.snapshot ? await this.app.readPullRequest(scope, operation.snapshot.number) : await this.app.reconcilePullRequest(scope, operation.intent); + if (snapshot) return this.recordSnapshot(actor, id, snapshot); + // An absence observed after timeout is not proof that POST never happened. + return this.store.transaction(actor.tenantId, async tx => { const current = await must(tx, 'github_operation', id); current.status = 'unknown'; await tx.put('github_operation', touch(current)); return current; }); + } catch (error) { throw this.error(error); } + } + async authorizeMerge(actor: Actor, id: string, input: { expectedHeadSha: string; expectedBaseSha: string }) { + requireRole(actor, ['owner', 'admin', 'deployer']); requireHuman(actor); + const observed = await this.reconcilePullRequest(actor, id); + return this.store.transaction(actor.tenantId, async tx => { + const operation = await must(tx, 'github_operation', id); await this.access(tx, actor, operation); const run = await must(tx, 'run', operation.runId); + if (operation.version !== observed.version || operation.mergeAttempted || operation.status !== 'open' || run.revision !== operation.revision || run.verifiedCommit !== input.expectedHeadSha || operation.snapshot?.headSha !== input.expectedHeadSha || operation.snapshot?.baseSha !== input.expectedBaseSha || operation.intent.expectedHeadSha !== input.expectedHeadSha || operation.intent.expectedBaseSha !== input.expectedBaseSha) throw new DomainError('GITHUB_APPROVAL_STALE', 'Approval must bind the current verified head and target SHA'); + operation.mergeApproval = { actorId: actor.userId, headSha: input.expectedHeadSha, baseSha: input.expectedBaseSha, revision: run.revision, grantedAt: new Date().toISOString() }; await tx.put('github_operation', touch(operation)); return operation; + }); + } + async merge(actor: Actor, id: string) { + if (actor.kind !== 'verifier') { requireRole(actor, ['owner', 'admin', 'deployer']); requireHuman(actor); } + const observed = await this.reconcilePullRequest(actor, id); const scope = await this.currentScope(observed); + const claim = await this.store.transaction(actor.tenantId, async tx => { + const operation = await must(tx, 'github_operation', id); await this.access(tx, actor, operation); const run = await must(tx, 'run', operation.runId); + if (operation.mergeAttempted || operation.snapshot?.merged) return { dispatch: false, operation, mode: 'human' as const }; + const approval = operation.mergeApproval; + const human = !!approval && approval.revision === run.revision && approval.headSha === operation.intent.expectedHeadSha && approval.baseSha === operation.intent.expectedBaseSha; + if (!human && !scope.allowAutomaticMerge) throw new DomainError('GITHUB_MERGE_NOT_AUTHORIZED', 'Exact-version human approval or operator preauthorization is required'); + if (operation.status !== 'open' || run.revision !== operation.revision || run.verifiedCommit !== operation.intent.expectedHeadSha || ['paused', 'failed', 'canceled'].includes(run.status)) throw new DomainError('GITHUB_APPROVAL_STALE', 'Verified candidate changed before merge'); + operation.mergeAttempted = true; operation.status = 'merging'; await tx.put('github_operation', touch(operation)); return { dispatch: true, operation, mode: human ? 'human' as const : 'preauthorized' as const }; + }); + if (!claim.dispatch) return claim.operation; + try { const snapshot = await this.app.mergePullRequest(scope, claim.operation.snapshot!.number, claim.operation.intent, { mode: claim.mode, binding: `${claim.operation.intent.expectedHeadSha}:${claim.operation.intent.expectedBaseSha}` }); return this.recordSnapshot(actor, id, snapshot); } + catch (error) { await this.failure(actor, id, error, true); throw this.error(error); } + } + private async recordSnapshot(actor: Actor, id: string, snapshot: PullRequestSnapshot) { + return this.store.transaction(actor.tenantId, async tx => { + const operation = await must(tx, 'github_operation', id); await this.access(tx, actor, operation); const run = await must(tx, 'run', operation.runId); + if (!snapshot.body.includes(operation.intent.operationMarker) || snapshot.headRef !== operation.intent.headBranch || snapshot.baseRef !== operation.intent.baseBranch) throw new DomainError('GITHUB_PULL_SCOPE_INVALID', 'PR marker or branch binding changed'); + operation.snapshot = snapshot; operation.errorCode = undefined; + if (run.revision !== operation.revision) { operation.status = 'stale'; operation.mergeApproval = undefined; } + else if (snapshot.merged && snapshot.mergeCommitSha) { + operation.status = run.verifiedCommit === snapshot.mergeCommitSha ? 'merged' : 'reverification_required'; + if (operation.status === 'reverification_required' && !['canceled', 'failed', 'succeeded'].includes(run.status)) { + const activeVerifier = actor.kind === 'verifier' && run.status === 'running' && run.leaseOwnerId === actor.userId && run.leaseOwnerKind === 'verifier' && run.lease && Date.parse(run.lease.expiresAt) > Date.now(); + run.sourceCommit = snapshot.mergeCommitSha; run.verifiedCommit = undefined; run.stage = 'verify'; + if (!activeVerifier) { run.status = 'waiting'; run.waitingReason = 'merged_sha_reverification'; run.lastActiveAt = undefined; if (run.lease) run.lease.expiresAt = new Date().toISOString(); } + await tx.put('run', touch(run)); + for (const approval of await tx.list('approval')) { const release = await tx.get('release', String(approval.releaseId)); if (release?.runId === run.id && ['pending', 'approved'].includes(String(approval.status))) await tx.put('approval', { ...touch(approval), status: 'invalidated' }); } + } + } else if (snapshot.headSha !== operation.intent.expectedHeadSha || snapshot.baseSha !== operation.intent.expectedBaseSha) { operation.status = 'stale'; operation.mergeApproval = undefined; } + else if (operation.mergeAttempted && snapshot.state === 'open') operation.status = 'merge_pending'; + else operation.status = snapshot.state; + const next = touch(operation); await tx.put('github_operation', next); await tx.event(run.id, 'github.pr.observed', 'GitHub pull request state reconciled; merge acceptance is distinct from source verification.', { operationId: id, number: snapshot.number, state: next.status, headSha: snapshot.headSha, baseSha: snapshot.baseSha, mergeCommitSha: snapshot.mergeCommitSha }); return next; + }); + } + private async failure(actor: Actor, id: string, error: unknown, merging: boolean) { await this.store.transaction(actor.tenantId, async tx => { const op = await must(tx, 'github_operation', id); op.status = error instanceof GitHubError && error.unknownOutcome ? merging ? 'merge_unknown' : 'unknown' : 'failed'; op.errorCode = error instanceof GitHubError ? error.code : 'GITHUB_UNAVAILABLE'; await tx.put('github_operation', touch(op)); }); } + private error(error: unknown) { return error instanceof DomainError ? error : error instanceof GitHubError ? new DomainError(error.code, error.message, error.unknownOutcome ? 503 : 409) : new DomainError('GITHUB_UNAVAILABLE', 'GitHub integration is unavailable; no success is recorded', 503); } +} diff --git a/apps/api/src/domain/meta-evolution.ts b/apps/api/src/domain/meta-evolution.ts new file mode 100644 index 0000000..ab25b17 --- /dev/null +++ b/apps/api/src/domain/meta-evolution.ts @@ -0,0 +1,98 @@ +import { DomainError, type Actor, type Entity, type Project, type Run, type Budget } from '@wishforge/contracts'; +import { z } from 'zod'; +import { clusterFailures, improvementTask, normalizeFailure, type AutoEvolutionScope, type FailureObservation } from '../../../../packages/evolution/src/meta-loop.js'; +import { ControlPlane, must, record, touch } from './control-plane.js'; +import { requireRole } from './policy.js'; +import { resolveBundle } from './evolution.js'; +import { resolveProvisionerTarget } from './provisioner-target.js'; + +export interface MetaTask extends Entity {kind:'meta_task';status:'prepared'|'submitted'|'deferred';baselineBundle:string;scope:AutoEvolutionScope;failureSignature:string;projectId:string;provider:'codex'|'codebuddy';budget:Budget;sourceRunIds:string[];experienceIds:string[];requesterId:string;submission:ReturnType;runId?:string;wishId?:string;lastError?:string;} +interface AuthorizedExperience extends Entity {kind:'failure_observation';sourceTenantId:string;sourceRunIds:string[];summary:string;authorization:{purpose:'platform_evolution';approvedBy:string;approvedAt:string;revokedAt?:string};} +export type MetaTickResult={status:'unconfigured'|'idle'|'deferred';reason:string}|{status:'submitted'|'existing';metaTaskId:string;runId:string;wishId:string;sourceRunIds:string[];baselineBundle:string;scope:AutoEvolutionScope}; +const settingsSchema=z.object({projectId:z.string().min(1),provider:z.enum(['codex','codebuddy']),scope:z.enum(['prompt','orchestration','tool','platform']),minimum:z.coerce.number().int().min(1).max(50),maxTokens:z.coerce.number().int().min(1000).max(2000000),maxMinutes:z.coerce.number().int().min(1).max(180),lookbackDays:z.coerce.number().int().min(1).max(30)}); + +/** One explicit tick; no timers, no cross-tenant query, no model calls in this service. */ +export class MetaEvolution { + constructor(private control:ControlPlane,private env=control.env,private clock:()=>number=Date.now){} + async tick(actor:Actor):Promise{ + requireRole(actor,['owner','admin']); + const tenantId=this.env.WF_SYSTEM_TENANT; + if(!tenantId)return{status:'unconfigured',reason:'WF_SYSTEM_TENANT is required; customer usage cannot fund platform evolution'}; + if(actor.tenantId!==tenantId||actor.runId||!['human','worker','evaluator'].includes(actor.kind))throw new DomainError('FORBIDDEN','Only an authorized platform operator may trigger the system meta loop',403); + const parsed=settingsSchema.safeParse({projectId:this.env.WF_META_PROJECT_ID,provider:this.env.WF_META_PROVIDER??'codex',scope:this.env.WF_META_SCOPE??'prompt',minimum:this.env.WF_META_MIN_FAILURES??3,maxTokens:this.env.WF_META_MAX_TOKENS??30000,maxMinutes:this.env.WF_META_MAX_MINUTES??15,lookbackDays:this.env.WF_META_LOOKBACK_DAYS??7}); + if(!parsed.success)return{status:'unconfigured',reason:'Configure a system project and valid bounded candidate-generation settings'}; + try { if (!await resolveProvisionerTarget(this.env, tenantId)) return { status: 'unconfigured', reason: 'A system-tenant-scoped isolated provisioner is required before creating improvement work' }; } catch (error) { if (!(error instanceof DomainError)) throw error; return { status: 'unconfigured', reason: error.code }; } + const settings=parsed.data; + const prepared=await this.control.store.transaction(tenantId,async tx=>{ + const project=await tx.get('project',settings.projectId); + if(!project?.repositoryUrl||!project.verificationCommands.length)return{status:'unconfigured' as const,reason:'The system project requires a durable repository and protected independent verification commands'}; + const provider=(await this.control.providerInfo(tx)).find(p=>p.id===settings.provider); + if(!provider?.enabled)return{status:'unconfigured' as const,reason:'Connect a separately funded system-tenant provider credential and configure its executor'}; + const baselineBundle=String((await tx.get('policy','evolution-routing-v1'))?.stableVersion??'baseline-v1'); + const baseline=await resolveBundle(tx,baselineBundle); + const experiences=await tx.list('experience'); + const tasks=experiences.filter(e=>e.kind==='meta_task') as MetaTask[]; + // Replaying the same prepared operation repairs a crash after submit without creating a second run. + const pending=tasks.find(t=>!t.runId&&t.baselineBundle===baselineBundle&&t.scope===settings.scope&&['prepared','deferred'].includes(t.status)); + if(pending){ + for(const sourceId of pending.sourceRunIds){const source=await tx.get('run',sourceId);if(!source||source.tenantId!==tenantId||source.status!=='failed'||source.purpose==='evolution'||source.bundleVersion!==baselineBundle)return{status:'deferred' as const,reason:'Prepared source evidence changed; operator review is required'};} + for(const experienceId of pending.experienceIds){const e=await tx.get('experience',experienceId);if(!e||e.sourceTenantId!==tenantId||e.authorization?.purpose!=='platform_evolution'||e.authorization.revokedAt||!['owner','admin'].includes((await tx.membership(e.authorization.approvedBy))??''))return{status:'deferred' as const,reason:'Prepared experience authorization was revoked; operator review is required'};} + return{task:pending}; + } + const runs=(await tx.list('run')).filter(r=>r.status==='failed'&&r.purpose!=='evolution'&&r.bundleVersion===baselineBundle&&Date.parse(r.updatedAt)>=this.clock()-settings.lookbackDays*86400000).slice(0,200); + const byId=new Map(runs.map(r=>[r.id,r])); + const authorizedByRun=new Map(); + for(const raw of experiences){ + if(raw.kind!=='failure_observation')continue; + const e=raw as AuthorizedExperience,auth=e.authorization; + if(e.sourceTenantId!==tenantId||auth?.purpose!=='platform_evolution'||auth.revokedAt||!auth.approvedBy||!Array.isArray(e.sourceRunIds)||!e.sourceRunIds.length||!e.sourceRunIds.every(id=>byId.has(id))||typeof e.summary!=='string')continue; + const role=await tx.membership(auth.approvedBy);if(!['owner','admin'].includes(role??''))continue; + const approvedAt=Date.parse(auth.approvedAt);if(!Number.isFinite(approvedAt)||approvedAt>this.clock())continue; + for(const runId of e.sourceRunIds){const list=authorizedByRun.get(runId)??[];list.push({summary:e.summary,id:e.id});authorizedByRun.set(runId,list);} + } + const observations:FailureObservation[]=[];let remainingEventBudget=5000; + for(const run of runs){ + let summary=typeof run.error==='string'?run.error:''; + if(!summary){ + let after=0; + for(let page=0;page<10&&remainingEventBudget>0;page++){ + const events=await tx.events(run.id,after);remainingEventBudget-=events.length; + const failure=[...events].reverse().find(e=>e.type==='provider.failed'||(e.type==='run.transition'&&e.data?.status==='failed'));if(failure)summary=failure.message; + const next=events.at(-1)?.seq??after;if(events.length<1000||next<=after)break;after=next; + } + } + const authorized=authorizedByRun.get(run.id)??[]; + // Authorization can enrich missing failure evidence, but never copy a foreign tenant's text. + summary=normalizeFailure(summary||authorized[0]?.summary||''); + if(summary)observations.push({runId:run.id,tenantId,baselineBundle,provider:run.provider,stage:run.stage,summary,experienceIds:authorized.map(e=>e.id)}); + } + const consumed=new Set(tasks.filter(t=>t.baselineBundle===baselineBundle&&t.scope===settings.scope&&t.runId).flatMap(t=>t.sourceRunIds)); + const cluster=clusterFailures(observations,tenantId,baselineBundle,settings.minimum,consumed)[0]; + if(!cluster)return{status:'idle' as const,reason:'No unconsumed platform-owned failure cluster meets the configured threshold'}; + let submission:ReturnType; + try{submission=improvementTask(cluster,baselineBundle,baseline,settings.scope);}catch{return{status:'unconfigured' as const,reason:'Baseline/evidence context exceeds the trusted task size limit'};} + const existing=await tx.get('experience',submission.metadata.metaTaskId);if(existing)return{task:existing}; + const task:MetaTask={...record(tenantId),id:submission.metadata.metaTaskId,kind:'meta_task',status:'prepared',baselineBundle,scope:settings.scope,failureSignature:cluster.signature,projectId:settings.projectId,provider:settings.provider,budget:{maxTokens:settings.maxTokens,maxMinutes:settings.maxMinutes,maxRepairRounds:1},sourceRunIds:cluster.sourceRunIds,experienceIds:cluster.experienceIds,requesterId:actor.userId,submission}; + await tx.put('experience',task);return{task}; + }); + if(!('task'in prepared))return prepared; + const task=prepared.task!; + if(task.runId&&task.wishId)return{status:'existing',metaTaskId:task.id,runId:task.runId,wishId:task.wishId,sourceRunIds:task.sourceRunIds,baselineBundle:task.baselineBundle,scope:task.scope}; + const serviceActor:Actor={tenantId,userId:'platform-meta-loop',role:'admin',kind:'evaluator'}; + try{ + const result=await this.control.submit(serviceActor,task.projectId,{goal:task.submission.goal,acceptanceCriteria:task.submission.acceptanceCriteria,provider:task.provider,budget:task.budget},task.submission.idempotencyKey,task.submission.metadata); + return this.control.store.transaction(tenantId,async tx=>{ + const current=await must(tx,'experience',task.id);if(current.runId&¤t.wishId)return{status:'existing',metaTaskId:current.id,runId:current.runId,wishId:current.wishId,sourceRunIds:current.sourceRunIds,baselineBundle:current.baselineBundle,scope:current.scope};current.status='submitted';current.runId=result.run_id;current.wishId=result.wish_id;current.lastError=undefined;await tx.put('experience',touch(current)); + await tx.event(result.run_id,'evolution.task_submitted','Platform-owned failure cluster submitted for candidate generation; evaluation and publication remain separately gated',{metaTaskId:task.id,sourceRunIds:task.sourceRunIds,baselineBundle:task.baselineBundle,scope:task.scope}); + return{status:'submitted',metaTaskId:task.id,runId:result.run_id,wishId:result.wish_id,sourceRunIds:task.sourceRunIds,baselineBundle:task.baselineBundle,scope:task.scope}; + }); + }catch(error){ + return this.control.store.transaction(tenantId,async tx=>{ + const current=await must(tx,'experience',task.id); + if(current.runId&¤t.wishId)return{status:'existing',metaTaskId:current.id,runId:current.runId,wishId:current.wishId,sourceRunIds:current.sourceRunIds,baselineBundle:current.baselineBundle,scope:current.scope}; + current.status='deferred';current.lastError=error instanceof DomainError?error.code:'SUBMISSION_UNAVAILABLE';await tx.put('experience',touch(current)); + return{status:'deferred',reason:current.lastError}; + }); + } + } +} diff --git a/apps/api/src/domain/policy.ts b/apps/api/src/domain/policy.ts new file mode 100644 index 0000000..a60af94 --- /dev/null +++ b/apps/api/src/domain/policy.ts @@ -0,0 +1,37 @@ +import { createHash, timingSafeEqual } from 'node:crypto'; +import { DomainError, type Actor, type EvaluationReport, type EvolutionCandidate, type Run } from '@wishforge/contracts'; + +export function canonical(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`; + if (value && typeof value === 'object') return `{${Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`; + return JSON.stringify(value); +} +export const digest = (value: unknown) => `sha256:${createHash('sha256').update(canonical(value)).digest('hex')}`; +export function sameSecret(a: string, b: string) { const x = Buffer.from(a), y = Buffer.from(b); return x.length === y.length && x.length >= 16 && timingSafeEqual(x, y); } +export function requireRole(actor: Actor, permitted: Actor['role'][]) { if (!permitted.includes(actor.role)) throw new DomainError('FORBIDDEN', 'Your role cannot perform this action', 403); } +export function requireHuman(actor: Actor) { if (actor.kind !== 'human') throw new DomainError('HUMAN_APPROVAL_REQUIRED', 'Confirm this action in an authenticated interactive session', 403); } +export function checkLease(run: Run, token: number, now: number) { if (!run.lease || run.lease.token !== token || Date.parse(run.lease.expiresAt) <= now) throw new DomainError('STALE_LEASE', 'Worker lease expired or was replaced'); } +export function releaseRisk(input: { changedPaths?: string[]; migration?: boolean; permissionsExpanded?: boolean; evidenceComplete: boolean; preauthorized: boolean }) { + const reasons: string[] = []; + if (!input.evidenceComplete) reasons.push('Missing trusted change classification'); + if (!input.preauthorized) reasons.push('Environment is not preauthorized for automatic release'); + if (input.migration) reasons.push('Database migration'); + if (input.permissionsExpanded) reasons.push('Permission expansion'); + for (const path of input.changedPaths ?? []) { + if (/(^|\/)(auth|security|billing|migrations?|infra|\.github|\.codex)(\/|$)|(^|\/)(Dockerfile|compose[^/]*|wishforge\.ya?ml|package(-lock)?\.json|pnpm-lock\.yaml|requirements[^/]*|pyproject\.toml)$/.test(path)) reasons.push(`Protected change: ${path}`); + } + return [...new Set(reasons)]; +} +export function evaluationGate(report: EvaluationReport, candidate: EvolutionCandidate): string[] { + const failures: string[] = []; + if (report.candidateDigest !== candidate.candidateDigest || report.baselineDigest !== candidate.parentBundle) failures.push('Evaluation does not bind the candidate and baseline'); + if (report.distinctTasks < 50 || report.repeats < 3) failures.push('At least 50 distinct tasks with 3 repeats are required'); + if (report.hardGateFailures !== 0) failures.push('Hard safety gate failed'); + if (report.successDeltaLower95 < 0) failures.push('Quality non-regression is not established'); + if (report.costRatio > 1.1 || report.latencyP95Ratio > 1.1) failures.push('Cost or latency regression exceeds 10%'); + if (!report.targetImproved) failures.push('Declared target metric did not improve'); + return failures; +} +export function redact(message: string): string { + return message.replace(/(bearer\s+)[\w.\-]+/gi, '$1[redacted]').replace(/\b(sk-[\w-]{8,})\b/g, '[redacted]').replace(/((?:token|password|secret|api[_-]?key)\s*[=:]\s*)[^\s,;]+/gi, '$1[redacted]'); +} diff --git a/apps/api/src/domain/previews.ts b/apps/api/src/domain/previews.ts new file mode 100644 index 0000000..6548f3c --- /dev/null +++ b/apps/api/src/domain/previews.ts @@ -0,0 +1,71 @@ +import { createHash, createPublicKey, randomBytes, timingSafeEqual } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { z } from 'zod'; +import { DomainError, type Actor, type Environment, type Release } from '@wishforge/contracts'; +import type { Store, Transaction } from '../db/store.js'; +import { must, projectAccess, record, touch } from './control-plane.js'; +import { deploymentIdentity } from './releases.js'; +import { gatewayIdentityOrigins } from './gateway-target.js'; + +const id = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); +const target = z.object({ tenantId:id,environmentId:id,projectId:id,publicOrigin:z.string().max(2048),upstreamOrigin:z.string().max(2048),gatewayTokenEnv:z.string().regex(/^WF_[A-Z0-9_]{1,100}_TOKEN$/),proofPublicKeyFile:z.string().min(1).max(4096) }).strict(); +export interface PreviewTarget {tenantId:string;environmentId:string;projectId:string;publicOrigin:string;upstreamOrigin:string;gatewayToken:string;proofPublicKeyPem:string;policyDigest:string} +function origin(value:string, production:boolean, publicAddress:boolean) { + let parsed:URL;try{parsed=new URL(value);}catch{throw new DomainError('PREVIEW_CONFIGURATION_INVALID','Invalid preview origin',503);} + const loopback=['127.0.0.1','localhost','[::1]'].includes(parsed.hostname); + if(parsed.username||parsed.password||parsed.pathname!=='/'||parsed.search||parsed.hash||!['http:','https:'].includes(parsed.protocol)||(publicAddress&&parsed.protocol!=='https:'&&(production||!loopback)))throw new DomainError('PREVIEW_CONFIGURATION_INVALID','Preview origins must be dedicated origins; public production access requires HTTPS',503); + return parsed.origin; +} +export async function resolvePreviewTarget(env:NodeJS.ProcessEnv,tenantId:string,environmentId:string):Promise{ + if(!env.WF_PREVIEW_TARGETS_FILE)return undefined; + let entries:z.infer[]; + try{const bytes=await readFile(env.WF_PREVIEW_TARGETS_FILE);if(bytes.length>65536)throw new Error();entries=z.object({schemaVersion:z.literal(1),targets:z.array(target).max(1000)}).strict().parse(JSON.parse(bytes.toString('utf8'))).targets;} + catch{throw new DomainError('PREVIEW_CONFIGURATION_INVALID','Operator preview map is unreadable or invalid',503);} + const identities=new Set(),hosts=new Set(); + const identityOrigins=[env.WF_PUBLIC_URL,env.WF_API_PUBLIC_URL,env.WF_IDE_PUBLIC_URL,env.WF_WORKSPACE_GATEWAY_BASE,...await gatewayIdentityOrigins(env)].filter((value):value is string=>!!value).map(value=>new URL(value).hostname); + for(const entry of entries){entry.publicOrigin=origin(entry.publicOrigin,env.NODE_ENV==='production',true);entry.upstreamOrigin=origin(entry.upstreamOrigin,env.NODE_ENV==='production',false);const key=`${entry.tenantId}\0${entry.environmentId}`,host=new URL(entry.publicOrigin).hostname;if(identities.has(key)||hosts.has(host)||identityOrigins.includes(host)||entry.publicOrigin===entry.upstreamOrigin)throw new DomainError('PREVIEW_ORIGIN_CONFLICT','Each preview requires a dedicated hostname separate from all preview and identity sites',503);identities.add(key);hosts.add(host);} + const entry=entries.find(value=>value.tenantId===tenantId&&value.environmentId===environmentId);if(!entry)return undefined; + const gatewayToken=env[entry.gatewayTokenEnv];if(!gatewayToken||gatewayToken.length<32)throw new DomainError('PREVIEW_CONFIGURATION_INVALID','Scoped preview gateway credential is missing',503); + let proofPublicKeyPem:string;try{const bytes=await readFile(entry.proofPublicKeyFile);if(bytes.length>16384)throw new Error();proofPublicKeyPem=bytes.toString();if(createPublicKey(proofPublicKeyPem).asymmetricKeyType!=='ed25519')throw new Error();}catch{throw new DomainError('PREVIEW_CONFIGURATION_INVALID','Preview gateway Ed25519 public key is invalid',503);} + const policyDigest=`sha256:${createHash('sha256').update(JSON.stringify({tenantId:entry.tenantId,projectId:entry.projectId,environmentId:entry.environmentId,publicOrigin:entry.publicOrigin,upstreamOrigin:entry.upstreamOrigin,proofPublicKeyPem})).digest('hex')}`; + return {...entry,gatewayToken,proofPublicKeyPem,policyDigest}; +} +const opaque=()=>randomBytes(32).toString('base64url'); +const hash=(value:string)=>createHash('sha256').update(value).digest('hex'); +const readOnly=(method:string)=>['GET','HEAD'].includes(method); +export const previewAuthorizeInput=z.object({tenantId:id,environmentId:id,kind:z.enum(['launch','session','probe']),credential:z.string().regex(/^[A-Za-z0-9_-]{43}$/),method:z.enum(['GET','HEAD','POST','PUT','PATCH','DELETE','OPTIONS','WS']).default('GET'),path:z.string().startsWith('/').max(4096).default('/'),challenge:z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional()}).strict(); +type AuthorizationInput=z.infer; + +export class Previews{ + constructor(private store:Store,private env=process.env){} + private async target(tenantId:string,environmentId:string){const config=await resolvePreviewTarget(this.env,tenantId,environmentId);if(!config)throw new DomainError('PRIVATE_ACCESS_UNCONFIGURED','Operator private preview routing is not configured for this environment',503);return config;} + private async environment(tx:Transaction,config:PreviewTarget){const environment=await must(tx,'environment',config.environmentId);if(environment.projectId!==config.projectId||environment.visibility!=='private'||environment.applicationUrl&&new URL(environment.applicationUrl).origin!==config.publicOrigin)throw new DomainError('PREVIEW_SCOPE_MISMATCH','Preview environment no longer matches its operator routing',403);return environment;} + private async member(tx:Transaction,tenantId:string,userId:string,projectId:string){const role=await tx.membership(userId);if(!role)throw new DomainError('FORBIDDEN','Preview membership was revoked',403);const actor:Actor={tenantId,userId,kind:'human',role};await projectAccess(tx,actor,projectId);return actor;} + private async currentRelease(tx:Transaction,environment:Environment,releaseId:string,policyDigest:string,bindingDigest?:string){const release=await must(tx,'release',releaseId);if(release.environmentId!==environment.id||release.projectId!==environment.projectId||release.visibility!=='private'||release.privateAccessPolicyDigest!==policyDigest||release.applicationUrl!==environment.applicationUrl||(bindingDigest&&release.bindingDigest!==bindingDigest)||!(['deploying','unknown'].includes(release.status)&&environment.activeReleaseId===release.id||release.status==='healthy'&&environment.currentReleaseId===release.id))throw new DomainError('PREVIEW_RELEASE_STALE','Preview release was replaced or is not active',403);return release;} + async launch(actor:Actor,environmentId:string){ + if(!['human','connector'].includes(actor.kind))throw new DomainError('FORBIDDEN','Interactive preview identity required',403); + const subjectExpiresAt=actor.authExpiresAt??(this.env.NODE_ENV!=='production'?Date.now()+900000:undefined);if(!Number.isSafeInteger(subjectExpiresAt)||subjectExpiresAt!<=Date.now())throw new DomainError('UNAUTHENTICATED','A live expiring user credential is required for preview launch',401); + const config=await this.target(actor.tenantId,environmentId);return this.store.transaction(actor.tenantId,async tx=>{const environment=await this.environment(tx,config);await this.member(tx,actor.tenantId,actor.userId,environment.projectId);if(!environment.currentReleaseId)throw new DomainError('PREVIEW_NOT_READY','No accepted private release is available',409);const release=await this.currentRelease(tx,environment,environment.currentReleaseId,config.policyDigest);const code=opaque(),expiresAt=new Date(Math.min(Date.now()+30000,subjectExpiresAt!)).toISOString();await tx.put('preview_authorization',{...record(actor.tenantId),id:`launch-${hash(code)}`,kind:'launch',status:'active',environmentId,projectId:environment.projectId,userId:actor.userId,subjectExpiresAt,releaseId:release.id,bindingDigest:release.bindingDigest,expiresAt,publicOrigin:config.publicOrigin,policyDigest:config.policyDigest});return{launchUrl:`${config.publicOrigin}/_wishforge/session?code=${code}`,expiresAt,visibility:'private'};}); + } + async issueProbe(actor:Actor,releaseId:string){return this.store.transaction(actor.tenantId,tx=>this.issueProbeInTransaction(tx,actor,releaseId));} + async issueProbeForRunner(actor:Actor,releaseId:string,taskId:string){ + return this.store.transaction(actor.tenantId,async tx=>{ + const release=await must(tx,'release',releaseId),environment=await must(tx,'environment',release.environmentId),task=await must(tx,'runner_task',taskId),runner=environment.runnerId?await tx.get('runner',environment.runnerId):undefined; + const envelope=task.envelope as {signature?:string;payload?:{id?:string;tenantId?:string;environmentId?:string;expiresAt?:string;release?:{id?:string;bindingDigest?:string}}}|undefined,payload=envelope?.payload; + if(actor.kind!=='deployer'||actor.userId!==`runner:${environment.id}`||!runner||runner.status!=='active'||actor.clientId!==runner.id||task.runnerId!==runner.id||task.status!=='pending'||task.environmentId!==environment.id||task.releaseId!==releaseId||!envelope?.signature||payload?.id!==taskId||payload.tenantId!==actor.tenantId||payload.environmentId!==environment.id||!Number.isFinite(Date.parse(payload.expiresAt??''))||Date.parse(payload.expiresAt!)<=Date.now()||payload.release?.id!==releaseId||payload.release.bindingDigest!==release.bindingDigest||environment.activeReleaseId!==release.id)throw new DomainError('STALE_RUNNER_TASK','A live signed task from the current environment runner is required for a preview probe',403); + const issued=await this.issueProbeInTransaction(tx,actor,releaseId),authorization=await must(tx,'preview_authorization',`probe-${issued.capabilitySha256}`); + const expiresAt=new Date(Math.min(Date.parse(issued.expiresAt),Date.parse(payload.expiresAt!))).toISOString();authorization.runnerTaskId=taskId;authorization.expiresAt=expiresAt;await tx.put('preview_authorization',touch(authorization));return{...issued,expiresAt}; + }); + } + async issueProbeInTransaction(tx:Transaction,actor:Actor,releaseId:string){const release=await must(tx,'release',releaseId);deploymentIdentity(actor,release.environmentId,release.runId);const config=await this.target(actor.tenantId,release.environmentId),environment=await this.environment(tx,config);await this.currentRelease(tx,environment,releaseId,config.policyDigest,release.bindingDigest);const capability=opaque(),challenge=opaque(),capabilitySha256=hash(capability),expiresAt=new Date(Date.now()+120000).toISOString();await tx.put('preview_authorization',{...record(actor.tenantId),id:`probe-${hash(capability)}`,kind:'probe',status:'active',challenge,capabilitySha256,environmentId:environment.id,projectId:environment.projectId,releaseId,bindingDigest:release.bindingDigest,expiresAt,publicOrigin:config.publicOrigin,policyDigest:config.policyDigest});return{tenantId:actor.tenantId,environmentId:environment.id,publicOrigin:config.publicOrigin,releaseId,bindingDigest:release.bindingDigest,capability,challenge,capabilitySha256,expiresAt,proofPublicKeyPem:config.proofPublicKeyPem,policyDigest:config.policyDigest};} + async authorize(serviceAuthorization:string|undefined,untrusted:unknown){ + const input=previewAuthorizeInput.parse(untrusted),config=await this.target(input.tenantId,input.environmentId);const expected=Buffer.from(config.gatewayToken),supplied=Buffer.from(serviceAuthorization?.replace(/^Bearer /,'')??'');if(expected.length!==supplied.length||!timingSafeEqual(expected,supplied))throw new DomainError('UNAUTHENTICATED','Preview gateway identity required',401); + if(input.path.startsWith('//')||input.path.includes('\\')||input.path.startsWith('/_wishforge/'))throw new DomainError('PREVIEW_PATH_INVALID','Reserved preview path',400); + return this.store.transaction(input.tenantId,async tx=>{const authorization=await must(tx,'preview_authorization',`${input.kind}-${hash(input.credential)}`);if(authorization.kind!==input.kind||authorization.environmentId!==input.environmentId||authorization.status!=='active'||!Number.isFinite(Date.parse(String(authorization.expiresAt)))||Date.parse(String(authorization.expiresAt))<=Date.now()||authorization.publicOrigin!==config.publicOrigin||authorization.policyDigest!==config.policyDigest||input.kind!=='probe'&&(!Number.isSafeInteger(authorization.subjectExpiresAt)||Number(authorization.subjectExpiresAt)<=Date.now()))throw new DomainError('PREVIEW_AUTH_EXPIRED','Preview authorization is expired or mismatched',401);const environment=await this.environment(tx,config);const release=await this.currentRelease(tx,environment,String(authorization.releaseId),config.policyDigest,String(authorization.bindingDigest)); + let role='probe';if(input.kind!=='probe'){const actor=await this.member(tx,input.tenantId,String(authorization.userId),environment.projectId);role=actor.role;if(role==='viewer'&&!readOnly(input.method))throw new DomainError('FORBIDDEN','Viewer preview access is read-only',403);}else {if(input.challenge!==authorization.challenge)throw new DomainError('FORBIDDEN','Release probe challenge must match its issued capability',403);if(authorization.runnerTaskId){const task=await must(tx,'runner_task',String(authorization.runnerTaskId)),payload=(task.envelope as {payload?:{expiresAt?:string}}|undefined)?.payload;if(task.status!=='pending'||task.runnerId!==environment.runnerId||task.releaseId!==release.id||!Number.isFinite(Date.parse(payload?.expiresAt??''))||Date.parse(payload?.expiresAt??'')<=Date.now())throw new DomainError('STALE_RUNNER_TASK','Preview probe task is no longer active',403);}if(!readOnly(input.method))throw new DomainError('FORBIDDEN','Release probe permits GET/HEAD only',403);const protectedConfig=release.deliveryConfigSnapshot as {healthPath?:string;smokeChecks?:Array<{path:string}>}|undefined;const application=release.applicationUrl?new URL(release.applicationUrl):undefined;const paths=[protectedConfig?.healthPath,...(protectedConfig?.smokeChecks??[]).map(check=>check.path),application?application.pathname+application.search:undefined].filter((value):value is string=>typeof value==='string');if(!paths.includes(input.path))throw new DomainError('FORBIDDEN','Release probe is limited to protected acceptance paths',403);} + const base={tenantId:input.tenantId,environmentId:environment.id,projectId:environment.projectId,publicOrigin:config.publicOrigin,applicationUrl:release.applicationUrl,role,releaseId:release.id,bindingDigest:release.bindingDigest,policyDigest:config.policyDigest,expiresAt:String(authorization.expiresAt)}; + if(input.kind!=='launch')return base; + authorization.status='consumed';await tx.put('preview_authorization',touch(authorization));const sessionToken=opaque(),expiresAt=new Date(Math.min(Date.now()+900000,Number(authorization.subjectExpiresAt))).toISOString();await tx.put('preview_authorization',{...record(input.tenantId),id:`session-${hash(sessionToken)}`,kind:'session',status:'active',environmentId:environment.id,projectId:environment.projectId,userId:authorization.userId,subjectExpiresAt:authorization.subjectExpiresAt,releaseId:release.id,bindingDigest:release.bindingDigest,publicOrigin:config.publicOrigin,policyDigest:config.policyDigest,expiresAt});return{...base,sessionToken,expiresAt}; + }); + } +} diff --git a/apps/api/src/domain/private-access-verifier.ts b/apps/api/src/domain/private-access-verifier.ts new file mode 100644 index 0000000..f385a51 --- /dev/null +++ b/apps/api/src/domain/private-access-verifier.ts @@ -0,0 +1,17 @@ +import {DomainError,type Environment,type Release,type PrivateAccessEvidence,type Entity} from '@wishforge/contracts'; +import type {Transaction} from '../db/store.js'; +import {must,touch} from './control-plane.js'; +import {resolvePreviewTarget} from './previews.js'; +import {verifyPrivateAccessSamples,type ReleaseManifest} from '../../../../packages/runtime/src/index.js'; +export async function privatePolicyForEnvironment(environment:Environment,env:NodeJS.ProcessEnv){if(environment.visibility!=='private'||!environment.applicationUrl)return undefined;const config=await resolvePreviewTarget(env,environment.tenantId,environment.id);if(!config||config.projectId!==environment.projectId||config.publicOrigin!==new URL(environment.applicationUrl).origin)throw new DomainError('PRIVATE_ACCESS_UNCONFIGURED','An operator-managed private identity gateway must match this tenant, environment and application origin',503);return config.policyDigest;} +export async function verifyPrivateEvidence(tx:Transaction,env:NodeJS.ProcessEnv,release:Release,untrusted:unknown,receiptId:string){ + const evidence=untrusted as PrivateAccessEvidence;if(!evidence||!/^[a-f0-9]{64}$/.test(evidence.capabilitySha256??'')||!/^[A-Za-z0-9_-]{43}$/.test(evidence.challenge??''))throw new DomainError('PRIVATE_ACCESS_PROOF_REQUIRED','Independent signed private access evidence is required'); + const environment=await must(tx,'environment',release.environmentId);const config=await resolvePreviewTarget(env,release.tenantId,release.environmentId);if(!config||config.policyDigest!==release.privateAccessPolicyDigest||config.projectId!==release.projectId||environment.visibility!=='private'||environment.applicationUrl!==release.applicationUrl||new URL(release.applicationUrl!).origin!==config.publicOrigin||!(environment.activeReleaseId===release.id||environment.currentReleaseId===release.id))throw new DomainError('PRIVATE_ACCESS_POLICY_STALE','Private gateway policy or active release changed'); + const authorization=await tx.get('preview_authorization',`probe-${evidence.capabilitySha256}`); + if(!authorization||authorization.kind!=='probe'||authorization.runnerTaskId!==receiptId||!['active','consumed'].includes(String(authorization.status))||authorization.status==='consumed'&&authorization.consumedBy!==receiptId||authorization.capabilitySha256!==evidence.capabilitySha256||authorization.challenge!==evidence.challenge||authorization.environmentId!==release.environmentId||authorization.projectId!==release.projectId||authorization.releaseId!==release.id||authorization.bindingDigest!==release.bindingDigest||authorization.policyDigest!==config.policyDigest||authorization.publicOrigin!==config.publicOrigin||Date.parse(String(authorization.expiresAt))<=Date.now())throw new DomainError('PRIVATE_ACCESS_PROBE_STALE','Private access nonce, capability digest or authorization expiry does not match this receipt'); + const contract=release.deliveryConfigSnapshot as Pick|undefined;if(!contract?.healthPath||!contract.smokeChecks?.length)throw new DomainError('PRIVATE_ACCESS_UNCONFIGURED','Protected private health and business checks are required'); + const manifest={schemaVersion:1,id:release.id,tenantId:release.tenantId,environmentId:release.environmentId,sourceCommit:release.sourceCommit,image:release.imageDigest,applicationUrl:release.applicationUrl,visibility:'private',bindingDigest:release.bindingDigest,privateAccessPolicyDigest:release.privateAccessPolicyDigest,...contract} as ReleaseManifest; + try{verifyPrivateAccessSamples(manifest,evidence,config.proofPublicKeyPem,String(authorization.challenge),String(authorization.capabilitySha256));}catch{throw new DomainError('PRIVATE_ACCESS_PROOF_INVALID','Gateway signature, request body/status or required private acceptance checks failed');} + authorization.status='consumed';authorization.consumedBy=receiptId;authorization.consumedAt=new Date().toISOString();await tx.put('preview_authorization',touch(authorization));return{visibility:'private',policyDigest:config.policyDigest,checkedAt:evidence.checkedAt,checks:['health','business-smoke','application-url','anonymous-denied','private-access']}; +} +export function publicEvidence(evidence:Entity){const {privateAccessEvidence:_,...visible}=evidence;return visible;} diff --git a/apps/api/src/domain/provider-proxy.ts b/apps/api/src/domain/provider-proxy.ts new file mode 100644 index 0000000..be741df --- /dev/null +++ b/apps/api/src/domain/provider-proxy.ts @@ -0,0 +1,205 @@ +import { createHash } from 'node:crypto'; +import { SignJWT, jwtVerify } from 'jose'; +import { DomainError, type Actor, type Entity, type Run } from '@wishforge/contracts'; +import type { Store, Transaction } from '../db/store.js'; +import { CredentialVault } from './connections.js'; +import { executionLease, must, record, touch, now } from './control-plane.js'; + +const ISSUER = 'wishforge-provider-proxy', AUDIENCE = 'wishforge-openai-proxy'; +const UPSTREAM = 'https://api.openai.com/v1'; +const MAX_BODY = 2 * 1024 * 1024, MAX_FRAME = 1024 * 1024, MAX_RESPONSE = 16 * 1024 * 1024, MAX_REPLAY = 2 * 1024 * 1024; +const hash = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex'); +interface ProxyClaims { tenantId: string; runId: string; generation: string; leaseToken: number; ownerId: string; connectionId: string; connectionVersion: number } +export interface ProxyRequestRecord extends Entity { runId: string; projectId: string; connectionId: string; connectionVersion: number; generation: string; leaseToken: number; bodyDigest: string; path: string; status: 'dispatched' | 'completed' | 'rejected' | 'unknown'; reservedTokens: number; usageTokens?: number; responseId?: string; responseStatus?: number; responseType?: string; responseBody?: string; unknownReason?: string } +export interface ProviderProxyRequest { authorization?: string; method: string; path: string; headers?: Headers | Record; body?: Uint8Array; signal?: AbortSignal } +interface Options { vault?: Pick; fetcher?: typeof fetch; pollMs?: number } +export function providerProxyConfigured(env = process.env) { + if (env.NODE_ENV !== 'production' && env.WF_PROVIDER_PROXY_ENABLED !== 'true') return false; + if (!env.WF_PROVIDER_PROXY_PUBLIC_URL || !env.WF_PROVIDER_PROXY_SIGNING_KEY || env.WF_PROVIDER_PROXY_SIGNING_KEY.length < 32 || !env.WF_PROVIDER_PROXY_ALLOWED_MODELS?.trim()) return false; + try { const url = new URL(env.WF_PROVIDER_PROXY_PUBLIC_URL); return !url.username && !url.password && !url.search && !url.hash && url.pathname.replace(/\/$/, '').endsWith('/provider-proxy/v1') && (url.protocol === 'https:' || (env.NODE_ENV !== 'production' && url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname))); } catch { return false; } +} +export class ProviderProxy { + private readonly vault: Pick; + private readonly fetcher: typeof fetch; + private readonly pollMs: number; + constructor(private store: Store, private env = process.env, options: Options = {}) { this.vault = options.vault ?? new CredentialVault(env); this.fetcher = options.fetcher ?? fetch; this.pollMs = Math.max(25, Math.min(options.pollMs ?? 500, 1000)); } + private requireConfigured() { if (!providerProxyConfigured(this.env)) throw new DomainError('PROVIDER_PROXY_UNCONFIGURED', 'Configure the isolated model proxy, signing key, public HTTPS base URL and allowed model list', 503); } + private key() { this.requireConfigured(); return new TextEncoder().encode(this.env.WF_PROVIDER_PROXY_SIGNING_KEY!); } + private models() { return new Set(this.env.WF_PROVIDER_PROXY_ALLOWED_MODELS!.split(',').map(v => v.trim()).filter(Boolean)); } + private actor(claim: ProxyClaims): Actor { return { tenantId: claim.tenantId, userId: claim.ownerId, kind: 'worker', role: 'admin', runId: claim.runId, ...(claim.generation === 'development-local' ? {} : { credentialId: claim.generation }) }; } + private async valid(tx: Transaction, claim: ProxyClaims) { + const run = await must(tx, 'run', claim.runId); + executionLease(this.actor(claim), run, claim.leaseToken); + if (run.provider !== 'codex' || run.status !== 'running' || (run.executionGeneration ?? 'development-local') !== claim.generation) throw new DomainError('PROVIDER_PROXY_REVOKED', 'Proxy credential no longer belongs to an active Codex execution', 403); + const elapsed = run.activeMilliseconds + (run.lastActiveAt ? Math.max(0, Date.now() - Date.parse(run.lastActiveAt)) : 0); + if (elapsed >= run.budget.maxMinutes * 60_000) throw new DomainError('PROVIDER_TIME_EXHAUSTED', 'Run execution-time limit is exhausted', 429); + const connection = await must(tx, 'provider_connection', claim.connectionId); + if (connection.provider !== 'codex' || connection.status !== 'active' || connection.version !== claim.connectionVersion || typeof connection.ciphertext !== 'string') throw new DomainError('PROVIDER_CONNECTION_REVOKED', 'Provider connection was revoked or replaced', 403); + return { run, connection }; + } + async credential(actor: Actor, run: Run) { + this.requireConfigured(); + if (actor.kind !== 'worker' || run.provider !== 'codex' || !run.lease) throw new DomainError('PROVIDER_PROXY_FORBIDDEN', 'Codex executor lease required', 403); + const claims = await this.store.transaction(actor.tenantId, async tx => { + const current = await must(tx, 'run', run.id); executionLease(actor, current, run.lease!.token); + if (current.status !== 'running') throw new DomainError('RUN_STOPPED', 'Run is not executing'); + if (this.env.NODE_ENV === 'production' && (!actor.credentialId || actor.credentialId !== current.executionGeneration)) throw new DomainError('PROVIDER_GENERATION_REQUIRED', 'Production requires a run-scoped execution generation', 403); + const connection = (await tx.list('provider_connection')).find(c => c.provider === 'codex' && c.status === 'active' && typeof c.ciphertext === 'string'); + if (!connection) throw new DomainError('PROVIDER_CONNECTION_MISSING', 'Connect an active tenant-owned Codex credential', 503); + return { tenantId: actor.tenantId, runId: current.id, generation: String(current.executionGeneration ?? 'development-local'), leaseToken: current.lease!.token, ownerId: actor.userId, connectionId: connection.id, connectionVersion: connection.version, remainingSeconds: Math.max(0, Math.floor((current.budget.maxMinutes * 60000 - current.activeMilliseconds) / 1000)) }; + }); + const { remainingSeconds, ...binding } = claims; if (!remainingSeconds) throw new DomainError('PROVIDER_TIME_EXHAUSTED', 'Run execution-time limit is exhausted', 429); + const ttl = Math.min(3600, remainingSeconds); + const apiKey = await new SignJWT(binding).setProtectedHeader({ alg: 'HS256' }).setIssuer(ISSUER).setAudience(AUDIENCE).setSubject(actor.userId).setIssuedAt().setExpirationTime(`${ttl}s`).sign(this.key()); + return { apiKey, baseUrl: this.env.WF_PROVIDER_PROXY_PUBLIC_URL!.replace(/\/$/, ''), expiresAt: new Date(Date.now() + ttl * 1000).toISOString(), metering: 'proxy' as const }; + } + private async claims(authorization?: string): Promise { + if (!authorization?.startsWith('Bearer ')) throw new DomainError('PROVIDER_PROXY_UNAUTHENTICATED', 'Run-scoped model credential required', 401); + try { + const { payload } = await jwtVerify(authorization.slice(7), this.key(), { algorithms: ['HS256'], issuer: ISSUER, audience: AUDIENCE }); + if (![payload.tenantId, payload.runId, payload.generation, payload.ownerId, payload.connectionId].every(v => typeof v === 'string' && v.length > 0) || !Number.isSafeInteger(payload.leaseToken) || Number(payload.leaseToken) < 1 || !Number.isSafeInteger(payload.connectionVersion) || payload.sub !== payload.ownerId) throw new Error('Invalid claims'); + return payload as unknown as ProxyClaims; + } catch (error) { if (error instanceof DomainError) throw error; throw new DomainError('PROVIDER_PROXY_UNAUTHENTICATED', 'Proxy credential is invalid or expired', 401); } + } + private body(request: ProviderProxyRequest): { data?: Record; raw: string } { + const raw = new TextDecoder('utf-8', { fatal: true }).decode(request.body ?? new Uint8Array()); + if (Buffer.byteLength(raw) > MAX_BODY) throw new DomainError('PROVIDER_REQUEST_TOO_LARGE', 'Proxy request exceeds 2 MiB', 413); + if (request.method === 'GET') { if (raw) throw new DomainError('PROVIDER_INVALID_REQUEST', 'Model listing cannot contain a body', 400); return { raw }; } + let data: Record; try { data = JSON.parse(raw); } catch { throw new DomainError('PROVIDER_INVALID_REQUEST', 'Responses requires a JSON object', 400); } + if (!data || Array.isArray(data) || typeof data !== 'object' || typeof data.model !== 'string' || !this.models().has(data.model)) throw new DomainError('PROVIDER_MODEL_DENIED', 'Choose an operator-approved model', 403); + if (data.background === true || data.previous_response_id || data.conversation || data.prompt || data.multi_agent) throw new DomainError('PROVIDER_STATEFUL_REQUEST_DENIED', 'Unbounded remote state and server-hosted execution are not supported by this proxy', 400); + // Pinned Codex CLI sends transport-only client metadata; never forward it as an API parameter. + if (data.client_metadata !== undefined) { + if (!data.client_metadata || typeof data.client_metadata !== 'object' || Array.isArray(data.client_metadata) || Object.keys(data.client_metadata).length > 20 || Object.entries(data.client_metadata).some(([key, value]) => key.length > 100 || typeof value !== 'string' || value.length > 4096)) throw new DomainError('PROVIDER_INVALID_REQUEST', 'Client metadata must be a bounded string map', 400); + delete data.client_metadata; + } + const allowed = new Set(['model', 'input', 'instructions', 'tools', 'tool_choice', 'parallel_tool_calls', 'stream', 'stream_options', 'reasoning', 'store', 'background', 'include', 'service_tier', 'text', 'prompt_cache_key', 'prompt_cache_retention', 'prompt_cache_options', 'metadata', 'truncation', 'max_output_tokens', 'temperature', 'top_p', 'top_logprobs', 'user', 'safety_identifier']); + if (Object.keys(data).some(key => !allowed.has(key))) throw new DomainError('PROVIDER_PARAMETER_DENIED', 'Request uses an unverified provider capability', 400); + if (data.max_output_tokens !== undefined && (!Number.isSafeInteger(data.max_output_tokens) || data.max_output_tokens < 1)) throw new DomainError('PROVIDER_INVALID_REQUEST', 'max_output_tokens must be a positive integer', 400); + const localTool = (tool: any, depth = 0): boolean => { + if (!tool || typeof tool !== 'object' || depth > 3) return false; + if (['function', 'custom'].includes(tool.type)) return true; + return tool.type === 'namespace' && typeof tool.name === 'string' && /^[a-zA-Z0-9_-]{1,80}$/.test(tool.name) && Array.isArray(tool.tools) && tool.tools.length > 0 && tool.tools.length <= 128 && tool.tools.every((child: any) => localTool(child, depth + 1)); + }; + if (data.tools !== undefined && (!Array.isArray(data.tools) || data.tools.length > 128 || !data.tools.every((tool: any) => localTool(tool)))) throw new DomainError('PROVIDER_REMOTE_TOOL_DENIED', 'Only local function/custom tools and bounded namespaces of those tools are permitted', 403); + const inspect = (value: any, depth = 0) => { + if (depth > 60) throw new DomainError('PROVIDER_INVALID_REQUEST', 'Request nesting exceeds limit', 400); + if (!value || typeof value !== 'object') return; + if (['input_image', 'input_audio', 'input_file', 'image_url', 'file', 'audio', 'video', 'item_reference'].includes(value.type) || value.file_id || value.image_url || value.audio_url) throw new DomainError('PROVIDER_MULTIMODAL_DENIED', 'Only self-contained text inputs are supported for bounded proxy metering', 403); + for (const child of Object.values(value)) inspect(child, depth + 1); + }; inspect(data.input); + return { raw, data }; + } + async forward(request: ProviderProxyRequest): Promise { + this.requireConfigured(); + if (!((request.method === 'POST' && request.path === '/responses') || (request.method === 'GET' && request.path === '/models'))) throw new DomainError('PROVIDER_ROUTE_DENIED', 'Only POST /responses and GET /models are permitted', 404); + const claim = await this.claims(request.authorization), parsed = this.body(request); + const headers = request.headers instanceof Headers ? request.headers : new Headers(Object.entries(request.headers ?? {}).filter((pair): pair is [string, string] => typeof pair[1] === 'string')); + const explicitKey = headers.get('idempotency-key') ?? headers.get('x-client-request-id'); + if (explicitKey && !/^[a-zA-Z0-9_.:-]{8,200}$/.test(explicitKey)) throw new DomainError('PROVIDER_INVALID_REQUEST_ID', 'Invalid request idempotency key', 400); + const bodyDigest = hash(parsed.raw); const requestId = `proxy-${hash(JSON.stringify([claim.runId, claim.generation, claim.leaseToken, claim.connectionId, claim.connectionVersion, request.path, explicitKey ?? bodyDigest]))}`; + const prepared = await this.store.transaction(claim.tenantId, async tx => { + const { run, connection } = await this.valid(tx, claim); + const prior = await tx.get('provider_proxy_request', requestId); + if (prior) { + if (prior.bodyDigest !== bodyDigest) throw new DomainError('PROVIDER_IDEMPOTENCY_CONFLICT', 'Request key was reused for different input'); + if (prior.status === 'unknown') throw new DomainError('PROVIDER_OUTCOME_UNKNOWN', 'Prior upstream outcome requires reconciliation; no retry was sent', 409); + if (prior.status === 'dispatched') throw new DomainError('PROVIDER_REQUEST_IN_FLIGHT', 'The original request is still in flight; it was not repeated', 409); + if (prior.responseBody === undefined) throw new DomainError('PROVIDER_RESPONSE_NOT_REPLAYABLE', 'Request was already processed; inspect recorded response identity before continuing', 409); + return { replay: prior, connection }; + } + if (run.providerProxyActiveRequest) throw new DomainError('PROVIDER_REQUEST_IN_FLIGHT', 'Only one model request per run is allowed; an unresolved request retains its reservation', 409); + if (run.usedTokens >= run.budget.maxTokens || run.reservedTokens < 1) throw new DomainError('PROVIDER_BUDGET_EXHAUSTED', 'Run token budget is exhausted', 429); + let reserved = 0; + if (parsed.data) { + // Text-only requests use a deliberately conservative byte-count reservation, + // including protocol overhead; exact actual usage comes only from upstream. + const inputReserve = Buffer.byteLength(parsed.raw) + 4096; + const remaining = Math.min(run.budget.maxTokens - run.usedTokens, run.reservedTokens); + const outputLimit = Math.min(parsed.data.max_output_tokens ?? 8192, remaining - inputReserve); + if (outputLimit < 16) throw new DomainError('PROVIDER_BUDGET_EXHAUSTED', 'Remaining budget cannot cover bounded input and output', 429); + parsed.data.max_output_tokens = outputLimit; parsed.data.store = false; parsed.data.background = false; parsed.data.service_tier = 'default'; parsed.data.safety_identifier = hash(`${claim.tenantId}/${claim.runId}`); parsed.data.prompt_cache_key = hash(`${claim.tenantId}/${claim.runId}`); delete parsed.data.user; reserved = inputReserve + outputLimit; + } + const operation: ProxyRequestRecord = { ...record(claim.tenantId), id: requestId, runId: run.id, projectId: run.projectId, connectionId: connection.id, connectionVersion: connection.version, generation: claim.generation, leaseToken: claim.leaseToken, bodyDigest, path: request.path, status: 'dispatched', reservedTokens: reserved }; + run.providerProxyActiveRequest = requestId; await tx.put('run', touch(run)); await tx.put('provider_proxy_request', operation); + await tx.event(run.id, 'provider.proxy.dispatched', 'Scoped model request recorded before upstream I/O.', { requestId, reservedTokens: reserved }); return { operation, connection }; + }); + if ('replay' in prepared && prepared.replay) return new Response(prepared.replay.responseBody, { status: prepared.replay.responseStatus, headers: { 'content-type': prepared.replay.responseType!, 'cache-control': 'no-store', 'x-wishforge-request-id': requestId } }); + const operation = prepared.operation!; + const abort = new AbortController(); let reader: ReadableStreamDefaultReader | undefined; let settled = false, settlePromise: Promise | undefined, pollBusy = false, upstreamStarted = false; + const finish = (status: ProxyRequestRecord['status'], usageTokens?: number, response?: { status: number; type: string; body?: string; id?: string }, reason?: string): Promise => { + if (settlePromise) return settlePromise; + settled = true; clearInterval(timer); request.signal?.removeEventListener('abort', canceled); + settlePromise = this.store.transaction(claim.tenantId, async tx => { + const op = await must(tx, 'provider_proxy_request', requestId); if (op.status !== 'dispatched') return; + const run = await must(tx, 'run', claim.runId); op.status = status; op.usageTokens = usageTokens; op.unknownReason = reason; op.responseId = response?.id; op.responseStatus = response?.status; op.responseType = response?.type; op.responseBody = response?.body; + if (usageTokens !== undefined) { await tx.meter({ id: `provider-proxy:${requestId}`, runId: run.id, tokens: usageTokens, computeSeconds: 0, storageBytes: 0, at: now() }); run.usedTokens += usageTokens; run.reservedTokens = Math.max(0, run.reservedTokens - usageTokens); } + if (status === 'unknown') { run.reservedTokens = Math.max(run.reservedTokens, op.reservedTokens); if (!['canceled', 'failed', 'succeeded', 'paused'].includes(run.status)) { run.status = 'waiting'; run.waitingReason = 'provider_usage_unknown'; if (run.lease) run.lease.expiresAt = now(); } } + else if (run.providerProxyActiveRequest === requestId) { run.providerProxyActiveRequest = undefined; if (['canceled', 'failed', 'succeeded'].includes(run.status)) run.reservedTokens = 0; } + if (run.usedTokens >= run.budget.maxTokens && !['canceled', 'failed', 'succeeded', 'paused'].includes(run.status)) { run.status = 'waiting'; run.waitingReason = 'budget'; if (run.lease) run.lease.expiresAt = now(); } + await tx.put('provider_proxy_request', touch(op)); await tx.put('run', touch(run)); await tx.event(run.id, `provider.proxy.${status}`, status === 'unknown' ? 'Upstream outcome or usage is unknown; new model requests are blocked pending reconciliation.' : 'Trusted upstream request outcome recorded.', { requestId, usageTokens, responseId: response?.id }); + }); return settlePromise; + }; + const canceled = () => { abort.abort(); void reader?.cancel().catch(() => undefined); if (!settled) { const unknown = upstreamStarted && request.method === 'POST'; void finish(unknown ? 'unknown' : 'rejected', unknown ? undefined : 0, undefined, 'client_disconnected'); } }; + const timer = setInterval(() => { if (settled || pollBusy) return; pollBusy = true; void this.store.transaction(claim.tenantId, tx => this.valid(tx, claim)).catch(() => { abort.abort(); void reader?.cancel().catch(() => undefined); if (!settled) { const unknown = upstreamStarted && request.method === 'POST'; void finish(unknown ? 'unknown' : 'rejected', unknown ? undefined : 0, undefined, 'lease_or_connection_revoked'); } }).finally(() => { pollBusy = false; }); }, this.pollMs); timer.unref(); + request.signal?.addEventListener('abort', canceled, { once: true }); + try { + if (request.signal?.aborted) { canceled(); await settlePromise; throw new DomainError('PROVIDER_REQUEST_CANCELED', 'Request canceled', 409); } + const apiKey = await this.vault.open(claim.tenantId, String(prepared.connection.ciphertext)); + if (!/^[a-zA-Z0-9_-]{8,16000}$/.test(apiKey)) throw new DomainError('PROVIDER_KEY_INVALID', 'Provider credential format is invalid', 503); + await this.store.transaction(claim.tenantId, tx => this.valid(tx, claim)); + upstreamStarted = true; + const upstream = await this.fetcher(`${UPSTREAM}${request.path}`, { method: request.method, headers: { Authorization: `Bearer ${apiKey}`, 'content-type': 'application/json', Accept: parsed.data?.stream === true ? 'text/event-stream' : 'application/json', 'X-Client-Request-Id': requestId }, ...(parsed.data ? { body: JSON.stringify(parsed.data) } : {}), redirect: 'error', signal: AbortSignal.any([abort.signal, AbortSignal.timeout(120000)]) }); + const redact = (text: string) => text.replaceAll(apiKey, '[redacted]').replaceAll(request.authorization!.slice(7), '[redacted]'); + if (!upstream.ok) { + await upstream.body?.cancel(); const unknown = request.method === 'POST' && (upstream.status >= 500 || upstream.status === 408); + const text = JSON.stringify({ error: { code: unknown ? 'PROVIDER_OUTCOME_UNKNOWN' : 'PROVIDER_REQUEST_REJECTED', type: 'provider_proxy_error', message: unknown ? 'Provider outcome is unknown; reconcile before retrying.' : 'Provider rejected the request.' } }); + await finish(unknown ? 'unknown' : 'rejected', unknown ? undefined : 0, { status: upstream.status, type: 'application/json', body: text }); return new Response(text, { status: upstream.status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } }); + } + if (!upstream.body) throw new DomainError('PROVIDER_RESPONSE_INVALID', 'Provider response body is missing', 502); + reader = upstream.body.getReader(); + if (parsed.data?.stream === true) { + if (!upstream.headers.get('content-type')?.includes('text/event-stream')) throw new DomainError('PROVIDER_RESPONSE_INVALID', 'Expected a Responses event stream', 502); + const stream = new ReadableStream({ + start: controller => { void (async () => { + const decoder = new TextDecoder(); const encoder = new TextEncoder(); let buffer = '', total = 0, replay = '', responseId: string | undefined; + try { + while (!settled) { + const item = await reader!.read(); if (item.done) break; + total += item.value.byteLength; if (total > MAX_RESPONSE) throw new Error('Response size limit'); buffer = (buffer + decoder.decode(item.value, { stream: true })).replace(/\r\n/g, '\n'); + let index: number; + while ((index = buffer.indexOf('\n\n')) >= 0) { + const frame = buffer.slice(0, index); buffer = buffer.slice(index + 2); + if (Buffer.byteLength(frame) > MAX_FRAME) throw new Error('SSE frame size limit'); + const data = frame.split('\n').filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n'); + let event: any; if (data && data !== '[DONE]') { try { event = JSON.parse(data); } catch { throw new Error('Invalid SSE JSON'); } } + if (event?.response?.id && typeof event.response.id === 'string') { if (responseId && responseId !== event.response.id) throw new Error('Response identity mismatch'); responseId = event.response.id; } + const safe = redact(`${frame}\n\n`); if (replay.length <= MAX_REPLAY) replay += safe; + if (['response.completed', 'response.incomplete', 'response.failed'].includes(event?.type)) { + const usage = trustedUsage(event.response?.usage); if (usage === undefined || !responseId) throw new Error('Terminal response lacks trusted usage'); + await finish('completed', usage, { status: 200, type: 'text/event-stream', body: replay.length <= MAX_REPLAY ? replay : undefined, id: responseId }); controller.enqueue(encoder.encode(safe)); controller.close(); await reader!.cancel(); return; + } + controller.enqueue(encoder.encode(safe)); + } + if (Buffer.byteLength(buffer) > MAX_FRAME) throw new Error('SSE frame size limit'); + } + if (!settled) await finish('unknown', undefined, undefined, 'stream_ended_without_usage'); + controller.error(new Error('Provider stream ended without a trusted terminal usage receipt')); + } catch { if (!settled) await finish('unknown', undefined, undefined, 'stream_interrupted'); abort.abort(); await reader?.cancel().catch(() => undefined); controller.error(new Error('Provider stream interrupted; request outcome requires reconciliation')); } + })(); }, + cancel: async () => { canceled(); await settlePromise; }, + }); + return new Response(stream, { status: 200, headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-store', 'x-accel-buffering': 'no', 'x-wishforge-request-id': requestId } }); + } + const chunks: Uint8Array[] = []; let total = 0; + while (true) { const item = await reader.read(); if (item.done) break; total += item.value.byteLength; if (total > MAX_REPLAY) throw new Error('Response size limit'); chunks.push(item.value); } + if (settled) throw new DomainError('PROVIDER_REQUEST_CANCELED', 'Request was canceled or revoked', 409); + const raw = new TextDecoder().decode(Buffer.concat(chunks)); let data: any; try { data = JSON.parse(raw); } catch { throw new Error('Provider returned invalid JSON'); } + const usage = request.path === '/models' ? 0 : trustedUsage(data.usage); + if (usage === undefined || (request.path === '/responses' && typeof data.id !== 'string')) throw new Error('Provider response lacks trusted usage'); + if (request.path === '/models') { if (!Array.isArray(data.data)) throw new Error('Invalid model listing'); data = { object: 'list', data: data.data.filter((model: any) => this.models().has(model.id)) }; } + const safe = redact(JSON.stringify(data)); await finish('completed', usage, { status: 200, type: 'application/json', body: safe, id: request.path === '/responses' ? data.id : undefined }); return new Response(safe, { status: 200, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-wishforge-request-id': requestId } }); + } catch (error) { abort.abort(); await reader?.cancel().catch(() => undefined); const unknown = upstreamStarted && request.method === 'POST'; if (!settled) await finish(unknown ? 'unknown' : 'rejected', unknown ? undefined : 0, undefined, unknown ? 'upstream_result_unknown' : 'credential_or_lease_unavailable'); if (error instanceof DomainError) throw error; throw new DomainError(unknown ? 'PROVIDER_OUTCOME_UNKNOWN' : 'PROVIDER_UNAVAILABLE', 'Upstream response unavailable; no automatic retry was sent', 503); } + } +} +function trustedUsage(value: any): number | undefined { return value && Number.isSafeInteger(value.input_tokens) && value.input_tokens >= 0 && Number.isSafeInteger(value.output_tokens) && value.output_tokens >= 0 && Number.isSafeInteger(value.total_tokens) && value.total_tokens === value.input_tokens + value.output_tokens ? value.total_tokens : undefined; } diff --git a/apps/api/src/domain/provisioner-target.ts b/apps/api/src/domain/provisioner-target.ts new file mode 100644 index 0000000..2e91f9b --- /dev/null +++ b/apps/api/src/domain/provisioner-target.ts @@ -0,0 +1,39 @@ +import { readFile } from 'node:fs/promises'; +import { z } from 'zod'; +import { DomainError } from '@wishforge/contracts'; + +const tenantIdSchema = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); +const targetSchema = z.object({ url: z.string().max(2048), tokenEnv: z.string().regex(/^WF_[A-Z0-9_]{1,100}_TOKEN$/) }).strict(); +const fileSchema = z.object({ schemaVersion: z.literal(1), tenants: z.record(tenantIdSchema, targetSchema) }).strict(); +export interface ProvisionerTarget { url: string; token: string } +function checkedTarget(url: string, token: string | undefined, env: NodeJS.ProcessEnv): ProvisionerTarget { + let parsed: URL; + try { parsed = new URL(url); } catch { throw new DomainError('PROVISIONER_CONFIGURATION_INVALID', 'Operator provisioner URL is invalid', 503); } + const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname); + if (!(parsed.protocol === 'https:' || (env.NODE_ENV !== 'production' && parsed.protocol === 'http:' && loopback)) || parsed.username || parsed.password || parsed.search || parsed.hash || !token || token.length < 32) throw new DomainError('PROVISIONER_CONFIGURATION_INVALID', 'Provisioner requires a scoped service token and HTTPS (local development loopback excepted)', 503); + return { url: parsed.toString().replace(/\/$/, ''), token }; +} + +/** Operator-owned routing only: no request/model value can supply an endpoint or credential. */ +export async function resolveProvisionerTarget(env: NodeJS.ProcessEnv, tenantId: string): Promise { + if (!tenantIdSchema.safeParse(tenantId).success) throw new DomainError('PROVISIONER_CONFIGURATION_INVALID', 'Invalid provisioner tenant scope', 503); + if (env.WF_PROVISIONER_TARGETS_FILE) { + let parsed: z.infer; + try { + const bytes = await readFile(env.WF_PROVISIONER_TARGETS_FILE); + if (bytes.length > 65536) throw new Error('too large'); + parsed = fileSchema.parse(JSON.parse(bytes.toString('utf8'))); + } catch { throw new DomainError('PROVISIONER_CONFIGURATION_INVALID', 'Operator tenant provisioner map is unreadable or invalid', 503); } + const entry = Object.prototype.hasOwnProperty.call(parsed.tenants, tenantId) ? parsed.tenants[tenantId] : undefined; + // Presence of a map explicitly disables legacy fallback, including for omitted tenants. + return entry ? checkedTarget(entry.url, env[entry.tokenEnv], env) : undefined; + } + // Local setup pre-generates a credential before a provisioner is installed. + // A credential alone is not an endpoint and must leave runs safely waiting. + if (!env.WF_PROVISIONER_URL) return undefined; + const configured = [...new Set((env.WF_DISPATCH_TENANTS ?? '').split(',').map(value => value.trim()).filter(Boolean))]; + const boundTenant = env.WF_PROVISIONER_TENANT_ID ?? (configured.length === 1 ? configured[0] : undefined); + if (!boundTenant) throw new DomainError('PROVISIONER_TENANT_BINDING_REQUIRED', 'A legacy global provisioner requires one explicitly bound tenant; configure the tenant provisioner map for multiple tenants', 503); + if (boundTenant !== tenantId) return undefined; + return checkedTarget(env.WF_PROVISIONER_URL, env.WF_PROVISIONER_TOKEN, env); +} diff --git a/apps/api/src/domain/releases.ts b/apps/api/src/domain/releases.ts new file mode 100644 index 0000000..319caa0 --- /dev/null +++ b/apps/api/src/domain/releases.ts @@ -0,0 +1,137 @@ +import {requireDeploymentSecretPolicy} from './deployment-secret-policy.js'; +import {privatePolicyForEnvironment,verifyPrivateEvidence,publicEvidence} from './private-access-verifier.js'; +import {gatewayIdentityOrigins} from './gateway-target.js'; +import { DomainError, environmentInput, releaseInput, type Actor, type Environment, type Release, type Approval, type Run, type Evidence, type Project } from '@wishforge/contracts'; +import type { Store, Transaction } from '../db/store.js'; +import { record, touch, must, projectAccess, idempotent, now, executionScope } from './control-plane.js'; +import { digest, releaseRisk, requireRole, requireHuman, redact } from './policy.js'; + +import {accessConfiguration,assertApplicationConfigured,assertApplicationAccepted} from './application-access.js'; +import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js'; + +export function releaseBinding(release: Release) { + return { deploymentSecretPolicyDigest:release.deploymentSecretPolicyDigest,privateAccessPolicyDigest:release.privateAccessPolicyDigest,applicationUrl:release.applicationUrl,visibility:release.visibility,deliveryRequired:release.deliveryRequired,developmentLoopback:release.developmentLoopback,runId: release.runId, revision: release.revision, sourceCommit: release.sourceCommit, imageDigest: release.imageDigest, architecture: release.architecture, configVersion: release.configVersion, secretVersionRefs: release.secretVersionRefs, environmentId: release.environmentId, evidenceIds: release.evidenceIds.slice(0, 2), policyVersion: release.policyVersion, previousReleaseId: release.previousReleaseId, deliveryConfigSnapshot: release.deliveryConfigSnapshot, verificationPolicyDigest: release.verificationPolicyDigest }; +} +export function deploymentIdentity(actor: Actor, environmentId: string, runId: string) { + if (actor.kind !== 'deployer' || (actor.runId && actor.runId !== runId) || (actor.userId.startsWith('runner:') && actor.userId !== `runner:${environmentId}`)) throw new DomainError('FORBIDDEN', 'Deployment identity is not assigned to this environment/run', 403); +} +export class Releases { + constructor(private store: Store, private env = process.env) {} + private async projectIds(tx: Transaction, actor: Actor) { return new Set((await tx.list('project')).filter(p => ['owner', 'admin'].includes(actor.role) || p.memberIds.includes(actor.userId)).map(p => p.id)); } + async environments(actor:Actor){return this.store.transaction(actor.tenantId,async tx=>{const ids=await this.projectIds(tx,actor);return Promise.all((await tx.list('environment')).filter(e=>ids.has(e.projectId)).map(async environment=>{if(environment.visibility!=='private'||!environment.applicationUrl)return environment;try{await privatePolicyForEnvironment(environment,this.env);return{...environment,accessStatus:'configured',accessReason:undefined};}catch{return{...environment,accessStatus:'unconfigured',accessReason:'Private identity gateway routing is missing or no longer matches this environment.'};}}));});} + async createEnvironment(actor: Actor, input: unknown) { + requireHuman(actor); requireRole(actor, ['owner', 'admin']); const data = environmentInput.parse(input);requireDeploymentSecretPolicy(data); + return this.store.transaction(actor.tenantId, async tx => { await projectAccess(tx, actor, data.projectId); if (data.runnerId) throw new DomainError('RUNNER_REGISTRATION_REQUIRED', 'Register a runner after creating the environment', 400); const env = { ...record(actor.tenantId), ...data, ...accessConfiguration(data,this.env,await gatewayIdentityOrigins(this.env)) } as Environment; await tx.put('environment', env); return env; }); + } + async updateAccess(actor:Actor,id:string,input:{applicationUrl:string|null;visibility:'private'|'public'}){requireHuman(actor);requireRole(actor,['owner','admin']);return this.store.transaction(actor.tenantId,async tx=>{const environment=await must(tx,'environment',id);await projectAccess(tx,actor,environment.projectId);if(environment.activeReleaseId)throw new DomainError('ENVIRONMENT_CONFLICT','Reconcile the active deployment before changing application access');const config=accessConfiguration({...environment,applicationUrl:input.applicationUrl??undefined,visibility:input.visibility},this.env,await gatewayIdentityOrigins(this.env));Object.assign(environment,config);await tx.put('environment',touch(environment));return environment;});} + async updateDeploymentSecrets(actor:Actor,id:string,input:{secretVersionRefs:string[];deploymentSecretPolicyDigest:string|null}){requireHuman(actor);requireRole(actor,['owner','admin']);const policy={secretVersionRefs:input.secretVersionRefs,deploymentSecretPolicyDigest:input.deploymentSecretPolicyDigest??undefined};requireDeploymentSecretPolicy(policy);return this.store.transaction(actor.tenantId,async tx=>{const environment=await must(tx,'environment',id);await projectAccess(tx,actor,environment.projectId);if(environment.activeReleaseId)throw new DomainError('ENVIRONMENT_CONFLICT','Reconcile the active deployment before changing application secret references');Object.assign(environment,policy);await tx.put('environment',touch(environment));return environment;});} + private async visibleRelease(release:Release,environment:Environment|undefined){const {deliveryUrl:_,deliveryLaunchPath:__,...hidden}=release;const base=hidden as Release;if(release.status!=='healthy'||environment?.currentReleaseId!==release.id||release.applicationUrl!==environment.applicationUrl||release.visibility!==environment.visibility)return base;if(release.visibility==='public'&&release.deliveryUrl===release.applicationUrl)return release;if(release.visibility==='private'&&release.deliveryLaunchPath){try{if(await privatePolicyForEnvironment(environment,this.env)===release.privateAccessPolicyDigest)return{...base,deliveryLaunchPath:`/delivery/${release.environmentId}/launch`};}catch{}}return base;} + async list(actor:Actor){return this.store.transaction(actor.tenantId,async tx=>{const ids=await this.projectIds(tx,actor),environments=new Map((await tx.list('environment')).map(e=>[e.id,e]));return Promise.all((await tx.list('release')).filter(r=>ids.has(r.projectId)).map(r=>this.visibleRelease(r,environments.get(r.environmentId))));});} + async delivery(actor:Actor,id:string){return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);await projectAccess(tx,actor,run.projectId);const environments=new Map((await tx.list('environment')).map(e=>[e.id,e]));const releases=await Promise.all((await tx.list('release')).filter(r=>r.runId===id).map(r=>this.visibleRelease(r,environments.get(r.environmentId))));const release=releases.find(r=>!!r.deliveryUrl||!!r.deliveryLaunchPath)??releases[0]??null;return{run,release,releases,evidence:(await tx.list('evidence')).filter(e=>e.runId===id).map(publicEvidence),checkpoint:run.checkpointId?await tx.get('checkpoint',run.checkpointId):null,accepted:run.status==='succeeded',accessStatus:release?.deliveryUrl||release?.deliveryLaunchPath?'verified':'unconfigured',...(release?.deliveryUrl?{url:release.deliveryUrl,visibility:release.visibility}:{}),...(release?.deliveryLaunchPath?{visibility:'private',environmentId:release.environmentId,launchPath:release.deliveryLaunchPath}:{})};});} + + async request(actor: Actor, input: unknown, key?: string) { + requireRole(actor, ['owner', 'admin', 'deployer']); const data = releaseInput.parse(input); + return this.store.transaction(actor.tenantId, async tx => { + const run = await must(tx, 'run', data.runId); if (run.providerProxyActiveRequest) throw new DomainError('MODEL_USAGE_UNCONFIRMED', 'Outstanding model usage must be reconciled before publication'); if (run.purpose === 'evolution' || run.noDeployment) throw new DomainError('CANDIDATE_ONLY', 'Evolution generation tasks cannot publish an application release'); if (actor.kind === 'deployer' && run.executionGeneration && data.generation !== run.executionGeneration) throw new DomainError('STALE_GENERATION', 'A newer execution generation superseded this delivery'); const project = await projectAccess(tx, actor, run.projectId); + if (!['human', 'connector'].includes(actor.kind)) executionScope(actor, run); + return idempotent(tx, key, { operation: 'release', actorId: actor.userId, ...data }, async () => { + if (['canceled', 'failed', 'paused'].includes(run.status)) throw new DomainError('RUN_STOPPED', 'Stopped runs cannot be published'); + const env = await must(tx, 'environment', data.environmentId); + if (env.projectId !== run.projectId) throw new DomainError('ENVIRONMENT_MISMATCH', 'Environment belongs to another project'); + requireDeploymentSecretPolicy(env);accessConfiguration(env,this.env,await gatewayIdentityOrigins(this.env));const privateAccessPolicyDigest=await privatePolicyForEnvironment(env,this.env);assertApplicationConfigured({...env,privateAccessPolicyDigest},this.env); + assertVerificationProfile(project, this.env); + const verification = await must(tx, 'evidence', data.verificationEvidenceId), build = await must(tx, 'evidence', data.buildEvidenceId); + for (const e of [verification, build]) if (e.runId !== run.id || e.revision !== run.revision || !e.passed || e.sourceCommit !== run.verifiedCommit) throw new DomainError('STALE_EVIDENCE', 'Evidence must pass for this exact run, revision and commit'); + if (verification.type !== 'verification' || build.type !== 'build' || !build.imageDigest) throw new DomainError('EVIDENCE_REQUIRED', 'Trusted test and immutable build evidence are required'); + if (verification.verificationPolicyDigest !== verificationPolicyDigest(project) || build.verificationPolicyDigest !== verificationPolicyDigest(project)) throw new DomainError('STALE_EVIDENCE', 'Protected verification policy changed after evidence was recorded'); + const checkpoint = run.checkpointId ? await tx.get('checkpoint', run.checkpointId) : undefined; + const classification = checkpoint?.trustedClassification as { changedPaths: string[]; migration: boolean; permissionsExpanded: boolean; sourceCommit: string } | undefined; + const riskReasons = releaseRisk({ ...classification, evidenceComplete: !!classification && checkpoint?.revision === run.revision && classification.sourceCommit === run.verifiedCommit, preauthorized: env.autoDeploy }); + const binding = { deploymentSecretPolicyDigest:env.deploymentSecretPolicyDigest,privateAccessPolicyDigest,applicationUrl:env.applicationUrl,visibility:env.visibility??'private',deliveryRequired:this.env.NODE_ENV==='production'||!!env.applicationUrl,developmentLoopback:this.env.NODE_ENV!=='production'&&!env.production,runId: run.id, revision: run.revision, sourceCommit: run.verifiedCommit!, imageDigest: build.imageDigest, architecture: env.architecture, configVersion: env.configVersion, secretVersionRefs: env.secretVersionRefs, environmentId: env.id, evidenceIds: [verification.id, build.id], policyVersion: run.policyVersion, previousReleaseId: env.currentReleaseId, deliveryConfigSnapshot: project.deliveryConfig ?? null, verificationPolicyDigest: verificationPolicyDigest(project) }; + const release = { ...record(actor.tenantId), ...binding, projectId: run.projectId, status: riskReasons.length ? 'awaiting_approval' : 'ready', bindingDigest: digest(binding), riskReasons } as Release; + if (riskReasons.length) { + const approval = { ...record(actor.tenantId), releaseId: release.id, bindingDigest: release.bindingDigest, status: 'pending', expiresAt: new Date(Date.now() + 86400000).toISOString() } as Approval; + await tx.put('approval', approval); release.approvalId = approval.id; + } + await tx.put('release', release); await tx.event(run.id, 'release.created', riskReasons.length ? 'Release requires approval of the exact artifact and environment.' : 'Release passed the configured automatic policy.', { releaseId: release.id, bindingDigest: release.bindingDigest }); + if (!riskReasons.length) await tx.enqueue('release.ready', { releaseId: release.id }); + return release; + }); + }); + } + /** Revalidate immutable authorization at every boundary, including after deployment I/O. */ + async assertCurrent(tx: Transaction, release: Release, requireApproval = true) { + const run = await must(tx, 'run', release.runId), environment = await must(tx, 'environment', release.environmentId), project = await must(tx, 'project', release.projectId); + assertVerificationProfile(project, this.env); + if (environment.applicationUrl!==release.applicationUrl||(environment.visibility??'private')!==(release.visibility??'private'))throw new DomainError('RELEASE_STALE','Application URL or visibility changed; request a new release'); + accessConfiguration(environment,this.env,await gatewayIdentityOrigins(this.env));const privatePolicy=await privatePolicyForEnvironment(environment,this.env);if(privatePolicy!==release.privateAccessPolicyDigest)throw new DomainError('RELEASE_STALE','Private identity gateway policy changed; request a new release');assertApplicationConfigured(release,this.env); + if (digest(releaseBinding(release)) !== release.bindingDigest || run.revision !== release.revision || run.verifiedCommit !== release.sourceCommit || ['canceled', 'failed', 'paused'].includes(run.status) || run.policyVersion !== release.policyVersion || environment.projectId !== release.projectId || environment.deploymentSecretPolicyDigest!==release.deploymentSecretPolicyDigest||environment.configVersion !== release.configVersion || environment.architecture !== release.architecture || digest(environment.secretVersionRefs) !== digest(release.secretVersionRefs) || digest(project.deliveryConfig ?? null) !== digest(release.deliveryConfigSnapshot) || verificationPolicyDigest(project) !== release.verificationPolicyDigest || environment.currentReleaseId !== release.previousReleaseId) throw new DomainError('RELEASE_STALE', 'Requirements, code, policy, configuration, secrets or environment changed; request a new release'); + requireDeploymentSecretPolicy(release); + if (requireApproval && release.approvalId) { + const approval = await must(tx, 'approval', release.approvalId); + if (approval.status !== 'approved' || approval.releaseId !== release.id || approval.bindingDigest !== release.bindingDigest) throw new DomainError('APPROVAL_STALE', 'Release approval is absent or invalidated'); + } + return { run, environment, project }; + } + async decide(actor: Actor, id: string, input: { decision: string; bindingDigest: string }) { + requireRole(actor, ['owner', 'admin', 'deployer']); requireHuman(actor); + if (!['approve', 'reject'].includes(input.decision)) throw new DomainError('INVALID_DECISION', 'Choose approve or reject', 400); + return this.store.transaction(actor.tenantId, async tx => { + const approval = await must(tx, 'approval', id); const release = await must(tx, 'release', approval.releaseId); await projectAccess(tx, actor, release.projectId); + if (approval.status !== 'pending' || Date.parse(approval.expiresAt) <= Date.now()) throw new DomainError('APPROVAL_EXPIRED', 'Approval is expired or already resolved'); + if (input.bindingDigest !== approval.bindingDigest || release.bindingDigest !== approval.bindingDigest || release.status !== 'awaiting_approval') throw new DomainError('APPROVAL_STALE', 'Release no longer matches this approval'); + await this.assertCurrent(tx, release, false); + approval.status = input.decision === 'approve' ? 'approved' : 'rejected'; approval.decidedBy = actor.userId; + release.status = input.decision === 'approve' ? 'ready' : 'failed'; + await tx.put('approval', touch(approval)); await tx.put('release', touch(release)); + await tx.event(release.runId, 'release.approval', `Release ${input.decision} decision recorded.`, { releaseId: release.id, actorId: actor.userId }); + if (release.status === 'ready') await tx.enqueue('release.ready', { releaseId: release.id }); return release; + }); + } + async begin(actor: Actor, id: string) { + return this.store.transaction(actor.tenantId, async tx => { + const release = await must(tx, 'release', id); deploymentIdentity(actor, release.environmentId, release.runId); + const { environment: env } = await this.assertCurrent(tx, release); + if (release.status === 'deploying' && env.activeReleaseId === id) return release; + if (release.status !== 'ready') throw new DomainError('RELEASE_NOT_READY', 'Release must pass policy/approval'); + if (env.activeReleaseId) throw new DomainError('ENVIRONMENT_CONFLICT', 'Another release owns the environment'); + env.activeReleaseId = release.id; release.status = 'deploying'; await tx.put('environment', touch(env)); await tx.put('release', touch(release)); return release; + }); + } + async accept(actor: Actor, id: string, input: { evidenceId: string; bindingDigest: string }) { + return this.store.transaction(actor.tenantId, tx => this.acceptInTransaction(tx, actor, id, input)); + } + async acceptInTransaction(tx: Transaction, actor: Actor, id: string, input: { evidenceId: string; bindingDigest: string }) { + const release = await must(tx, 'release', id); deploymentIdentity(actor, release.environmentId, release.runId); + if (release.status === 'healthy' && input.bindingDigest === release.bindingDigest && release.evidenceIds.includes(input.evidenceId)) return release; + const { run, environment: env } = await this.assertCurrent(tx, release), evidence = await must(tx, 'evidence', input.evidenceId); + if (!['deploying', 'unknown'].includes(release.status) || env.activeReleaseId !== release.id || release.bindingDigest !== input.bindingDigest) throw new DomainError('RELEASE_CONFLICT', 'Deployment does not own this release'); + if (evidence.type !== 'deployment' || !evidence.passed || evidence.runId !== run.id || evidence.revision !== release.revision || evidence.sourceCommit !== release.sourceCommit || evidence.imageDigest !== release.imageDigest || evidence.releaseId !== release.id || evidence.environmentId !== env.id || evidence.bindingDigest !== release.bindingDigest || !evidence.checks?.includes('health') || !evidence.checks.includes('business-smoke')) throw new DomainError('ACCEPTANCE_REQUIRED', 'Health and business smoke evidence must bind this exact release and environment'); + if(release.visibility==='private'&&release.applicationUrl){await verifyPrivateEvidence(tx,this.env,release,evidence.privateAccessEvidence,String(evidence.runnerTaskId??evidence.id));release.deliveryLaunchPath=`/delivery/${release.environmentId}/launch`;delete release.deliveryUrl;}else{assertApplicationAccepted(release,evidence.accessEvidence,this.env);if(release.applicationUrl)release.deliveryUrl=release.applicationUrl;} + release.status = 'healthy'; release.deployedAt = now(); release.evidenceIds.push(evidence.id); env.currentReleaseId = id; env.activeReleaseId = undefined; + if (run.providerProxyActiveRequest) throw new DomainError('MODEL_USAGE_UNCONFIRMED', 'Outstanding model usage must be reconciled before acceptance'); run.status = 'succeeded'; run.stage = 'accept'; run.reservedTokens = 0; run.lastActiveAt = undefined; if (run.lease) run.lease.expiresAt = now(); + await tx.put('release', touch(release)); await tx.put('environment', touch(env)); await tx.put('run', touch(run)); await tx.event(run.id, 'delivery.accepted', 'Deployed artifact passed health and business acceptance.', { releaseId: id, evidenceId: evidence.id }); await tx.enqueue('run.signal', { runId: run.id, action: 'completed' }); return release; + } + async reportFailure(actor: Actor, id: string, status: 'failed' | 'unknown', message: string) { + return this.store.transaction(actor.tenantId, async tx => { const release = await must(tx, 'release', id); deploymentIdentity(actor, release.environmentId, release.runId); const env = await must(tx, 'environment', release.environmentId); if (!['deploying', 'unknown'].includes(release.status) || env.activeReleaseId !== id) throw new DomainError('RELEASE_CONFLICT', 'Failure receipt does not own the active deployment'); release.status = status; /* Preserve the lock until live-state reconciliation, even for a reported failure. */ await tx.put('release', touch(release)); await tx.event(release.runId, 'release.failure', redact(message), { releaseId: id, status }); return release; }); + } + async rollback(actor: Actor, id: string, key?: string) { + requireRole(actor, ['owner', 'admin', 'deployer']); requireHuman(actor); + return this.store.transaction(actor.tenantId, async tx => { + const release = await must(tx, 'release', id); await projectAccess(tx, actor, release.projectId); + return idempotent(tx, key, { operation: 'rollback', actorId: actor.userId, id }, async () => { + const env = await must(tx, 'environment', release.environmentId); + if (env.activeReleaseId) throw new DomainError('ENVIRONMENT_CONFLICT', 'Reconcile the active deployment before rollback'); + if (env.currentReleaseId !== id || release.status !== 'healthy' || !release.previousReleaseId) throw new DomainError('ROLLBACK_UNAVAILABLE', 'No compatible previous live release is known'); + const previous = await must(tx, 'release', release.previousReleaseId); + if (previous.environmentId !== env.id || previous.projectId !== release.projectId || !['healthy', 'rolled_back'].includes(previous.status) || previous.privateAccessPolicyDigest!==await privatePolicyForEnvironment(env,this.env)||previous.applicationUrl!==env.applicationUrl||(previous.visibility??'private')!==(env.visibility??'private')||previous.deploymentSecretPolicyDigest!==env.deploymentSecretPolicyDigest||previous.configVersion !== env.configVersion || previous.architecture !== env.architecture || digest(previous.secretVersionRefs) !== digest(env.secretVersionRefs) || digest(previous.deliveryConfigSnapshot) !== digest(release.deliveryConfigSnapshot)) throw new DomainError('ROLLBACK_REQUIRES_OPERATOR', 'Previous artifact, configuration and secrets require compatibility review'); + const existing = (await tx.list('runner_task')).find(t => t.environmentId === env.id && t.action === 'rollback' && ['pending', 'dispatching', 'unknown'].includes(String(t.status))); + if (existing) throw new DomainError('ENVIRONMENT_CONFLICT', 'A rollback is already pending'); + const operation = { ...record(actor.tenantId), action: 'rollback', releaseId: id, targetReleaseId: previous.id, environmentId: env.id, expectedReleaseId: id, targetBindingDigest: previous.bindingDigest, status: 'pending' }; + // Acquiring the environment lock here prevents a ready forward release racing the rollback. + env.activeReleaseId = previous.id; await tx.put('environment', touch(env)); + await tx.put('runner_task', operation); await tx.enqueue('release.rollback', { operationId: operation.id }); await tx.event(release.runId, 'rollback.requested', 'Rollback queued for the authenticated environment runner.', { operationId: operation.id, targetReleaseId: previous.id }); return operation; + }); + }); + } +} diff --git a/apps/api/src/domain/resource-dispatch.ts b/apps/api/src/domain/resource-dispatch.ts new file mode 100644 index 0000000..e6bd97f --- /dev/null +++ b/apps/api/src/domain/resource-dispatch.ts @@ -0,0 +1,29 @@ +import type { Run, ExecutionResourceGrant } from '@wishforge/contracts'; +import type { ControlPlane } from './control-plane.js'; +import { must, touch } from './control-plane.js'; +import { heldAllocation, recordAllocation } from './entitlements.js'; +import { resolveProvisionerTarget } from './provisioner-target.js'; + +/** Normal stopped generations release compute only after a scoped provisioner receipt. */ +export async function releaseStoppedAllocations(control: ControlPlane, tenantId: string, fetcher: typeof fetch = fetch) { + const provisioner = await resolveProvisionerTarget(control.env, tenantId); if (!provisioner) return; + const candidates = await control.store.transaction(tenantId, async tx => (await tx.list('run')).filter(run => heldAllocation(run) && ['succeeded','failed','canceled','paused','waiting'].includes(run.status) && (!run.lease || Date.parse(run.lease.expiresAt) <= Date.now()))); + for (const observed of candidates) { + const allocation = observed.resourceAllocation as { generation: string; grant: ExecutionResourceGrant; status: string; cleanupConfirmedAt?: string }; + if (allocation.status === 'unknown' && allocation.cleanupConfirmedAt) continue; + try { + const current = await control.store.transaction(tenantId, tx => must(tx, 'run', observed.id)); + if ((current.resourceAllocation as { generation?: string } | undefined)?.generation !== allocation.generation || !['succeeded','failed','canceled','paused','waiting'].includes(current.status) || (current.lease && Date.parse(current.lease.expiresAt) > Date.now())) continue; + const response = await fetcher(`${provisioner.url}/runs/release`, { method: 'POST', headers: { Authorization: `Bearer ${provisioner.token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ tenantId, runId: observed.id, generation: allocation.generation, resourceGrant: allocation.grant }), signal: AbortSignal.timeout(30000) }); + if (!response.ok) continue; + const receipt = await response.json() as { tenantId: string; runId: string; generation: string; status: string; computeReleased: boolean; persistentStorageRetained: boolean }; + if (receipt.tenantId !== tenantId || receipt.runId !== observed.id || receipt.generation !== allocation.generation || receipt.status !== 'released' || receipt.computeReleased !== true || receipt.persistentStorageRetained !== true) continue; + await control.store.transaction(tenantId, async tx => { + const latest = await must(tx, 'run', observed.id); const value = latest.resourceAllocation as { generation?: string; status?: string } | undefined; + if (value?.generation !== allocation.generation || ['running','queued'].includes(latest.status)) return; + if (allocation.status === 'unknown' || value.status === 'unknown') { latest.resourceAllocation = { ...value, cleanupConfirmedAt: new Date().toISOString(), status: 'unknown' }; await tx.put('run', touch(latest)); await tx.event(latest.id, 'resources.reconciliation_required', 'Compute cleanup was observed after an unknown provisioning outcome; operator reconciliation is required before releasing the reserved slot.'); } + else await recordAllocation(tx, latest.id, allocation.generation, 'released'); + }); + } catch { /* Keep the durable slot; a missing receipt is never proof resources stopped. */ } + } +} diff --git a/apps/api/src/domain/runner-broker.ts b/apps/api/src/domain/runner-broker.ts new file mode 100644 index 0000000..4daaa06 --- /dev/null +++ b/apps/api/src/domain/runner-broker.ts @@ -0,0 +1,142 @@ +import {resolvePreviewTarget} from './previews.js'; +import {verifyPrivateEvidence,privatePolicyForEnvironment} from './private-access-verifier.js'; +import {matchesApplicationAccess} from '@wishforge/contracts'; +import { createHash, createPrivateKey, createPublicKey, randomBytes, randomUUID, sign } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { z } from 'zod'; +import { DomainError, type Actor, type Entity, type Environment, type Release, type Run, type Evidence } from '@wishforge/contracts'; +import type { Store, Transaction } from '../db/store.js'; +import { ControlPlane, must, projectAccess, record, touch, now } from './control-plane.js'; +import { canonical, digest, requireHuman, requireRole } from './policy.js'; +import { Releases, releaseBinding } from './releases.js'; + +interface Envelope { keyId: string; signature: string; payload: { id: string; action: string; target: string; expiresAt: string; release: { id: string; sourceCommit: string; image: string; [key: string]: unknown }; [key: string]: unknown } } +const receipt = z.object({ result: z.object({ releaseId: z.string().min(1), status: z.enum(['dry-run', 'applied', 'verified', 'failed', 'unconfigured', 'not-found', 'conflict']), target: z.enum(['compose', 'kubernetes']), evidence: z.record(z.string(), z.unknown()), rendered: z.string().optional() }).strict() }).strict(); +export class RunnerBroker { + constructor(private store: Store, private control: ControlPlane, private releases: Releases, private env = process.env) {} + async register(actor: Actor, environmentId: string) { + requireRole(actor, ['owner', 'admin']); requireHuman(actor); + const token = randomBytes(32).toString('base64url'); const tokenHash = createHash('sha256').update(token).digest('hex'); + const publicKeys = await this.publicKeys(); + const runner = await this.store.transaction(actor.tenantId, async tx => { + const environment = await must(tx, 'environment', environmentId); await projectAccess(tx, actor, environment.projectId); + for (const old of await tx.list('runner')) if (old.environmentId === environmentId) await tx.put('runner', { ...touch(old), status: 'revoked' }); + const registration = { ...record(actor.tenantId), environmentId, tokenHash, status: 'active' }; await tx.put('runner', registration); environment.runnerId = registration.id; await tx.put('environment', touch(environment)); return registration; + }); + return { id: runner.id, environmentId, tenantId: actor.tenantId, token, publicKeys, note: 'Save this token once. Runner also requires an operator-issued client certificate; no client certificate is minted here.' }; + } + async publicKeys() { const key = await this.signingKey(); return { [this.env.WF_RUNNER_SIGNING_KEY_ID ?? 'v1']: createPublicKey(key).export({ type: 'spki', format: 'pem' }).toString() }; } + private async signingKey() { + if (!this.env.WF_RUNNER_SIGNING_KEY_FILE) throw new DomainError('SIGNER_UNCONFIGURED', 'Configure the independent Runner signing key before enabling deployment', 503); + const key = createPrivateKey(await readFile(this.env.WF_RUNNER_SIGNING_KEY_FILE)); + if (key.asymmetricKeyType !== 'ed25519') throw new DomainError('INVALID_SIGNER', 'Runner task key must be Ed25519', 503); + return key; + } + private async registration(tx: Transaction, actor: Actor, environment: Environment) { + if (actor.kind !== 'deployer' || actor.userId !== `runner:${environment.id}`) throw new DomainError('FORBIDDEN', 'Runner is not registered for this environment', 403); + const registration = environment.runnerId ? await tx.get('runner', environment.runnerId) : undefined; + if (!registration || registration.status !== 'active' || (actor.clientId && actor.clientId !== registration.id)) throw new DomainError('RUNNER_REVOKED', 'Runner registration is inactive or replaced', 403); + return registration; + } + async poll(actor: Actor, environmentId: string) { + const key = await this.signingKey(); + return this.store.transaction(actor.tenantId, async tx => { + const environment = await must(tx, 'environment', environmentId), registration = await this.registration(tx, actor, environment); + const tasks = await tx.list('runner_task'); + const pending = tasks.find(t => t.environmentId === environmentId && t.status === 'pending' && t.envelope); + if (pending) { + const envelope = pending.envelope as Envelope; + if (pending.runnerId === registration.id && Date.parse(envelope.payload.expiresAt) > Date.now()) { + if (environment.activeReleaseId !== pending.releaseId) throw new DomainError('STALE_RUNNER_TASK', 'Task no longer owns the environment'); + const target = await must(tx, 'release', String(pending.releaseId)); + if (!pending.rollbackOperationId) await this.releases.assertCurrent(tx, target); + else { + const operation = await must(tx, 'runner_task', String(pending.rollbackOperationId)); + if (operation.lastTaskId !== pending.id || operation.expectedReleaseId !== environment.currentReleaseId || target.applicationUrl!==environment.applicationUrl||(target.visibility??'private')!==(environment.visibility??'private')||target.deploymentSecretPolicyDigest!==environment.deploymentSecretPolicyDigest||target.configVersion !== environment.configVersion || target.architecture !== environment.architecture || digest(target.secretVersionRefs) !== digest(environment.secretVersionRefs)) throw new DomainError('ROLLBACK_STALE', 'Rollback state changed'); + } + return envelope; + } + // An old lease may already have changed the target: the next task may only reconcile it. + pending.status = 'expired'; await tx.put('runner_task', touch(pending)); + } + const rollback = tasks.find(t => t.environmentId === environmentId && t.action === 'rollback' && ['pending', 'dispatching', 'unknown'].includes(String(t.status))); + let release: Release | undefined; + let action: 'deploy' | 'reconcile'; + let previous: string | undefined; + if (rollback) { + release = await must(tx, 'release', String(rollback.targetReleaseId)); + if (environment.currentReleaseId !== rollback.expectedReleaseId || environment.activeReleaseId !== release.id || rollback.targetBindingDigest !== release.bindingDigest || digest(releaseBinding(release)) !== release.bindingDigest || release.environmentId !== environment.id || release.applicationUrl!==environment.applicationUrl||(release.visibility??'private')!==(environment.visibility??'private')||release.deploymentSecretPolicyDigest!==environment.deploymentSecretPolicyDigest||release.configVersion !== environment.configVersion || release.architecture !== environment.architecture || digest(release.secretVersionRefs) !== digest(environment.secretVersionRefs)) throw new DomainError('ROLLBACK_STALE', 'Rollback no longer matches the environment and approved previous artifact'); + action = rollback.status === 'pending' ? 'deploy' : 'reconcile'; previous = String(rollback.expectedReleaseId); + } else { + const releases = await tx.list('release'); + release = environment.activeReleaseId ? releases.find(r => r.id === environment.activeReleaseId && ['deploying', 'unknown', 'failed'].includes(r.status)) : releases.find(r => r.environmentId === environmentId && r.status === 'ready'); + if (!release) return null; + await this.releases.assertCurrent(tx, release); + action = release.status === 'ready' ? 'deploy' : 'reconcile'; previous = release.previousReleaseId; + } + const config = release.deliveryConfigSnapshot as { containerPort?: number; healthPath?: string; smokeChecks?: unknown[]; config?: Record } | null; + if (!config?.containerPort || !config.healthPath || !config.smokeChecks?.length) throw new DomainError('ACCEPTANCE_UNCONFIGURED', 'Protected port, health path and business smoke checks are required before deployment', 503); + let privateAccess; + if(release.visibility==='private'&&release.applicationUrl){const target=await resolvePreviewTarget(this.env,actor.tenantId,environmentId);if(!target||release.privateAccessPolicyDigest!==target.policyDigest)throw new DomainError('PRIVATE_ACCESS_POLICY_STALE','Private preview policy changed');privateAccess={publicOrigin:target.publicOrigin,proofPublicKeyPem:target.proofPublicKeyPem,policyDigest:target.policyDigest};} + const time = Date.now(), id = randomUUID(); + const payload = JSON.parse(JSON.stringify({ schemaVersion: 1, id, tenantId: actor.tenantId, environmentId, nonce: randomUUID(), issuedAt: new Date(time).toISOString(), expiresAt: new Date(time + 300000).toISOString(), action, target: environment.type === 'compose' ? 'compose' : 'kubernetes', release: { schemaVersion: 1, id: release.id, tenantId: actor.tenantId, environmentId, sourceCommit: release.sourceCommit, image: release.imageDigest, architecture: release.architecture, configVersion: release.configVersion,deploymentSecretPolicyDigest:release.deploymentSecretPolicyDigest, secretVersionRefs: release.secretVersionRefs, bindingDigest: release.bindingDigest, applicationUrl:release.applicationUrl,visibility:release.visibility,privateAccessPolicyDigest:release.privateAccessPolicyDigest,privateAccess,deliveryRequired:release.deliveryRequired,developmentLoopback:release.developmentLoopback, config: config.config, containerPort: config.containerPort, healthPath: config.healthPath, smokeChecks: config.smokeChecks, expectedPreviousReleaseId: previous ?? null } })); + const keyId = this.env.WF_RUNNER_SIGNING_KEY_ID ?? 'v1'; + const envelope = { keyId, payload, signature: sign(null, Buffer.from(canonical({ keyId, payload })), key).toString('base64url') }; + const task = { ...record(actor.tenantId), id, environmentId, releaseId: release.id, runnerId: registration.id, status: 'pending', envelope, ...(rollback ? { rollbackOperationId: rollback.id } : {}) }; + await tx.put('runner_task', task); + if (rollback) { if(release.visibility==='private'&&release.applicationUrl){release.status='deploying';await tx.put('release',touch(release));} rollback.status = 'dispatching'; rollback.lastTaskId = task.id; await tx.put('runner_task', touch(rollback)); } + else { environment.activeReleaseId = release.id; release.status = 'deploying'; await tx.put('environment', touch(environment)); await tx.put('release', touch(release)); } + return envelope; + }); + } + async result(actor: Actor, taskId: string, input: unknown) { + const { result } = receipt.parse(input); + return this.store.transaction(actor.tenantId, async tx => { + const task = await must(tx, 'runner_task', taskId), environment = await must(tx, 'environment', String(task.environmentId)); + const registration = await this.registration(tx, actor, environment); + if (task.runnerId !== registration.id || !task.envelope) throw new DomainError('STALE_RUNNER_TASK', 'Receipt belongs to a replaced runner or an unsigned operation'); + const envelope = task.envelope as Envelope, payload = envelope.payload; + if (result.releaseId !== payload.release.id || result.target !== payload.target) throw new DomainError('RESULT_MISMATCH', 'Receipt does not match the signed release and deployment target'); + if (task.status === 'completed') { + if (task.resultDigest !== digest(result)) throw new DomainError('RECEIPT_CONFLICT', 'A different receipt has already been committed for this task'); + return { acknowledged: true, delivered: task.delivered === true, rolledBack: task.rolledBack === true }; + } + if (task.status !== 'pending' || Date.parse(payload.expiresAt) <= Date.now()) throw new DomainError('STALE_RUNNER_TASK', 'Task lease expired or was replaced; reconcile the target using a new signed task'); + const release = await must(tx, 'release', String(task.releaseId)); + if (environment.activeReleaseId !== release.id || release.sourceCommit !== payload.release.sourceCommit || release.imageDigest !== payload.release.image || release.bindingDigest !== payload.release.bindingDigest) throw new DomainError('RESULT_MISMATCH', 'Receipt no longer owns the deployed artifact or environment'); + const basicVerified=result.status==='verified'&&result.evidence.identityMatched===true&&result.evidence.trafficSwitched===true&&Array.isArray(result.evidence.checks)&&result.evidence.checks.includes('health')&&result.evidence.checks.includes('business-smoke'); + const privateMode=release.visibility==='private'&&!!release.applicationUrl; + let verified=basicVerified&&!privateMode&&matchesApplicationAccess(release,result.evidence.accessEvidence)&&(this.env.NODE_ENV!=='production'||!!release.applicationUrl); + if(privateMode&&basicVerified){await verifyPrivateEvidence(tx,this.env,release,result.evidence.privateAccessEvidence,task.id);verified=true;} + + let rolledBack = false; + if (task.rollbackOperationId) { + const operation = await must(tx, 'runner_task', String(task.rollbackOperationId)); + if (operation.status !== 'dispatching' || operation.lastTaskId !== task.id || environment.currentReleaseId !== operation.expectedReleaseId || release.id !== operation.targetReleaseId || release.bindingDigest !== operation.targetBindingDigest || environment.applicationUrl!==release.applicationUrl||(environment.visibility??'private')!==(release.visibility??'private')||environment.deploymentSecretPolicyDigest!==release.deploymentSecretPolicyDigest||environment.configVersion !== release.configVersion || digest(environment.secretVersionRefs) !== digest(release.secretVersionRefs)) throw new DomainError('ROLLBACK_STALE', 'Rollback receipt no longer matches the active operation'); + if (verified) { + const original = await must(tx, 'release', String(operation.releaseId)); + original.status = 'rolled_back'; release.status = 'healthy';if(release.applicationUrl){if(privateMode){release.deliveryLaunchPath=`/delivery/${release.environmentId}/launch`;delete release.deliveryUrl;}else release.deliveryUrl=release.applicationUrl;} environment.currentReleaseId = release.id; environment.activeReleaseId = undefined; operation.status = 'completed'; operation.completedAt = now(); + const evidence = this.deploymentEvidence(actor, release, environment, task.id,result.evidence); await tx.put('evidence', evidence); operation.evidenceId = evidence.id; + await tx.put('release', touch(original)); await tx.put('release', touch(release)); await tx.put('environment', touch(environment)); + await tx.event(original.runId, 'release.rolled_back', 'Previous immutable artifact restored and passed health and business acceptance.', { operationId: operation.id, targetReleaseId: release.id, evidenceId: evidence.id }); rolledBack = true; + } else { operation.status = 'unknown'; const original = await must(tx, 'release', String(operation.releaseId)); await tx.event(original.runId, 'rollback.unknown', 'Rollback requires live-state reconciliation.', { operationId: operation.id }); } + await tx.put('runner_task', touch(operation)); + } else if (verified) { + await this.releases.assertCurrent(tx, release); + const evidence = this.deploymentEvidence(actor, release, environment, task.id,result.evidence); + await tx.put('evidence', evidence); + await this.releases.acceptInTransaction(tx, actor, release.id, { evidenceId: evidence.id, bindingDigest: release.bindingDigest }); + } else { + if (!['deploying', 'unknown', 'failed'].includes(release.status)) throw new DomainError('RELEASE_CONFLICT', 'Deployment receipt is obsolete'); + release.status = 'unknown'; await tx.put('release', touch(release)); + await tx.event(release.runId, 'release.failure', `Runner reported ${result.status}; live state must be reconciled before another deployment.`, { releaseId: release.id, taskId }); + } + task.status = 'completed'; task.result = result; task.resultDigest = digest(result); task.delivered = verified && !task.rollbackOperationId; task.rolledBack = rolledBack; + await tx.put('runner_task', touch(task)); + return { acknowledged: true, delivered: task.delivered, rolledBack, ...(verified&&release.applicationUrl?(privateMode?{launchPath:`/delivery/${release.environmentId}/launch`,environmentId:release.environmentId,visibility:'private'}:{url:release.applicationUrl}):{}) }; + }); + } + private deploymentEvidence(actor: Actor, release: Release, environment: Environment, taskId: string,resultEvidence:Record): Evidence { + return { ...record(actor.tenantId), runId: release.runId, revision: Number(release.revision), sourceCommit: release.sourceCommit, imageDigest: release.imageDigest, type: 'deployment', passed: true, ...(release.applicationUrl?(release.visibility==='private'?{privateAccessEvidence:resultEvidence.privateAccessEvidence,privateAccessSummary:{policyDigest:release.privateAccessPolicyDigest}}:{accessEvidence:resultEvidence.accessEvidence}):{}), checks: ['health', 'business-smoke',...(release.visibility==='private'&&release.applicationUrl?['private-access','anonymous-denied']:[])], issuer: actor.userId, releaseId: release.id, environmentId: environment.id, bindingDigest: release.bindingDigest, runnerTaskId: taskId }; + } +} diff --git a/apps/api/src/domain/verification-policy.ts b/apps/api/src/domain/verification-policy.ts new file mode 100644 index 0000000..1949bb7 --- /dev/null +++ b/apps/api/src/domain/verification-policy.ts @@ -0,0 +1,42 @@ +import { z } from 'zod'; +import { DomainError, type Project, type VerificationProfile } from '@wishforge/contracts'; +import { digest } from './policy.js'; + +const profilePath = z.string().regex(/^\/usr\/local\/lib\/wishforge-verification\/[a-zA-Z0-9_./-]+$/).refine(p => !p.includes('..') && !p.includes('//')); +export const verificationProfileSchema = z.object({ + id: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/), + version: z.string().min(1).max(100), + commands: z.array(z.array(z.string().min(1).max(4096)).min(1).max(50)).min(1).max(20), + files: z.array(z.object({ path: profilePath, sha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict()).min(1).max(100) +}).strict().superRefine((p, ctx) => { + if (new Set(p.files.map(f => f.path)).size !== p.files.length) ctx.addIssue({ code: 'custom', message: 'Profile file paths must be unique' }); + for (const argv of p.commands) { + if (!argv[0]?.startsWith('/') || !argv.some(a => p.files.some(f => f.path === a)) || argv.some(a => a.includes('\0'))) ctx.addIssue({ code: 'custom', message: 'Each command must use an absolute executable and a pinned acceptance file' }); + } +}); + +export function configuredVerificationProfiles(env: NodeJS.ProcessEnv): VerificationProfile[] { + if (!env.WF_VERIFICATION_PROFILES_JSON) return []; + try { + const profiles = z.array(verificationProfileSchema).max(100).parse(JSON.parse(env.WF_VERIFICATION_PROFILES_JSON)); + if (new Set(profiles.map(p => p.id)).size !== profiles.length) throw new Error('Duplicate profile id'); + return profiles; + } catch { throw new DomainError('VERIFICATION_CONFIGURATION_INVALID', 'Operator verification profile configuration is invalid', 503); } +} +export function selectVerificationProfile(id: string, env: NodeJS.ProcessEnv): VerificationProfile { + const profile = configuredVerificationProfiles(env).find(p => p.id === id); + if (!profile) throw new DomainError('VERIFICATION_PROFILE_UNAVAILABLE', 'Choose an operator-installed verification profile', 409); + return profile; +} +export function verificationPolicyDigest(project: Project): string { + // Preserve the previous development contract when no independent profile exists. + return digest(project.verificationProfile ? { commands: project.verificationCommands, profile: project.verificationProfile } : project.verificationCommands); +} +export function assertVerificationProfile(project: Project, env: NodeJS.ProcessEnv) { + if (!project.verificationProfile) { + if (env.NODE_ENV === 'production') throw new DomainError('VERIFICATION_PROFILE_REQUIRED', 'Production verification requires an operator-installed independent acceptance profile'); + return; + } + const active = selectVerificationProfile(project.verificationProfile.id, env); + if (digest(active) !== digest(project.verificationProfile)) throw new DomainError('VERIFICATION_PROFILE_REPLACED', 'The installed acceptance profile changed; select the new version and reverify'); +} diff --git a/apps/api/src/domain/workspace-integration.ts b/apps/api/src/domain/workspace-integration.ts new file mode 100644 index 0000000..e27680d --- /dev/null +++ b/apps/api/src/domain/workspace-integration.ts @@ -0,0 +1,63 @@ +import {resolveGatewayTarget} from './gateway-target.js'; +import { DomainError, type Actor, type Entity, type Run } from '@wishforge/contracts'; +import type { Store } from '../db/store.js'; +import { executionLease, executionScope, must, projectAccess, touch } from './control-plane.js'; +import { digest, requireHuman, requireRole } from './policy.js'; +import { validateSnapshot, type WorkspaceSnapshot } from '../../../../packages/runtime/src/workspace-snapshot.js'; + +export interface WorkspaceInput extends WorkspaceSnapshot { workspaceId:string;workspaceVersion:number;sourceCommit:string;activityDigest:string;requirementRevision:number;importGeneration:unknown;importedBy:string;importedAt:string } +interface InputState { workspaceId:string;latestSnapshot:WorkspaceSnapshot|null;currentDiskDigest:string;activityDigest:string;dirty:boolean;activeClients:number } +interface MatchRecord { generation:unknown;leaseToken:number;inputDigest:string;targetCommit:string;matchedAt:string } +export interface IntegrationLease {runId:string;generation:unknown;verifierId:string;leaseToken:number;fence:number;expiresAt:string} +export class WorkspaceIntegration { + constructor(private store:Store,private env=process.env,private fetcher:typeof fetch=fetch){} + private async load(actor:Actor,id:string){return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);await projectAccess(tx,actor,run.projectId);if(!['human','connector'].includes(actor.kind))executionScope(actor,run);const workspaces=(await tx.list('workspace')).filter(w=>w.projectId===run.projectId&&w.status!=='archived'&&(w.status==='ready'||typeof w.upstreamUrl==='string'));return{run,workspaces,inputs:(run.workspaceInputs??[]) as WorkspaceInput[]};});} + private async gateway(tenantId:string){const target=await resolveGatewayTarget(this.env,tenantId);if(!target)throw new DomainError('WORKSPACE_GATE_UNAVAILABLE','No authenticated workspace gateway is configured for this tenant',503);return target;} + private async state(run:Run,workspace:Entity):Promise{ + if(workspace.status!=='ready')throw new DomainError('WORKSPACE_GATE_UNAVAILABLE','Active workspace state is unavailable; integration is blocked',503); + const gateway=await this.gateway(run.tenantId); + const response=await this.fetcher(new URL('/internal/integration-state',gateway.internalUrl),{method:'POST',headers:{authorization:`Bearer ${gateway.token}`,'content-type':'application/json'},body:JSON.stringify({tenantId:run.tenantId,workspaceId:workspace.id,runId:run.id,generation:run.executionGeneration,revision:run.revision}),redirect:'error',signal:AbortSignal.timeout(15000)}).catch(()=>{throw new DomainError('WORKSPACE_GATE_UNAVAILABLE','Workspace input service is unreachable; integration is blocked',503);}); + if(!response.ok)throw new DomainError('WORKSPACE_GATE_UNAVAILABLE','Could not establish current workspace input state; integration is blocked',503); + const value=await response.json().catch(()=>{throw new DomainError('WORKSPACE_GATE_UNAVAILABLE','Workspace input service returned an unreadable receipt',503);}) as InputState; + if(!value||value.workspaceId!==workspace.id||typeof value.dirty!=='boolean'||!/^[a-f0-9]{64}$/.test(value.currentDiskDigest)||!/^[a-f0-9]{64}$/.test(value.activityDigest))throw new DomainError('WORKSPACE_GATE_UNAVAILABLE','Workspace returned an invalid input-state receipt',503); + return value; + } + async inspect(actor:Actor,id:string){const loaded=await this.load(actor,id);return{required:loaded.workspaces.length>0,requirementRevision:loaded.run.revision,generation:loaded.run.executionGeneration,workspaces:loaded.workspaces.map(w=>({id:w.id,status:w.status})),snapshots:loaded.inputs.filter(input=>input.requirementRevision===loaded.run.revision&&loaded.workspaces.some(w=>w.id===input.workspaceId))};} + async importSnapshot(actor:Actor,id:string,workspaceId:string,sourceCommit:string,userAuthorization:string){ + requireHuman(actor);requireRole(actor,['owner','admin','developer']);if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(sourceCommit))throw new DomainError('INVALID_COMMIT','A full committed source SHA is required',400); + const before=await this.load(actor,id);const workspace=before.workspaces.find(w=>w.id===workspaceId);if(!workspace||workspace.status!=='ready')throw new DomainError('NOT_FOUND','Ready workspace not found',404); + const gateway=await this.gateway(actor.tenantId); + const response=await this.fetcher(new URL(`/workspaces/${workspaceId}/_wishforge/integration/snapshot`,gateway.internalUrl),{method:'POST',headers:{authorization:userAuthorization,'content-type':'application/json'},body:'{}',redirect:'error',signal:AbortSignal.timeout(45000)}); + if(!response.ok)throw new DomainError('WORKSPACE_SAVE_BARRIER_REQUIRED','Every active editor must save and acknowledge before importing the workspace',409); + const state=await response.json() as InputState;if(state.workspaceId!==workspaceId||state.dirty!==false||!/^[a-f0-9]{64}$/.test(state.activityDigest)||!state.latestSnapshot||state.currentDiskDigest!==state.latestSnapshot.digest)throw new DomainError('WORKSPACE_INPUT_CHANGED','Workspace changed before its snapshot could be imported');const snapshot=state.latestSnapshot;validateSnapshot(snapshot); + return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);await projectAccess(tx,actor,run.projectId);const current=await must(tx,'workspace',workspaceId);if(run.revision!==before.run.revision||run.projectId!==before.run.projectId||current.version!==workspace.version)throw new DomainError('WORKSPACE_INPUT_CHANGED','Requirement or workspace changed while saving'); + const input:WorkspaceInput={...snapshot,workspaceId,workspaceVersion:current.version,sourceCommit,activityDigest:state.activityDigest,requirementRevision:run.revision,importGeneration:run.executionGeneration,importedBy:actor.userId,importedAt:new Date().toISOString()}; + run.workspaceInputs=[...((run.workspaceInputs??[]) as WorkspaceInput[]).filter(item=>item.workspaceId!==workspaceId),input];delete run.workspaceInputMatch;await tx.put('run',touch(run));await tx.event(id,'workspace.snapshot-imported','Saved workspace input imported; independent Git tree matching is still required',{workspaceId,snapshotRevision:input.revision,snapshotDigest:input.digest,sourceCommit});return{...input,trust:'input-only',nextAction:'Commit/push the saved tree to the integration target, then resume for independent matching'};}); + } + private async fresh(actor:Actor,id:string){const loaded=await this.load(actor,id);if(!loaded.workspaces.length)return loaded;for(const w of loaded.workspaces){const input=loaded.inputs.find(i=>i.workspaceId===w.id&&i.requirementRevision===loaded.run.revision);if(!input)throw new DomainError('WORKSPACE_SNAPSHOT_REQUIRED','Import a fresh coordinated snapshot of each ready workspace before integration');if(input.workspaceVersion!==w.version)throw new DomainError('WORKSPACE_INPUT_CHANGED','Workspace provisioning changed; import a new snapshot');const current=await this.state(loaded.run,w);if(current.dirty||current.latestSnapshot?.id!==input.id||current.latestSnapshot.revision!==input.revision||current.currentDiskDigest!==input.digest||current.activityDigest!==input.activityDigest)throw new DomainError('WORKSPACE_INPUT_CHANGED','Editor versions, membership, saved revision or source content changed; save, import and reverify');}return loaded;} + async recordMatch(actor:Actor,id:string,body:{leaseToken:number;targetCommit:string;snapshots:Array<{workspaceId:string;sourceCommit:string;snapshotRevision:number;snapshotDigest:string}>}){ + if(actor.kind!=='verifier')throw new DomainError('FORBIDDEN','Independent verifier identity required',403);const scoped=await this.load(actor,id);executionLease(actor,scoped.run,body.leaseToken);const loaded=await this.fresh(actor,id);executionLease(actor,loaded.run,body.leaseToken);if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(body.targetCommit))throw new DomainError('INVALID_COMMIT','Full integration target SHA required',400); + const expected=loaded.inputs.filter(i=>loaded.workspaces.some(w=>w.id===i.workspaceId)).map(i=>({workspaceId:i.workspaceId,sourceCommit:i.sourceCommit,snapshotRevision:i.revision,snapshotDigest:i.digest})).sort((a,b)=>a.workspaceId.localeCompare(b.workspaceId)); + if(digest(expected)!==digest([...body.snapshots].sort((a,b)=>a.workspaceId.localeCompare(b.workspaceId))))throw new DomainError('WORKSPACE_INPUT_CHANGED','Verifier result does not bind the exact imported workspace inputs'); + return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);executionLease(actor,run,body.leaseToken);this.assertProjectLease(actor,run,await projectAccess(tx,actor,run.projectId));if(run.revision!==loaded.run.revision||digest(run.workspaceInputs??[])!==digest(loaded.inputs))throw new DomainError('WORKSPACE_INPUT_CHANGED','Inputs changed while the verifier matched Git');run.workspaceInputMatch={generation:run.executionGeneration,leaseToken:body.leaseToken,inputDigest:digest(loaded.inputs),targetCommit:body.targetCommit,matchedAt:new Date().toISOString()} satisfies MatchRecord;await tx.put('run',touch(run));return{matched:true,inputDigest:digest(loaded.inputs)};}); + } + async acquire(actor:Actor,id:string,leaseToken:number){ + if(actor.kind!=='verifier')throw new DomainError('FORBIDDEN','Independent verifier required',403); + return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);executionLease(actor,run,leaseToken);const project=await projectAccess(tx,actor,run.projectId);const previous=project.integrationLease as IntegrationLease|undefined; + if(previous&&Date.parse(previous.expiresAt)>Date.now()){const owner=await tx.get('run',previous.runId);const live=owner&&owner.executionGeneration===previous.generation&&owner.lease?.token===previous.leaseToken&&Date.parse(owner.lease.expiresAt)>Date.now();if(live&&(previous.runId!==id||previous.generation!==run.executionGeneration||previous.leaseToken!==leaseToken||previous.verifierId!==actor.userId))throw new DomainError('INTEGRATION_BUSY','Another run owns the project integration queue');if(live){previous.expiresAt=new Date(Math.min(Date.now()+60000,Date.parse(run.lease!.expiresAt))).toISOString();await tx.put('project',touch(project));return previous;}} + const fence=Number(project.integrationFence??0)+1;const lease:IntegrationLease={runId:id,generation:run.executionGeneration,verifierId:actor.userId,leaseToken,fence,expiresAt:new Date(Math.min(Date.now()+60000,Date.parse(run.lease!.expiresAt))).toISOString()};project.integrationFence=fence;project.integrationLease=lease;run.projectIntegrationFence=fence;await tx.put('project',touch(project));await tx.put('run',touch(run));return lease;}); + } + private assertProjectLease(actor:Actor,run:Run,project:Entity){ + if(this.env.NODE_ENV!=='production'&&!run.executionGeneration)return; + const lock=project.integrationLease as IntegrationLease|undefined; + if(!lock||lock.runId!==run.id||lock.generation!==run.executionGeneration||lock.verifierId!==actor.userId||lock.leaseToken!==run.lease?.token||lock.fence!==run.projectIntegrationFence||Date.parse(lock.expiresAt)<=Date.now())throw new DomainError('INTEGRATION_LEASE_REQUIRED','A live database-backed project integration lease is required'); + } + async renew(actor:Actor,id:string,leaseToken:number,fence:number){return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);executionLease(actor,run,leaseToken);const project=await projectAccess(tx,actor,run.projectId);this.assertProjectLease(actor,run,project);const lock=project.integrationLease as IntegrationLease;if(!lock||lock.fence!==fence)throw new DomainError('STALE_INTEGRATION_FENCE','Project integration ownership changed');lock.expiresAt=new Date(Math.min(Date.now()+60000,Date.parse(run.lease!.expiresAt))).toISOString();await tx.put('project',touch(project));return lock;});} + async release(actor:Actor,id:string,leaseToken:number,fence:number){return this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);executionScope(actor,run);const project=await projectAccess(tx,actor,run.projectId);const lock=project.integrationLease as IntegrationLease|undefined;if(lock?.runId===id&&lock.generation===run.executionGeneration&&lock.verifierId===actor.userId&&lock.leaseToken===leaseToken&&lock.fence===fence){delete project.integrationLease;await tx.put('project',touch(project));return{released:true};}return{released:false};});} + async enforce(actor:Actor,id:string,leaseToken:number){const before=await this.load(actor,id);executionLease(actor,before.run,leaseToken);try{await this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);executionLease(actor,run,leaseToken);this.assertProjectLease(actor,run,await projectAccess(tx,actor,run.projectId));});const loaded=await this.fresh(actor,id);await this.store.transaction(actor.tenantId,async tx=>{const current=await must(tx,'run',id);executionLease(actor,current,leaseToken);this.assertProjectLease(actor,current,await projectAccess(tx,actor,current.projectId)); + if(current.revision!==loaded.run.revision||digest(current.workspaceInputs??[])!==digest(loaded.inputs))throw new DomainError('WORKSPACE_INPUT_CHANGED','Workspace inputs changed during current-state checks'); + const active=(await tx.list('workspace')).filter(w=>w.projectId===current.projectId&&w.status!=='archived'&&(w.status==='ready'||typeof w.upstreamUrl==='string')); + const versions=(list:Entity[])=>list.map(w=>({id:w.id,version:w.version})).sort((a,b)=>a.id.localeCompare(b.id)); + if(digest(versions(active))!==digest(versions(loaded.workspaces)))throw new DomainError('WORKSPACE_INPUT_CHANGED','Workspace membership or provisioning changed during current-state checks'); + if(!active.length)return;const match=current.workspaceInputMatch as MatchRecord|undefined;if(!match||match.generation!==current.executionGeneration||match.leaseToken!==current.lease?.token||match.inputDigest!==digest(loaded.inputs))throw new DomainError('WORKSPACE_GIT_MATCH_REQUIRED','Independent verifier must match the imported snapshot to the committed integration input in this execution generation');});}catch(error){if(error instanceof DomainError&&(error.code.startsWith('WORKSPACE_')||error.code.startsWith('INTEGRATION_')))await this.store.transaction(actor.tenantId,async tx=>{const run=await must(tx,'run',id);executionLease(actor,run,leaseToken);if(['succeeded','failed','canceled','paused'].includes(run.status))return;run.status='waiting';run.waitingReason=error.code.toLowerCase();if(run.lastActiveAt)run.activeMilliseconds+=Math.max(0,Date.now()-Date.parse(run.lastActiveAt));run.lastActiveAt=undefined;if(run.lease)run.lease.expiresAt=new Date().toISOString();await tx.put('run',touch(run));await tx.event(id,'run.waiting',error.message);});throw error;}} +} diff --git a/apps/api/src/domain/workspace-launch.ts b/apps/api/src/domain/workspace-launch.ts new file mode 100644 index 0000000..140295c --- /dev/null +++ b/apps/api/src/domain/workspace-launch.ts @@ -0,0 +1,9 @@ +import {DomainError,type Actor} from '@wishforge/contracts'; +import type {Store} from '../db/store.js'; +import {must,projectAccess} from './control-plane.js'; +import {requireHuman,requireRole} from './policy.js'; +import {resolveGatewayTarget,validateGatewayLaunch} from './gateway-target.js'; +export class WorkspaceLaunch{ + constructor(private store:Store,private env=process.env,private fetcher:typeof fetch=fetch){} + async launch(actor:Actor,id:string,authorization:string){requireHuman(actor);requireRole(actor,['owner','admin','developer']);await this.store.transaction(actor.tenantId,async tx=>{const workspace=await must(tx,'workspace',id);await projectAccess(tx,actor,String(workspace.projectId));if(workspace.status!=='ready'||!workspace.upstreamUrl)throw new DomainError('WORKSPACE_NOT_READY','Workspace is not ready',503);});const target=await resolveGatewayTarget(this.env,actor.tenantId);if(!target)throw new DomainError('GATEWAY_UNCONFIGURED','No IDE gateway is configured for this tenant',503);const response=await this.fetcher(new URL('/launch',target.internalUrl),{method:'POST',headers:{authorization,'content-type':'application/json'},body:JSON.stringify({workspaceId:id}),redirect:'error',signal:AbortSignal.timeout(15000)}).catch(()=>{throw new DomainError('GATEWAY_UNAVAILABLE','Tenant IDE gateway is unavailable',503);});if(!response.ok)throw new DomainError('IDE_LAUNCH_DENIED','Tenant gateway denied this interactive workspace session',[401,403,404].includes(response.status)?response.status:503);return validateGatewayLaunch(target,await response.json());} +} diff --git a/apps/api/src/domain/workspace-lifecycle.ts b/apps/api/src/domain/workspace-lifecycle.ts new file mode 100644 index 0000000..305f146 --- /dev/null +++ b/apps/api/src/domain/workspace-lifecycle.ts @@ -0,0 +1,49 @@ +import {resolveGatewayTarget} from './gateway-target.js'; +import {resolveProvisionerTarget} from './provisioner-target.js'; +import { randomUUID } from 'node:crypto'; +import { DomainError, type Actor, type Entity } from '@wishforge/contracts'; +import type { OutboxItem, Store, Transaction } from '../db/store.js'; +import { idempotent, must, projectAccess, touch } from './control-plane.js'; +import { digest, requireHuman, requireRole } from './policy.js'; +import { validateSnapshot, type WorkspaceSnapshot } from '../../../../packages/runtime/src/workspace-snapshot.js'; +export const WORKSPACE_IDLE_MS=30*60_000; +interface Lifecycle {revision:number;desired:'paused'|'running';automatic:boolean;requestedAt:string;operationId:string;state:'queued'|'unknown'|'observing'|'complete';snapshotDigest?:string} +interface SleepState {workspaceId:string;gatewayConnections:number;known:boolean;activeClients:number;terminals:number;debugSessions:number;dirty:boolean;snapshotComplete:boolean;snapshotRevision:number;diskDigest:string} +export class WorkspaceLifecycle { + constructor(private store:Store,private env=process.env,private fetcher:typeof fetch=fetch){} + + private async access(tx:Transaction,actor:Actor,id:string){requireHuman(actor);requireRole(actor,['owner','admin','developer']);const currentRole=await tx.membership(actor.userId);if(!currentRole||!['owner','admin','developer'].includes(currentRole))throw new DomainError('FORBIDDEN','Workspace permission was revoked',403);const workspace=await must(tx,'workspace',id);await projectAccess(tx,{...actor,role:currentRole},String(workspace.projectId));return workspace;} + private safe(w:Entity){return{id:w.id,status:w.status,lifecycle:w.lifecycle,reason:w.reason,lastActivityAt:w.lastActivityAt};} + private async configured(tenantId:string){const [provisioner,gateway]=await Promise.all([resolveProvisionerTarget(this.env,tenantId),resolveGatewayTarget(this.env,tenantId)]);if(!provisioner||!gateway)throw new DomainError('WORKSPACE_LIFECYCLE_UNCONFIGURED','Scoped workspace provisioner and gateway are required for this tenant',503);return{provisioner,gateway};} + async manual(actor:Actor,id:string,action:'pause'|'resume',key:string,authorization:string){ + if(!key||key.length<8||key.length>200)throw new DomainError('IDEMPOTENCY_REQUIRED','Provide an Idempotency-Key of 8–200 characters',400); + const request={workspaceId:id,action};const before=await this.store.transaction(actor.tenantId,async tx=>{const workspace=await this.access(tx,actor,id);const previous=await tx.idempotency(key);if(previous){if(previous.digest!==digest(request))throw new DomainError('IDEMPOTENCY_CONFLICT','Key already identifies another workspace action');return{previous:previous.response,workspace};}return{workspace};});if('previous' in before)return before.previous; + const {gateway}=await this.configured(actor.tenantId);if(before.workspace.managedBy!=='wishforge-provisioner')throw new DomainError('WORKSPACE_LIFECYCLE_UNCONFIGURED','This workspace does not have a managed lifecycle',503); + const desired=action==='pause'?'paused':'running';if(before.workspace.status===(action==='pause'?'paused':'ready'))return this.store.transaction(actor.tenantId,async tx=>{const current=await this.access(tx,actor,id);return idempotent(tx,key,request,async()=>{if(current.status!==before.workspace.status)throw new DomainError('WORKSPACE_OPERATION_CHANGED','Workspace changed before no-op confirmation');return this.safe(current);});}); + if(!['ready','paused','pausing','resuming','unknown'].includes(String(before.workspace.status)))throw new DomainError('WORKSPACE_NOT_READY','Workspace provisioning must be reconciled first'); + let snapshot:WorkspaceSnapshot|undefined; + if(action==='pause'){ + if(before.workspace.status!=='ready')throw new DomainError('WORKSPACE_OPERATION_PENDING','Resolve the existing lifecycle operation before pausing'); + const response=await this.fetcher(new URL(`/workspaces/${id}/_wishforge/integration/snapshot`,gateway.internalUrl),{method:'POST',headers:{authorization,'content-type':'application/json'},body:'{}',redirect:'error',signal:AbortSignal.timeout(45000)}).catch(()=>{throw new DomainError('WORKSPACE_SAVE_REQUIRED','Could not confirm all editor saves; workspace remains running');}); + if(!response.ok)throw new DomainError('WORKSPACE_SAVE_REQUIRED','Every active editor must acknowledge a saved snapshot before pausing'); + const receipt=await response.json() as {workspaceId:string;dirty:boolean;latestSnapshot?:WorkspaceSnapshot;currentDiskDigest:string};if(receipt.workspaceId!==id||receipt.dirty!==false||!receipt.latestSnapshot||receipt.currentDiskDigest!==receipt.latestSnapshot.digest)throw new DomainError('WORKSPACE_SAVE_REQUIRED','Workspace changed while saving');validateSnapshot(receipt.latestSnapshot);snapshot=receipt.latestSnapshot; + } + return this.store.transaction(actor.tenantId,async tx=>{const workspace=await this.access(tx,actor,id);return idempotent(tx,key,request,async()=>{if(workspace.upstreamUrl!==before.workspace.upstreamUrl||Number((workspace.lifecycle as Lifecycle|undefined)?.revision??0)!==Number((before.workspace.lifecycle as Lifecycle|undefined)?.revision??0))throw new DomainError('WORKSPACE_OPERATION_CHANGED','Another lifecycle action took ownership');return this.queue(tx,workspace,desired,false,snapshot?.digest);});}); + } + private async queue(tx:Transaction,workspace:Entity,desired:Lifecycle['desired'],automatic:boolean,snapshotDigest?:string){const revision=Number((workspace.lifecycle as Lifecycle|undefined)?.revision??0)+1;const operationId=randomUUID();workspace.lifecycle={revision,desired,automatic,requestedAt:new Date().toISOString(),operationId,state:'queued',snapshotDigest} satisfies Lifecycle;workspace.status=desired==='paused'?'pausing':'resuming';workspace.reason='Waiting for the isolated workspace controller to confirm the requested state.';await tx.put('workspace',touch(workspace));await tx.enqueue('workspace.reconcile',{workspaceId:workspace.id,projectId:workspace.projectId,revision,desired},operationId);return this.safe(workspace);} + private async safety(workspace:Entity):Promise{const gateway=await resolveGatewayTarget(this.env,workspace.tenantId);if(!gateway)throw new DomainError('WORKSPACE_ACTIVITY_UNKNOWN','Tenant gateway is unavailable');const response=await this.fetcher(new URL('/internal/lifecycle-state',gateway.internalUrl),{method:'POST',headers:{authorization:`Bearer ${gateway.token}`,'content-type':'application/json'},body:JSON.stringify({tenantId:workspace.tenantId,workspaceId:workspace.id}),redirect:'error',signal:AbortSignal.timeout(15000)});if(!response.ok)throw new DomainError('WORKSPACE_ACTIVITY_UNKNOWN','Workspace activity cannot be established');const value=await response.json() as SleepState;if(value.workspaceId!==workspace.id||value.known!==true||value.gatewayConnections!==0||value.activeClients!==0||value.terminals!==0||value.debugSessions!==0||value.dirty!==false||value.snapshotComplete!==true||!Number.isSafeInteger(value.snapshotRevision)||value.snapshotRevision<1||!/^[a-f0-9]{64}$/.test(value.diskDigest))throw new DomainError('WORKSPACE_NOT_IDLE','Workspace has active or unknown work, or lacks a complete saved snapshot');return value;} + async scheduleIdle(tenantId:string){if(this.env.WF_WORKSPACE_AUTO_SLEEP==='false')return;try{await this.configured(tenantId);}catch{return;}const cutoff=Date.now()-WORKSPACE_IDLE_MS;const candidates=await this.store.transaction(tenantId,async tx=>(await tx.list('workspace')).filter(w=>w.managedBy==='wishforge-provisioner'&&w.status==='ready'&&typeof w.lastActivityAt==='string'&&Date.parse(w.lastActivityAt)<=cutoff));for(const before of candidates){try{const receipt=await this.safety(before);await this.store.transaction(tenantId,async tx=>{const w=await must(tx,'workspace',before.id);if(w.status!=='ready'||w.lastActivityAt!==before.lastActivityAt||Date.parse(String(w.lastActivityAt))>cutoff)return;await this.queue(tx,w,'paused',true,receipt.diskDigest);});}catch{/* Unknown or active work is never automatically stopped. */}}} + async reconcile(tenantId:string,item:OutboxItem){const workspace=await this.store.transaction(tenantId,tx=>must(tx,'workspace',String(item.payload.workspaceId)));const operation=workspace.lifecycle as Lifecycle|undefined;if(!operation||operation.operationId!==item.id||operation.revision!==item.payload.revision){await this.store.transaction(tenantId,tx=>tx.acknowledge(item.id));return;} + try{const {provisioner}=await this.configured(tenantId); + if(operation.automatic&&Date.now()-Date.parse(operation.requestedAt)<5000){await this.store.transaction(tenantId,tx=>tx.defer(item.id,5));return;} + const target=new URL(`${provisioner.url}/workspaces/${workspace.id}/lifecycle`);target.searchParams.set('tenantId',tenantId);target.searchParams.set('projectId',String(workspace.projectId));const headers={authorization:`Bearer ${provisioner.token}`,'content-type':'application/json'}; + // Always observe first. A lost response never causes an unconditional mutation replay. + const observed=await this.fetcher(target,{headers,redirect:'error',signal:AbortSignal.timeout(15000)});if(!observed.ok)throw new Error('WORKSPACE_OBSERVE_UNKNOWN');let state=await observed.json() as {workspaceId:string;revision:number;desired:string;status:string}; + const valid=()=>state.workspaceId===workspace.id&&Number.isSafeInteger(state.revision)&&state.revision>=0&&['running','paused'].includes(state.desired)&&['ready','paused','pending'].includes(state.status);if(!valid()||state.revision>operation.revision)throw new Error('WORKSPACE_OBSERVE_UNKNOWN'); + if(state.revision{const current=await must(tx,'workspace',workspace.id);if((current.lifecycle as Lifecycle|undefined)?.operationId!==item.id)return;await this.queue(tx,current,'running',false);await tx.acknowledge(item.id);});return;}} + if(state.revision{const current=await must(tx,'workspace',workspace.id);if((current.lifecycle as Lifecycle|undefined)?.operationId!==item.id)throw new Error('WORKSPACE_SUPERSEDED');if(operation.automatic&¤t.lastActivityAt!==workspace.lastActivityAt)throw new Error('WORKSPACE_ACTIVITY_CHANGED');current.lifecycle={...operation,state:'unknown'};await tx.put('workspace',touch(current));});target.search='';const changed=await this.fetcher(target,{method:'PUT',headers,body:JSON.stringify({tenantId,projectId:workspace.projectId,workspaceId:workspace.id,revision:operation.revision,desired:operation.desired}),redirect:'error',signal:AbortSignal.timeout(15000)});if(!changed.ok)throw new Error('WORKSPACE_RECONCILE_UNKNOWN');state=await changed.json() as typeof state;} + if(!valid()||state.revision!==operation.revision||state.desired!==operation.desired)throw new Error('WORKSPACE_OBSERVE_UNKNOWN'); + await this.store.transaction(tenantId,async tx=>{const current=await must(tx,'workspace',workspace.id);if((current.lifecycle as Lifecycle|undefined)?.operationId!==item.id)return;const complete=(operation.desired==='paused'&&state.status==='paused')||(operation.desired==='running'&&state.status==='ready');current.lifecycle={...operation,state:complete?'complete':'observing'};current.status=complete?state.status:operation.desired==='paused'?'pausing':'resuming';current.reason=complete?undefined:'Waiting for observed workspace replicas and readiness.';if(complete&&state.status==='ready')current.lastActivityAt=new Date().toISOString();await tx.put('workspace',touch(current));if(complete)await tx.acknowledge(item.id);else await tx.defer(item.id,10);}); + }catch{await this.store.transaction(tenantId,async tx=>{const current=await must(tx,'workspace',workspace.id);if((current.lifecycle as Lifecycle|undefined)?.operationId!==item.id)return;current.status='unknown';current.reason='Workspace controller outcome is unknown; observation will be retried before any new action.';current.lifecycle={...operation,state:'unknown'};await tx.put('workspace',touch(current));await tx.defer(item.id,30);});} + } +} diff --git a/apps/api/src/http.ts b/apps/api/src/http.ts new file mode 100644 index 0000000..36b51eb --- /dev/null +++ b/apps/api/src/http.ts @@ -0,0 +1,175 @@ +import {resolveGatewayTarget} from './domain/gateway-target.js'; +import { Body, Controller, Delete, Get, HttpCode, Inject, Param, Patch, Post, Query, Req, Res, type ExceptionFilter, Catch, type ArgumentsHost } from '@nestjs/common'; +import type { Request, Response } from 'express'; +import { z, ZodError } from 'zod'; +import { DomainError, type Actor, type Entity, type Project, type Run, type Release } from '@wishforge/contracts'; +import { Authenticator } from './auth.js'; +import { ControlPlane, must, projectAccess, record, touch } from './domain/control-plane.js'; +import { Releases } from './domain/releases.js'; +import { Evolution, resolveBundle } from './domain/evolution.js'; +import { Connections } from './domain/connections.js'; +import { RunnerBroker } from './domain/runner-broker.js'; +import { GitStorage } from './domain/git-storage.js'; +import { GitHubIntegration } from './domain/github.js'; +import { Billing } from './domain/billing.js'; +import { Entitlements, requireCapacity } from './domain/entitlements.js'; +import { bundleConfigSchema, bundleDigest } from '../../../packages/evolution/src/index.js'; +import { MetaEvolution } from './domain/meta-evolution.js'; +import { requireRole, requireHuman } from './domain/policy.js'; +import { configuredVerificationProfiles, selectVerificationProfile } from './domain/verification-policy.js'; + +export class Services { + auth: Authenticator; releases: Releases; evolution: Evolution; connections: Connections; runners: RunnerBroker; github: GitHubIntegration; + constructor(readonly control: ControlPlane) { this.auth = new Authenticator(control.store, control.env); this.releases = new Releases(control.store, control.env); this.evolution = new Evolution(control.store, control.env); this.connections = new Connections(control.store, control.env); this.runners = new RunnerBroker(control.store, control, this.releases, control.env); this.github = new GitHubIntegration(control.store, control.env); } +} +type AuthRequest = Request & { actor: Actor }; +const ok = (data: T) => ({ data }); +const key = (req: Request) => req.header('Idempotency-Key'); + +@Catch() +export class Errors implements ExceptionFilter { + catch(error: unknown, host: ArgumentsHost) { + const res = host.switchToHttp().getResponse(); + if (res.headersSent) return res.end(); + if (error instanceof ZodError) return res.status(400).json({ error: { code: 'INVALID_INPUT', message: 'Request validation failed', details: error.flatten() } }); + if (error instanceof DomainError) return res.status(error.status).json({ error: { code: error.code, message: error.message, details: error.details } }); + console.error(error instanceof Error ? `${error.name}: ${error.message}` : 'Internal request failure'); + return res.status(500).json({ error: { code: 'INTERNAL_ERROR', message: 'Request failed. Consult the server audit log.' } }); + } +} + +@Controller('v1') +export class ApiController { + constructor(@Inject(Services) private s: Services) {} + @Get('dashboard') async dashboard(@Req() req: AuthRequest) { + const a = req.actor; const [projects, runs, releases, providers, evolution, usage] = await Promise.all([this.s.control.projects(a), this.s.control.runs(a), this.s.releases.list(a), this.s.control.providers(a), this.s.evolution.list(a), this.s.control.usage(a)]); + return ok({ projects, runs, releases, providers, evolution, usage, system: { mode: this.s.control.env.NODE_ENV === 'production' ? 'production' : 'development', region: this.s.control.env.WF_REGION ?? 'unconfigured', authMode: this.s.control.env.WF_DEV_AUTH_TOKEN ? 'local-development' : 'oidc' } }); + } + @Get('projects') async projects(@Req() r: AuthRequest) { return ok(await this.s.control.projects(r.actor)); } + @Post('projects') async createProject(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await this.s.control.createProject(r.actor, b)); } + @Get('verification-profiles') async verificationProfiles() { return ok(configuredVerificationProfiles(this.s.control.env).map(({ id, version }) => ({ id, version }))); } + @Post('projects/:id/verification-profile') async verificationProfile(@Req() r: AuthRequest, @Param('id') id: string, @Body() body: unknown) { + requireRole(r.actor, ['owner', 'admin']); requireHuman(r.actor); + const { profileId } = z.object({ profileId: z.string().min(1).max(80) }).strict().parse(body); + const profile = selectVerificationProfile(profileId, this.s.control.env); + return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { const project = await projectAccess(tx, r.actor, id); const next = { ...touch(project), verificationProfile: profile }; await tx.put('project', next); return next; })); + } + @Post('projects/:id/repository') async provisionRepository(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.control.provisionRepository(r.actor, id)); } + @Get('projects/:id/github') async githubStatus(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.github.status(r.actor, id)); } + @Post('runs/:id/github/pull-requests') async githubPr(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.github.createPullRequest(r.actor, id, b)); } + @Get('github/operations/:id') async githubRead(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.github.readPullRequest(r.actor, id)); } + @Post('github/operations/:id/authorize-merge') async githubAuthorize(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { expectedHeadSha: string; expectedBaseSha: string }) { return ok(await this.s.github.authorizeMerge(r.actor, id, b)); } + @Post('github/operations/:id/merge') async githubMerge(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.github.merge(r.actor, id)); } + @Get('projects/:id') async project(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.control.store.transaction(r.actor.tenantId, tx => projectAccess(tx, r.actor, id))); } + @Patch('projects/:id') async settings(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { + requireRole(r.actor, ['owner', 'admin']); requireHuman(r.actor); + const data = z.object({ canaryOptIn: z.boolean().optional(), verificationCommands: z.array(z.array(z.string().min(1)).min(1)).max(20).optional(), memberIds: z.array(z.string().min(1)).optional(), deliveryConfig: z.object({ imageRepository: z.string().min(1), architecture: z.enum(['linux/amd64', 'linux/arm64']), environmentId: z.string().min(1), dockerfile: z.string().default('Dockerfile'), sourceContext: z.string().default('.'), targetBranch: z.string().optional(), dockerContext: z.string().optional(), containerPort: z.number().int().min(1).max(65535), healthPath: z.string().startsWith('/'), smokeChecks: z.array(z.object({ path: z.string().startsWith('/'), expectedStatus: z.number().int().min(100).max(599), bodyIncludes: z.string().optional() })).min(1) }).strict().optional() }).strict().parse(b); + return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { const p = await projectAccess(tx, r.actor, id); const next = { ...touch(p), ...data }; await tx.put('project', next); return next; })); + } + @Post('projects/:id/wishes') @HttpCode(202) async submit(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.control.submit(r.actor, id, b, key(r))); } + @Get('runs') async runs(@Req() r: AuthRequest) { return ok(await this.s.control.runs(r.actor)); } + @Get('runs/:id') async run(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.control.run(r.actor, id)); } + @Get('runs/:id/events') async events(@Req() r: AuthRequest, @Param('id') id: string, @Query('after') after?: string) { return ok(await this.s.control.events(r.actor, id, Math.max(0, Number(after) || 0))); } + @Get('runs/:id/events/stream') async stream(@Req() r: AuthRequest, @Res() res: Response, @Param('id') id: string, @Query('after') after?: string) { + await this.s.control.run(r.actor, id); + res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' }); res.flushHeaders(); + let cursor = Math.max(0, Number(r.header('Last-Event-ID') ?? after) || 0), busy = false; + const pump = async () => { if (busy || res.writableEnded) return; busy = true; try { const actor = await this.s.auth.authenticate(r.header('Authorization')); for (const e of await this.s.control.events(actor, id, cursor)) { res.write(`id: ${e.seq}\nevent: run\ndata: ${JSON.stringify(e)}\n\n`); cursor = e.seq; } res.write(': heartbeat\n\n'); } catch { res.end(); } finally { busy = false; } }; + const timer = setInterval(() => void pump(), 2000); r.on('close', () => clearInterval(timer)); await pump(); + } + @Post('runs/:id/commands') async command(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.control.command(r.actor, id, b, key(r))); } + @Get('runs/:id/artifacts') async artifacts(@Req() r: AuthRequest, @Param('id') id: string) { const {evidence,checkpoint,release}=await this.s.releases.delivery(r.actor,id);return ok({evidence,checkpoint,release}); } + @Get('runs/:id/delivery') async delivery(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.releases.delivery(r.actor,id)); } + @Get('providers') async providers(@Req() r: AuthRequest) { return ok(await this.s.control.providers(r.actor)); } + @Get('artifacts/:id') async artifactMetadata(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.control.artifacts.metadata(r.actor, id)); } + @Get('artifacts/:id/download') async artifactDownload(@Req() r: AuthRequest, @Param('id') id: string, @Res() res: Response) { const { metadata, body } = await this.s.control.artifacts.download(r.actor, id); res.set({ 'Content-Type': metadata.contentType, 'Content-Length': String(body.length), 'Content-Disposition': `attachment; filename="${metadata.sha256}.bundle"`, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store' }); res.send(body); } + @Get('provider-connections') async connections(@Req() r: AuthRequest) { return ok(await this.s.connections.list(r.actor)); } + @Post('provider-connections') async connect(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await this.s.connections.create(r.actor, b)); } + @Delete('provider-connections/:id') async revoke(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.connections.revoke(r.actor, id)); } + @Get('environments') async envs(@Req() r: AuthRequest) { return ok(await this.s.releases.environments(r.actor)); } + @Patch('environments/:id/access') async environmentAccess(@Req() r:AuthRequest,@Param('id') id:string,@Body() body:unknown){const input=z.object({applicationUrl:z.string().max(2048).nullable(),visibility:z.enum(['private','public'])}).strict().parse(body);return ok(await this.s.releases.updateAccess(r.actor,id,input));} + @Patch('environments/:id/deployment-secrets') async environmentSecrets(@Req()r:AuthRequest,@Param('id')id:string,@Body()body:unknown){const input=z.object({secretVersionRefs:z.array(z.string().min(1).max(256)).max(32),deploymentSecretPolicyDigest:z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable()}).strict().parse(body);return ok(await this.s.releases.updateDeploymentSecrets(r.actor,id,input));} + @Post('environments') async env(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await this.s.releases.createEnvironment(r.actor, b)); } + @Post('environments/:id/runners') async runner(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.runners.register(r.actor, id)); } + @Get('releases') async releases(@Req() r: AuthRequest) { return ok(await this.s.releases.list(r.actor)); } + @Post('releases') async release(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await this.s.releases.request(r.actor, b, key(r))); } + @Post('approvals/:id/decision') async decision(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { decision: string; bindingDigest: string }) { return ok(await this.s.releases.decide(r.actor, id, b)); } + @Post('releases/:id/rollback') async rollback(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.releases.rollback(r.actor, id, key(r))); } + @Get('evolution') async evolution(@Req() r: AuthRequest) { return ok(await this.s.evolution.list(r.actor)); } + @Get('evolution/bundle') async activeBundle(@Req() r: AuthRequest) { return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { const routing = await tx.get('policy', 'evolution-routing-v1'); const stableVersion = String(routing?.stableVersion ?? 'baseline-v1'); return { stableVersion, config: await resolveBundle(tx, stableVersion) }; })); } + @Post('evolution') async candidate(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await this.s.evolution.create(r.actor, b)); } + @Post('evolution/tick') async metaTick(@Req() r: AuthRequest) { return ok(await new MetaEvolution(this.s.control).tick(r.actor)); } + @Post('evolution/:id/commands') async evolve(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { action: string }) { return ok(await this.s.evolution.command(r.actor, id, b.action)); } + @Get('entitlements') async entitlements(@Req() r: AuthRequest) { return ok(await new Entitlements(this.s.control.store, this.s.control.env).view(r.actor)); } + @Get('billing/plans') async billingPlans(@Req() r: AuthRequest) { return ok(await new Entitlements(this.s.control.store, this.s.control.env).plans(r.actor)); } + @Post('billing/members') async inviteMember(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await new Entitlements(this.s.control.store, this.s.control.env).inviteMember(r.actor, b, key(r))); } + @Post('billing/executions/:id/reconcile') async reconcileResources(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await new Entitlements(this.s.control.store, this.s.control.env).reconcileAllocation(r.actor, id, b, key(r))); } + @Get('billing/usage') async billingUsage(@Req() r: AuthRequest, @Query('period') period?: string) { return ok(await new Billing(this.s.control.store, this.s.control.env).usage(r.actor, period)); } + @Get('billing/invoices/:period') async billingInvoice(@Req() r: AuthRequest, @Param('period') period: string) { return ok(await new Billing(this.s.control.store, this.s.control.env).invoice(r.actor, period)); } + @Get('billing/invoices/:period/export') async billingExport(@Req() r: AuthRequest, @Param('period') period: string, @Res() res: Response) { const exported = await new Billing(this.s.control.store, this.s.control.env).exportCsv(r.actor, period); res.type('text/csv').setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`); res.send(exported.content); } + @Post('billing/invoices/:period/settlement') async billingSettlement(@Req() r: AuthRequest, @Param('period') period: string, @Body() b: unknown) { return ok(await new Billing(this.s.control.store, this.s.control.env).settle(r.actor, period, b, key(r))); } + @Get('usage') async usage(@Req() r: AuthRequest) { return ok(await this.s.control.usage(r.actor)); } + @Get('usage/export') async exportUsage(@Req() r: AuthRequest, @Res() res: Response) { const exported = await new Billing(this.s.control.store, this.s.control.env).exportCsv(r.actor); res.type('text/csv').setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`); res.send(exported.content); } + @Get('projects/:id/workspaces') async workspaces(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { await projectAccess(tx, r.actor, id); return (await tx.list('workspace')).filter(w => w.projectId === id).map(({ upstreamUrl: _, collaborationUpstreamUrl: _collaboration, ...publicValue }) => publicValue); })); } + @Post('projects/:id/workspaces') async workspace(@Req() r: AuthRequest, @Param('id') id: string) { + requireRole(r.actor, ['owner', 'admin', 'developer']); + return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { await projectAccess(tx, r.actor, id); const existing = (await tx.list('workspace')).find(w => w.projectId === id); if (existing) return existing; await requireCapacity(tx, 'workspace'); const workspace = { ...record(r.actor.tenantId), projectId: id, status: 'unconfigured', reason: 'An isolated Theia workspace provisioner and authenticated gateway must be connected before this workspace can be opened.' }; await tx.put('workspace', workspace); await tx.enqueue('workspace.provision', { workspaceId: workspace.id, projectId: id }); return workspace; })); + } +} + +@Controller('internal') +export class InternalController { + constructor(@Inject(Services) private s: Services) {} + @Post('runs/:id/github/state') async githubState(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number }) { return ok(await this.s.github.workerState(r.actor, id, b.leaseToken)); } + @Post('runs/:id/github/create') async githubCreate(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.github.workerCreate(r.actor, id, b)); } + @Post('runs/:id/github/advance') async githubAdvance(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.github.workerAdvance(r.actor, id, b)); } + @Get('runner/tasks') async runnerTask(@Req() r: AuthRequest, @Query('environmentId') environmentId: string) { return this.s.runners.poll(r.actor, environmentId); } + @Post('runner/tasks/:id/result') async runnerResult(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { result: { releaseId: string; status: string; target: string; evidence: Record } }) { return this.s.runners.result(r.actor, id, b); } + @Post('runs/:id/lease') async lease(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { workerId: string; generation?: string }) { if (!b.workerId) throw new DomainError('INVALID_WORKER', 'workerId required', 400); return ok(await this.s.control.lease(r.actor, id, b.workerId, b.generation)); } + @Post('runs/:id/lease/release') async releaseLease(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number }) { return ok(await this.s.control.releaseLease(r.actor, id, b.leaseToken)); } + @Post('runs/:id/heartbeat') async heartbeat(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number }) { return ok(await this.s.control.heartbeat(r.actor, id, b.leaseToken)); } + @Post('runs/:id/wait') async wait(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { reason: string; generation?: string }) { return ok(await this.s.control.waitRun(r.actor, id, b.reason, b.generation)); } + @Get('runs/:id/state') async workflowState(@Req() r: AuthRequest, @Param('id') id: string) { if (r.actor.kind !== 'worker' || r.actor.runId) throw new DomainError('FORBIDDEN', 'Trusted coordinator identity required', 403); return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { const run = await must(tx, 'run', id); return { status: run.status, generation: run.executionGeneration, generatedEvolutionCandidateId: run.generatedEvolutionCandidateId }; })); } + @Post('runs/:id/transition') async transition(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.control.transition(r.actor, id, b)); } + @Get('runs/:id/context') async context(@Req() r: AuthRequest, @Param('id') id: string) { const context = await this.s.control.context(r.actor, id); const [providerCredential, gitCredential] = await Promise.all([this.s.connections.forRun(r.actor, context.run), context.project.repositoryStorage === 'platform' ? new GitStorage(this.s.control.env).credential(r.actor, context.project, context.run) : this.s.github.app.configured() ? this.s.github.credential(r.actor, context.project, context.run) : undefined]); return ok({ ...context, providerCredential, gitCredential }); } + @Post('runs/:id/checkpoint') async checkpoint(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number; checkpoint: Record; workspace?: string }) { return ok(await this.s.control.checkpoint(r.actor, id, b.checkpoint, b.leaseToken, b.workspace)); } + @Post('runs/:id/classification') async classification(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number; sourceCommit: string; changedPaths: string[]; migration: boolean; permissionsExpanded: boolean }) { return ok(await this.s.control.classify(r.actor, id, b)); } + @Post('runs/:id/events') async events(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number; event: Record }) { return ok(await this.s.control.providerEvent(r.actor, id, b.leaseToken, b.event)); } + @Post('runs/:id/meter') async meter(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { operationId: string; tokens: number; computeSeconds: number; leaseToken: number }) { return ok(await this.s.control.meter(r.actor, id, b)); } + @Post('evidence') async evidence(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await this.s.control.evidence(r.actor, b)); } + @Post('runs/:id/evolution-code-candidate') async extractedCodeCandidate(@Req() r: AuthRequest, @Param('id') id: string, @Body() body: unknown) { + const { leaseToken } = z.object({ leaseToken: z.number().int().positive() }).strict().parse(body); + const candidate = await this.s.evolution.createCodeCandidate(r.actor, id, leaseToken); + return ok({ candidateId: candidate.id, candidateDigest: candidate.candidateDigest, scope: candidate.scope, status: candidate.status }); + } + @Post('runs/:id/evolution-candidate') async extractedCandidate(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { leaseToken: number; bundleConfig: unknown }) { + const config = bundleConfigSchema.parse(b.bundleConfig); + const run = await this.s.control.store.transaction(r.actor.tenantId, tx => must(tx, 'run', id)); + const candidate = await this.s.evolution.create(r.actor, { name: `Verified improvement ${id.slice(0, 8)}`, hypothesis: run.goal.slice(0, 4000), scope: run.evolutionScope, parentBundle: run.baselineBundle, candidateDigest: bundleDigest(config), targetMetric: 'success', dataScope: 'platform', bundleConfig: config }, { runId: id, leaseToken: b.leaseToken }); + return ok({ candidateId: candidate.id, candidateDigest: candidate.candidateDigest, status: candidate.status }); + } + @Post('releases') async release(@Req() r: AuthRequest, @Body() b: unknown) { if (r.actor.kind !== 'deployer') throw new DomainError('FORBIDDEN', 'Deployer required', 403); return ok(await this.s.releases.request(r.actor, b, key(r))); } + @Post('releases/:id/begin') async begin(@Req() r: AuthRequest, @Param('id') id: string) { return ok(await this.s.releases.begin(r.actor, id)); } + @Post('releases/:id/accept') async accept(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { evidenceId: string; bindingDigest: string }) { return ok(await this.s.releases.accept(r.actor, id, b)); } + @Post('releases/:id/failure') async failure(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { status: 'failed' | 'unknown'; message: string }) { if (!['failed', 'unknown'].includes(b.status)) throw new DomainError('INVALID_STATUS', 'Failure status required', 400); return ok(await this.s.releases.reportFailure(r.actor, id, b.status, b.message)); } + @Post('evolution/:id/evaluation') async evaluation(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.evolution.evaluate(r.actor, id, b)); } + @Post('evolution/rollout/tick') async rolloutTick(@Req() r: AuthRequest) { return ok(await this.s.evolution.rolloutTick(r.actor)); } + @Get('evolution/external-actions') async externalEvolutionActions(@Req() r: AuthRequest) { + if (r.actor.kind !== 'evaluator' || r.actor.tenantId !== this.s.control.env.WF_SYSTEM_TENANT) throw new DomainError('FORBIDDEN', 'Independent platform release operator required', 403); + return ok((await this.s.evolution.list(r.actor)).filter(c => c.externalAction?.status === 'requested').map(c => ({ candidateId: c.id, candidateDigest: c.candidateDigest, action: c.externalAction, sourceArtifact: c.sourceArtifact }))); + } + @Post('evolution/tick') async systemMetaTick(@Req() r: AuthRequest) { if (r.actor.kind !== 'evaluator') throw new DomainError('FORBIDDEN', 'System evaluator identity required', 403); return ok(await new MetaEvolution(this.s.control).tick(r.actor)); } + @Post('evolution/:id/observations') async observe(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) { return ok(await this.s.evolution.observe(r.actor, id, b)); } + @Post('workspaces/:id/authorize') async authorizeWorkspace(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { userToken: string; operation: string }) { + if (r.actor.userId !== 'workspace-gateway') throw new DomainError('FORBIDDEN', 'Workspace gateway identity required', 403); + const user = await this.s.auth.authenticate(`Bearer ${b.userToken}`); + if (user.tenantId !== r.actor.tenantId) throw new DomainError('NOT_FOUND', 'Workspace not found', 404); + return ok(await this.s.control.store.transaction(user.tenantId, async tx => { const workspace = await must(tx, 'workspace', id); await projectAccess(tx, user, String(workspace.projectId)); if (['edit', 'terminal', 'debug'].includes(b.operation)){requireHuman(user);requireRole(user, ['owner', 'admin', 'developer']);} if (workspace.status !== 'ready' || !workspace.upstreamUrl) throw new DomainError('WORKSPACE_NOT_READY', 'Workspace has not been provisioned', 503); if(r.actor.userId==='workspace-gateway'&&(!workspace.lastActivityAt||Date.now()-Date.parse(String(workspace.lastActivityAt))>=15000)){workspace.lastActivityAt=new Date().toISOString();await tx.put('workspace',workspace);} return { tenantId: user.tenantId, projectId: workspace.projectId, workspaceId: id, upstreamUrl: workspace.upstreamUrl, collaborationUpstreamUrl: workspace.collaborationUpstreamUrl, userId: user.userId, role: user.role }; })); + } + @Post('workspaces/:id/provisioned') async provisioned(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: { upstreamUrl: string; collaborationUpstreamUrl?: string }) { + if (r.actor.kind !== 'worker') throw new DomainError('FORBIDDEN', 'Workspace controller required', 403); + let collaboration: URL | undefined; if (b.collaborationUpstreamUrl) { collaboration = new URL(b.collaborationUpstreamUrl); if (!['http:', 'https:'].includes(collaboration.protocol) || collaboration.username || collaboration.password || collaboration.pathname !== '/' || collaboration.search || collaboration.hash) throw new DomainError('INVALID_COLLABORATION_UPSTREAM', 'Invalid workspace collaboration backend', 400); } const upstream = new URL(b.upstreamUrl); if (!['http:', 'https:'].includes(upstream.protocol) || upstream.username || upstream.password) throw new DomainError('INVALID_UPSTREAM', 'Invalid workspace backend', 400); + const base = (await resolveGatewayTarget(this.s.control.env,r.actor.tenantId))?.publicUrl; if (!base) throw new DomainError('GATEWAY_UNCONFIGURED', 'Authenticated workspace gateway is not configured', 503); + return ok(await this.s.control.store.transaction(r.actor.tenantId, async tx => { const w = await must(tx, 'workspace', id); if(w.lifecycle)throw new DomainError('WORKSPACE_LIFECYCLE_OWNED','Lifecycle controller must reconcile this workspace'); w.status = 'ready'; w.upstreamUrl = upstream.toString(); if (collaboration) w.collaborationUpstreamUrl = collaboration.toString(); w.url = `${base.replace(/\/$/, '')}/workspaces/${id}/`; w.reason = undefined; await tx.put('workspace', touch(w)); return { id, status: w.status, url: w.url }; })); + } +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts new file mode 100644 index 0000000..565854a --- /dev/null +++ b/apps/api/src/main.ts @@ -0,0 +1,71 @@ +import {WorkspaceLaunchController} from './workspace-launch-http.js'; +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { NestFactory } from '@nestjs/core'; +import express from 'express'; +import { DomainError } from '@wishforge/contracts'; +import { PgStore } from './db/store.js'; +import { ControlPlane } from './domain/control-plane.js'; +import { ApiController, InternalController, Services, Errors } from './http.js'; +import { handleMcp } from './mcp.js'; +import { Dispatcher } from './dispatcher.js'; +import { auditContext } from './audit-context.js'; +import { observability } from './telemetry.js'; +import { ProviderProxy } from './domain/provider-proxy.js'; +import { once } from 'node:events'; +import {WorkspaceLifecycleController,WorkspaceLifecycleInternalController} from './workspace-lifecycle-http.js'; +import {WorkspaceLifecycleWorker} from './workspace-lifecycle-worker.js'; +import { WorkspaceInputController, WorkspaceIntegrationController } from './workspace-integration-http.js'; +import { PreviewController, PreviewControlController, PreviewProbeController } from './preview-http.js'; +import { ResourceReconciliationWorker } from './resource-reconciliation-worker.js'; + +export async function bootstrap() { + // Migration credentials belong to operator tools, never the running application. + delete process.env.DATABASE_ADMIN_URL; delete process.env.WF_DATABASE_APP_PASSWORD; + if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is required. Run setup:local, db:migrate and db:seed.'); + const store = new PgStore(process.env.DATABASE_URL); await store.assertSafeRole(); + const service = new Services(new ControlPlane(store)); + const telemetry = await observability(); + @Module({ controllers: [ApiController, InternalController, WorkspaceInputController, WorkspaceIntegrationController, WorkspaceLifecycleController, WorkspaceLifecycleInternalController, WorkspaceLaunchController, PreviewController, PreviewControlController, PreviewProbeController], providers: [{ provide: Services, useValue: service }] }) + class AppModule {} + const app = await NestFactory.create(AppModule, { logger: ['error', 'warn', 'log'], bodyParser: false }); + app.use(express.json({ limit: '8mb' })); app.useGlobalFilters(new Errors()); + const raw = app.getHttpAdapter().getInstance(); raw.disable('x-powered-by'); + raw.use(telemetry.middleware); + raw.get('/metrics', telemetry.metrics); + raw.get('/health', (_req: express.Request, res: express.Response) => res.json({ status: 'ok', service: 'wishforge-control-plane', version: '0.1.0' })); + raw.get('/readyz', async (_req: express.Request, res: express.Response) => { try { await store.pool.query('SELECT 1'); res.json({ status: 'ready' }); } catch { res.status(503).json({ status: 'unavailable' }); } }); + raw.get('/.well-known/oauth-protected-resource', (_req: express.Request, res: express.Response) => res.json({ resource: `${process.env.WF_API_PUBLIC_URL ?? 'http://127.0.0.1:4000'}/mcp`, authorization_servers: process.env.OIDC_ISSUER ? [process.env.OIDC_ISSUER] : [], scopes_supported: ['openid', 'profile', 'wishforge'] })); + const authError = (error: unknown, res: express.Response) => { const known = error instanceof DomainError; res.status(known ? error.status : 500).json({ error: { code: known ? error.code : 'AUTH_UNAVAILABLE', message: known ? error.message : 'Authentication is unavailable' } }); }; + // This route uses a separate token audience and never accepts a normal OIDC or internal-worker credential. + raw.all('/provider-proxy/v1/:resource', async (req: express.Request, res: express.Response) => { + const abort = new AbortController(); res.once('close', () => { if (!res.writableEnded) abort.abort(); }); + try { + const upstream = await new ProviderProxy(store).forward({ authorization: req.header('Authorization'), method: req.method, path: `/${req.params.resource}`, headers: Object.fromEntries(Object.entries(req.headers).filter((entry): entry is [string, string] => typeof entry[1] === 'string')), body: req.method === 'GET' ? undefined : Buffer.from(JSON.stringify(req.body ?? null)), signal: abort.signal }); + res.status(upstream.status); upstream.headers.forEach((value, name) => res.setHeader(name, value)); res.flushHeaders(); + if (upstream.body) { const reader = upstream.body.getReader(); try { while (!abort.signal.aborted) { const part = await reader.read(); if (part.done) break; if (!res.write(Buffer.from(part.value))) await once(res, 'drain', { signal: abort.signal }); } } finally { await reader.cancel().catch(() => undefined); } } + res.end(); + } catch (error) { if (!res.headersSent) authError(error, res); else res.destroy(); } + }); + raw.use('/v1', async (req: express.Request, res: express.Response, next: express.NextFunction) => { try { const actor = await service.auth.authenticate(req.header('Authorization')); (req as express.Request & { actor: unknown }).actor = actor; res.setHeader('Cache-Control', 'no-store'); auditContext.run({ actorId: actor.userId }, next); } catch (error) { authError(error, res); } }); + raw.use('/internal', async (req: express.Request, res: express.Response, next: express.NextFunction) => { try { + const actor = await service.auth.internal(req.header('Authorization'), req.header('X-WishForge-Tenant')); + if (actor.runId) { + const addressed = /^\/runs\/([^/]+)\//.exec(req.path)?.[1] ?? (req.path === '/evidence' ? req.body?.runId : undefined); + if (addressed !== actor.runId) throw new DomainError('FORBIDDEN', 'Execution token is scoped to a single run', 403); + } + if (actor.userId === 'workspace-gateway' && !/^\/workspaces\/[^/]+\/(authorize|integration-authorize|lifecycle-authorize)$/.test(req.path)) throw new DomainError('FORBIDDEN', 'Gateway identity is limited to workspace authorization', 403); + if (actor.userId.startsWith('runner:') && !req.path.startsWith('/runner/')) throw new DomainError('FORBIDDEN', 'Runner identity is limited to assigned deployment tasks', 403); + (req as express.Request & { actor: unknown }).actor = actor; res.setHeader('Cache-Control', 'no-store'); auditContext.run({ actorId: actor.userId }, next); + } catch (error) { authError(error, res); } }); + raw.post('/mcp', async (req: express.Request, res: express.Response) => { try { await handleMcp(service, req, res); } catch (error) { if (!res.headersSent) { res.setHeader('WWW-Authenticate', `Bearer resource_metadata="${process.env.WF_API_PUBLIC_URL ?? 'http://127.0.0.1:4000'}/.well-known/oauth-protected-resource"`); authError(error, res); } } }); + raw.all('/mcp', (_req: express.Request, res: express.Response) => res.status(405).setHeader('Allow', 'POST').end()); + await app.listen(Number(process.env.PORT ?? 4000), process.env.HOST ?? '127.0.0.1'); + const workspaceLifecycle=new WorkspaceLifecycleWorker(service.control);if(process.env.WF_DISPATCH_ENABLED!=='false')workspaceLifecycle.start(); + const dispatcher = new Dispatcher(service.control); if (process.env.WF_DISPATCH_ENABLED !== 'false') void dispatcher.start(); + const resourceReconciliation = new ResourceReconciliationWorker(service.control); if (process.env.WF_DISPATCH_ENABLED !== 'false') resourceReconciliation.start(); + const shutdown = async () => { await resourceReconciliation.close(); await workspaceLifecycle.close(); await dispatcher.close(); await app.close(); await store.close(); await telemetry.close(); }; + process.once('SIGTERM', () => void shutdown()); process.once('SIGINT', () => void shutdown()); + return { app, service, shutdown }; +} +await bootstrap(); diff --git a/apps/api/src/mcp.ts b/apps/api/src/mcp.ts new file mode 100644 index 0000000..2c2f119 --- /dev/null +++ b/apps/api/src/mcp.ts @@ -0,0 +1,24 @@ +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { z } from 'zod'; +import type { Request, Response } from 'express'; +import { DomainError, wishInput, releaseInput } from '@wishforge/contracts'; +import type { Services } from './http.js'; + +export async function handleMcp(s: Services, req: Request, res: Response) { + const authenticated = await s.auth.authenticate(req.header('Authorization')); + const actor = { ...authenticated, kind: 'connector' as const }; + const server = new McpServer({ name: 'wishforge', version: '0.1.0' }, { instructions: 'Submit a wish with explicit acceptance criteria and reuse its idempotency_key when retrying. Tasks continue after this call returns. Use run_id to inspect status and answer questions. Agent completion is not verified delivery. Human release approvals must be completed at the returned web URL.' }); + const result = async (fn: () => Promise) => { try { const data = await fn(); return { content: [{ type: 'text' as const, text: JSON.stringify({ data }) }] }; } catch (error) { return { isError: true, content: [{ type: 'text' as const, text: JSON.stringify({ error: { code: error instanceof DomainError ? error.code : 'TOOL_ERROR', message: error instanceof Error ? error.message : 'Tool failed' } }) }] }; } }; + server.registerTool('submit_wish', { description: 'Submit a versioned wish; returns quickly with wish_id and run_id.', inputSchema: { project_id: z.string(), idempotency_key: z.string().min(8), ...wishInput.shape } }, ({ project_id, idempotency_key, ...input }) => result(() => s.control.submit(actor, project_id, input, idempotency_key))); + server.registerTool('get_run', { description: 'Read task stage, status and waiting reason.', inputSchema: { run_id: z.string() } }, ({ run_id }) => result(() => s.control.run(actor, run_id))); + server.registerTool('get_run_events', { description: 'Read persisted progress events after a cursor.', inputSchema: { run_id: z.string(), cursor: z.number().int().nonnegative().default(0) } }, ({ run_id, cursor }) => result(() => s.control.events(actor, run_id, cursor))); + server.registerTool('answer_question', { description: 'Add a requirement revision; invalidates obsolete verification and approval.', inputSchema: { run_id: z.string(), answer: z.string().min(1), idempotency_key: z.string().min(8) } }, ({ run_id, answer, idempotency_key }) => result(() => s.control.command(actor, run_id, { action: 'answer', message: answer }, idempotency_key))); + server.registerTool('control_run', { description: 'Pause, resume or cancel future execution. Cancel does not roll back a healthy live release.', inputSchema: { run_id: z.string(), action: z.enum(['pause', 'resume', 'cancel']), idempotency_key: z.string().min(8) } }, ({ run_id, action, idempotency_key }) => result(() => s.control.command(actor, run_id, { action }, idempotency_key))); + server.registerTool('get_delivery', { description: 'Read verified release and evidence, if available.', inputSchema: { run_id: z.string() } }, ({ run_id }) => result(async () => { return {run_id,...await s.releases.delivery(actor,run_id)}; })); + server.registerTool('request_release', { description: 'Request publication of trusted build evidence. High-risk publication requires an interactive human approval.', inputSchema: { ...releaseInput.shape, idempotency_key: z.string().min(8) } }, ({ idempotency_key, ...input }) => result(async () => { const release = await s.releases.request(actor, input, idempotency_key); return { release, approval_url: release.approvalId ? `${s.control.env.WF_PUBLIC_URL}/releases` : null }; })); + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); + await server.connect(transport); + res.on('close', () => { void transport.close(); void server.close(); }); + await transport.handleRequest(req, res, req.body); +} diff --git a/apps/api/src/preview-http.ts b/apps/api/src/preview-http.ts new file mode 100644 index 0000000..b428191 --- /dev/null +++ b/apps/api/src/preview-http.ts @@ -0,0 +1,23 @@ +import {Body,Controller,Inject,Param,Post,Req} from '@nestjs/common'; +import type {Request} from 'express'; +import type {Actor} from '@wishforge/contracts'; +import {z} from 'zod'; +import {Services} from './http.js'; +import {Previews} from './domain/previews.js'; +type AuthRequest=Request&{actor:Actor}; +@Controller('v1/environments') +export class PreviewController{ + constructor(@Inject(Services)private s:Services){} + @Post(':id/preview-launch')async launch(@Req()req:AuthRequest,@Param('id')id:string){return{data:await new Previews(this.s.control.store,this.s.control.env).launch(req.actor,id)};} +} +/** This path has its own environment-scoped service authentication, not OIDC or worker auth. */ +@Controller('preview-control') +export class PreviewControlController{ + constructor(@Inject(Services)private s:Services){} + @Post('authorize')async authorize(@Req()req:Request,@Body()body:unknown){return{data:await new Previews(this.s.control.store,this.s.control.env).authorize(req.header('Authorization'),body)};} +} +@Controller('internal/runner/releases') +export class PreviewProbeController{ + constructor(@Inject(Services)private s:Services){} + @Post(':id/preview-probe')async probe(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){const input=z.object({taskId:z.string().regex(/^[A-Za-z0-9_-]{1,128}$/)}).strict().parse(body);return{data:await new Previews(this.s.control.store,this.s.control.env).issueProbeForRunner(req.actor,id,input.taskId)};} +} diff --git a/apps/api/src/resource-reconciliation-worker.ts b/apps/api/src/resource-reconciliation-worker.ts new file mode 100644 index 0000000..6b30e43 --- /dev/null +++ b/apps/api/src/resource-reconciliation-worker.ts @@ -0,0 +1,25 @@ +import type { ControlPlane } from './domain/control-plane.js'; +import { releaseStoppedAllocations } from './domain/resource-dispatch.js'; + +/** Resource cleanup must continue while Temporal is unavailable. */ +export class ResourceReconciliationWorker { + private stopped = false; + private timer?: ReturnType; + private busy?: Promise; + constructor(private control: ControlPlane) {} + start() { + const tick = async () => { + if (this.stopped) return; + this.busy = this.tick(); await this.busy; + if (!this.stopped) this.timer = setTimeout(() => void tick(), 10000); + }; + void tick(); + } + async tick() { + for (const tenant of (this.control.env.WF_DISPATCH_TENANTS ?? '').split(',').map(value => value.trim()).filter(Boolean)) { + try { await releaseStoppedAllocations(this.control, tenant); } + catch { /* Keep the durable reservation on any missing or unknown result. */ } + } + } + async close() { this.stopped = true; if (this.timer) clearTimeout(this.timer); await this.busy; } +} diff --git a/apps/api/src/service-tokens.ts b/apps/api/src/service-tokens.ts new file mode 100644 index 0000000..42aeb9e --- /dev/null +++ b/apps/api/src/service-tokens.ts @@ -0,0 +1,11 @@ +import { SignJWT, jwtVerify } from 'jose'; +import { DomainError, type Actor } from '@wishforge/contracts'; +export class ServiceTokens { + constructor(private secret: string | undefined) {} + private key() { if (!this.secret || this.secret.length < 32) throw new DomainError('INTERNAL_SIGNER_UNCONFIGURED', 'Configure the internal token signing secret', 503); return new TextEncoder().encode(this.secret); } + async issue(tenantId: string, runId: string, kind: 'worker' | 'verifier', generation: string) { return new SignJWT({ tenant_id: tenantId, run_id: runId, kind, generation }).setProtectedHeader({ alg: 'HS256' }).setIssuer('wishforge-control-plane').setAudience('wishforge-internal').setSubject(`${kind}:${runId}:${generation}`).setIssuedAt().setExpirationTime('4h').sign(this.key()); } + async verify(token: string): Promise { + if (!token.startsWith('eyJ') || !this.secret) return undefined; + try { const { payload } = await jwtVerify(token, this.key(), { issuer: 'wishforge-control-plane', audience: 'wishforge-internal', algorithms: ['HS256'] }); if (!payload.sub || typeof payload.tenant_id !== 'string' || typeof payload.run_id !== 'string' || typeof payload.generation !== 'string' || !['worker', 'verifier'].includes(String(payload.kind))) return undefined; return { userId: payload.sub, tenantId: payload.tenant_id, runId: payload.run_id, credentialId: payload.generation, kind: payload.kind as 'worker' | 'verifier', role: 'admin' }; } catch { return undefined; } + } +} diff --git a/apps/api/src/telemetry.ts b/apps/api/src/telemetry.ts new file mode 100644 index 0000000..64981a7 --- /dev/null +++ b/apps/api/src/telemetry.ts @@ -0,0 +1,47 @@ +import { context, propagation, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api'; +import { Registry, Counter, Histogram, collectDefaultMetrics } from '@prometheus-io/client'; +import type { Request, Response, NextFunction } from 'express'; +import { sameSecret } from './domain/policy.js'; + +/** Low-cardinality metrics and redacted request spans; no bodies, tokens or URL query strings. */ +export async function observability(env = process.env) { + let stopTracing: (() => Promise) | undefined; + if (env.OTEL_EXPORTER_OTLP_ENDPOINT) { + const endpoint = new URL(env.OTEL_EXPORTER_OTLP_ENDPOINT); + if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.username || endpoint.password) throw new Error('Invalid OTLP collector URL'); + const [{ NodeSDK }, { OTLPTraceExporter }] = await Promise.all([import('@opentelemetry/sdk-node'), import('@opentelemetry/exporter-trace-otlp-http')]); + const sdk = new NodeSDK({ serviceName: 'wishforge-control-plane', traceExporter: new OTLPTraceExporter({ url: new URL('/v1/traces', endpoint).toString() }) }); + sdk.start(); stopTracing = () => sdk.shutdown(); + } + const registry = new Registry(); + collectDefaultMetrics({ register: registry, prefix: 'wishforge_' }); + const requests = new Counter({ name: 'wishforge_http_requests_total', help: 'Completed HTTP requests', labelNames: ['method', 'route', 'status'] as const, registers: [registry] }); + const duration = new Histogram({ name: 'wishforge_http_request_duration_seconds', help: 'HTTP handler duration', labelNames: ['method', 'route'] as const, buckets: [.01, .05, .1, .25, .5, 1, 2, 5, 15], registers: [registry] }); + return { + middleware(req: Request, res: Response, next: NextFunction) { + if (req.path === '/metrics') return next(); + const started = process.hrtime.bigint(); + const parent = propagation.extract(context.active(), req.headers); + const span = trace.getTracer('wishforge-http').startSpan('HTTP request', { kind: SpanKind.SERVER, attributes: { 'http.request.method': req.method } }, parent); + let finished = false; + const finish = () => { + if (finished) return; finished = true; + const method = ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'].includes(req.method) ? req.method : 'OTHER'; + const route = typeof req.route?.path === 'string' ? req.route.path : 'unmatched'; + const status = res.statusCode; + requests.inc({ method, route, status: String(status) }); duration.observe({ method, route }, Number(process.hrtime.bigint() - started) / 1e9); + span.updateName(`${method} ${route}`); span.setAttribute('http.route', route); span.setAttribute('http.response.status_code', status); + if (status >= 500) span.setStatus({ code: SpanStatusCode.ERROR }); span.end(); + }; + res.once('finish', finish); res.once('close', finish); + context.with(trace.setSpan(parent, span), next); + }, + async metrics(req: Request, res: Response) { + if (!env.WF_METRICS_TOKEN) { res.status(404).end(); return; } + const value = req.header('Authorization')?.replace(/^Bearer /, '') ?? ''; + if (!sameSecret(value, env.WF_METRICS_TOKEN)) { res.status(401).end(); return; } + res.type(registry.contentType).setHeader('Cache-Control', 'no-store'); res.send(await registry.metrics()); + }, + async close() { registry.clear(); await stopTracing?.(); }, + }; +} diff --git a/apps/api/src/workspace-integration-http.ts b/apps/api/src/workspace-integration-http.ts new file mode 100644 index 0000000..0e34545 --- /dev/null +++ b/apps/api/src/workspace-integration-http.ts @@ -0,0 +1,30 @@ +import { Body, Controller, Get, Inject, Param, Post, Req } from '@nestjs/common'; +import type { Request } from 'express'; +import { z } from 'zod'; +import { DomainError, type Actor, type Run } from '@wishforge/contracts'; +import { Services } from './http.js'; +import { must } from './domain/control-plane.js'; +type AuthRequest=Request&{actor:Actor}; +const lease=z.object({leaseToken:z.number().int().positive()}).strict(); +const fenced=z.object({leaseToken:z.number().int().positive(),fence:z.number().int().positive()}).strict(); +@Controller('v1') +export class WorkspaceInputController { + constructor(@Inject(Services)private s:Services){} + @Get('runs/:id/workspace-input')async inspect(@Req()req:AuthRequest,@Param('id')id:string){return{data:await this.s.control.workspaceIntegration.inspect(req.actor,id)};} + @Post('runs/:id/workspaces/:workspaceId/import-snapshot')async import(@Req()req:AuthRequest,@Param('id')id:string,@Param('workspaceId')workspaceId:string,@Body()body:unknown){const input=z.object({sourceCommit:z.string().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/),confirmation:z.literal('saved-workspace-committed')}).strict().parse(body);return{data:await this.s.control.workspaceIntegration.importSnapshot(req.actor,id,workspaceId,input.sourceCommit,req.header('Authorization')??'')};} +} +@Controller('internal') +export class WorkspaceIntegrationController { + constructor(@Inject(Services)private s:Services){} + @Get('runs/:id/workspace-input')async inspect(@Req()req:AuthRequest,@Param('id')id:string){return{data:await this.s.control.workspaceIntegration.inspect(req.actor,id)};} + @Post('runs/:id/workspace-input/match')async match(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){const input=z.object({leaseToken:z.number().int().positive(),targetCommit:z.string(),snapshots:z.array(z.object({workspaceId:z.string(),sourceCommit:z.string(),snapshotRevision:z.number().int().positive(),snapshotDigest:z.string().regex(/^[a-f0-9]{64}$/)}).strict()).max(20)}).strict().parse(body);return{data:await this.s.control.workspaceIntegration.recordMatch(req.actor,id,input)};} + @Post('runs/:id/workspace-input/check')async check(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){await this.s.control.workspaceIntegration.enforce(req.actor,id,lease.parse(body).leaseToken);return{data:{allowed:true}};} + @Post('runs/:id/integration-lease/acquire')async acquire(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){return{data:await this.s.control.workspaceIntegration.acquire(req.actor,id,lease.parse(body).leaseToken)};} + @Post('runs/:id/integration-lease/renew')async renew(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){const data=fenced.parse(body);return{data:await this.s.control.workspaceIntegration.renew(req.actor,id,data.leaseToken,data.fence)};} + @Post('runs/:id/integration-lease/release')async release(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){const data=fenced.parse(body);return{data:await this.s.control.workspaceIntegration.release(req.actor,id,data.leaseToken,data.fence)};} + @Post('workspaces/:id/integration-authorize')async authorize(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){ + if(req.actor.userId!=='workspace-gateway')throw new DomainError('FORBIDDEN','Workspace gateway identity required',403); + const input=z.object({runId:z.string(),revision:z.number().int().positive(),generation:z.string().optional()}).strict().parse(body); + return{data:await this.s.control.store.transaction(req.actor.tenantId,async tx=>{const workspace=await must(tx,'workspace',id),run=await must(tx,'run',input.runId);if(workspace.projectId!==run.projectId||workspace.status!=='ready'||!workspace.upstreamUrl||run.revision!==input.revision||run.executionGeneration!==input.generation||run.status!=='running'||!run.lease||Date.parse(run.lease.expiresAt)<=Date.now())throw new DomainError('WORKSPACE_INPUT_UNAVAILABLE','Workspace is not a live integration input',409);return{tenantId:req.actor.tenantId,workspaceId:id,projectId:run.projectId,upstreamUrl:workspace.upstreamUrl,userId:`integration:${run.id}`,role:'admin',purpose:'integration-state'};})}; + } +} diff --git a/apps/api/src/workspace-launch-http.ts b/apps/api/src/workspace-launch-http.ts new file mode 100644 index 0000000..866c4ba --- /dev/null +++ b/apps/api/src/workspace-launch-http.ts @@ -0,0 +1,3 @@ +import {Body,Controller,Inject,Param,Post,Req} from '@nestjs/common';import type {Request} from 'express';import {z} from 'zod';import type {Actor} from '@wishforge/contracts';import {Services} from './http.js';import {WorkspaceLaunch} from './domain/workspace-launch.js'; +@Controller('v1/workspaces') +export class WorkspaceLaunchController{constructor(@Inject(Services)private s:Services){}@Post(':id/launch')async launch(@Req()req:Request&{actor:Actor},@Param('id')id:string,@Body()body:unknown){z.object({}).strict().parse(body);return{data:await new WorkspaceLaunch(this.s.control.store,this.s.control.env).launch(req.actor,id,req.header('Authorization')??'')};}} diff --git a/apps/api/src/workspace-lifecycle-http.ts b/apps/api/src/workspace-lifecycle-http.ts new file mode 100644 index 0000000..766a4b0 --- /dev/null +++ b/apps/api/src/workspace-lifecycle-http.ts @@ -0,0 +1,18 @@ +import {Body,Controller,Inject,Param,Post,Req} from '@nestjs/common'; +import {z} from 'zod'; +import type {Request} from 'express'; +import {DomainError,type Actor} from '@wishforge/contracts'; +import {Services} from './http.js'; +import {must} from './domain/control-plane.js'; +import {WorkspaceLifecycle} from './domain/workspace-lifecycle.js'; +type AuthRequest=Request&{actor:Actor}; +@Controller('v1/workspaces') +export class WorkspaceLifecycleController{ + constructor(@Inject(Services)private s:Services){} + @Post(':id/lifecycle')async control(@Req()req:AuthRequest,@Param('id')id:string,@Body()body:unknown){const input=z.object({action:z.enum(['pause','resume']),confirmation:z.literal('change-workspace-lifecycle')}).strict().parse(body);return{data:await new WorkspaceLifecycle(this.s.control.store,this.s.control.env).manual(req.actor,id,input.action,req.header('Idempotency-Key')??'',req.header('Authorization')??'')};} +} +@Controller('internal/workspaces') +export class WorkspaceLifecycleInternalController{ + constructor(@Inject(Services)private s:Services){} + @Post(':id/lifecycle-authorize')async authorize(@Req()req:AuthRequest,@Param('id')id:string){if(req.actor.userId!=='workspace-gateway')throw new DomainError('FORBIDDEN','Workspace gateway identity required',403);return{data:await this.s.control.store.transaction(req.actor.tenantId,async tx=>{const w=await must(tx,'workspace',id);if(!['ready','pausing','unknown'].includes(String(w.status))||!w.upstreamUrl||w.managedBy!=='wishforge-provisioner')throw new DomainError('WORKSPACE_NOT_READY','Workspace activity cannot be established',503);return{tenantId:req.actor.tenantId,workspaceId:id,projectId:w.projectId,upstreamUrl:w.upstreamUrl,userId:'lifecycle-inspector',role:'admin',purpose:'workspace-lifecycle'};})};} +} diff --git a/apps/api/src/workspace-lifecycle-worker.ts b/apps/api/src/workspace-lifecycle-worker.ts new file mode 100644 index 0000000..63bdfb3 --- /dev/null +++ b/apps/api/src/workspace-lifecycle-worker.ts @@ -0,0 +1,10 @@ +import type {ControlPlane} from './domain/control-plane.js'; +import {WorkspaceLifecycle} from './domain/workspace-lifecycle.js'; +/** Independent of Temporal availability; durable outbox reconciliation owns no application deployment. */ +export class WorkspaceLifecycleWorker{ + private timer?:ReturnType;private stopped=false;private busy?:Promise; + constructor(private control:ControlPlane){} + start(){const tick=async()=>{if(this.stopped)return;this.busy=this.tick();await this.busy;if(!this.stopped)this.timer=setTimeout(()=>void tick(),10000);};void tick();} + private async tick(){const lifecycle=new WorkspaceLifecycle(this.control.store,this.control.env);for(const tenant of(this.control.env.WF_DISPATCH_TENANTS??'').split(',').filter(Boolean)){try{const pending=await this.control.store.transaction(tenant,tx=>tx.outbox());for(const item of pending.filter(x=>x.type==='workspace.reconcile'))await lifecycle.reconcile(tenant,item);await lifecycle.scheduleIdle(tenant);}catch{/* Durable items remain pending; never infer ready/suspended from a transport failure. */}}} + async close(){this.stopped=true;if(this.timer)clearTimeout(this.timer);await this.busy;} +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..3be161e --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1 @@ +{"extends":"../../tsconfig.base.json","include":["src/**/*.ts"]} diff --git a/apps/git-service/package.json b/apps/git-service/package.json new file mode 100644 index 0000000..efe65f8 --- /dev/null +++ b/apps/git-service/package.json @@ -0,0 +1 @@ +{ "name": "@wishforge/git-service", "version": "0.1.0", "private": true, "type": "module", "scripts": { "dev": "tsx src/main.ts", "typecheck": "tsc --noEmit" }, "dependencies": { "@wishforge/runtime": "*" } } diff --git a/apps/git-service/src/main.ts b/apps/git-service/src/main.ts new file mode 100644 index 0000000..026b72f --- /dev/null +++ b/apps/git-service/src/main.ts @@ -0,0 +1,10 @@ +import { createGitService } from './service.js'; +async function main(){ + for(const key of ['WF_GIT_ROOT','WF_GIT_PUBLIC_BASE_URL','WF_GIT_ADMIN_TOKEN','WF_GIT_TOKEN_SECRET'])if(!process.env[key])throw new Error(`unconfigured: ${key} is required`); + const server=await createGitService({root:process.env.WF_GIT_ROOT!,publicBaseUrl:process.env.WF_GIT_PUBLIC_BASE_URL!,adminToken:process.env.WF_GIT_ADMIN_TOKEN!,tokenSecret:process.env.WF_GIT_TOKEN_SECRET!,allowLocalHttp:process.env.WF_GIT_ALLOW_LOCAL_HTTP==='true'}); + const port = Number(process.env.WF_GIT_PORT ?? 4504); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('WF_GIT_PORT must be a valid port'); + server.listen(port,process.env.WF_GIT_HOST ?? '127.0.0.1',()=>console.log(`Git storage listening on port ${port}`)); + process.once('SIGTERM',()=>server.close()); +} +void main().catch(error=>{console.error(error.message);process.exitCode=1;}); diff --git a/apps/git-service/src/service.ts b/apps/git-service/src/service.ts new file mode 100644 index 0000000..eb8d964 --- /dev/null +++ b/apps/git-service/src/service.ts @@ -0,0 +1,114 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; +import { spawn } from 'node:child_process'; +import { mkdir, open, realpath, stat, unlink } from 'node:fs/promises'; +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import path from 'node:path'; +import { checkedCommand, RuntimeError, safeIdentifier, requireBranchName } from '@wishforge/runtime'; + +export interface GitServiceConfig { root: string; publicBaseUrl: string; adminToken: string; tokenSecret: string; allowLocalHttp?: boolean; maxPackBytes?: number; } +export interface GitClaims { aud: 'wishforge-git'; tenantId: string; projectId: string; permission: 'read' | 'write'; iat: number; exp: number; runId?: string; } +function sameSecret(a: string, b: string) { const x=Buffer.from(a),y=Buffer.from(b); return x.length===y.length && timingSafeEqual(x,y); } +export function issueGitToken(claims: GitClaims, secret: string): string { + const payload=Buffer.from(JSON.stringify(claims)).toString('base64url'); + return `${payload}.${createHmac('sha256',secret).update(payload).digest('base64url')}`; +} +export function verifyGitToken(token: string, secret: string, scope: { tenantId: string; projectId: string; write: boolean }, now = Math.floor(Date.now()/1000)): GitClaims { + const [payload,signature,...extra]=token.split('.'); + if(!payload || !signature || extra.length || !sameSecret(signature,createHmac('sha256',secret).update(payload).digest('base64url'))) throw new RuntimeError('UNAUTHORIZED','Invalid Git token'); + let claims: GitClaims; + try { claims=JSON.parse(Buffer.from(payload,'base64url').toString()) as GitClaims; } + catch { throw new RuntimeError('UNAUTHORIZED','Invalid Git token payload'); } + if(claims.aud!=='wishforge-git' || claims.tenantId!==scope.tenantId || claims.projectId!==scope.projectId || (scope.write && claims.permission!=='write') || !['read','write'].includes(claims.permission) || !Number.isInteger(claims.exp) || !Number.isInteger(claims.iat) || claims.exp<=now || claims.iat>now+30 || claims.exp-claims.iat>900) throw new RuntimeError('UNAUTHORIZED','Git token expired or does not authorize this repository/operation'); + return claims; +} +async function jsonBody(request: IncomingMessage):Promise> { + const chunks:Buffer[]=[];let bytes=0; + for await(const chunk of request) { bytes+=Buffer.byteLength(chunk); if(bytes>64*1024) throw new RuntimeError('PAYLOAD_TOO_LARGE','Admin request exceeds limit');chunks.push(Buffer.from(chunk)); } + return JSON.parse(Buffer.concat(chunks).toString() || '{}') as Record; +} +function json(response:ServerResponse,status:number,body:unknown) { response.writeHead(status,{'content-type':'application/json','cache-control':'no-store'});response.end(JSON.stringify(body)); } + +export async function createGitService(config:GitServiceConfig) { + if(config.adminToken.length<24 || config.tokenSecret.length<32) throw new RuntimeError('UNCONFIGURED','Strong Git admin and token-signing secrets are required'); + const publicBase=new URL(config.publicBaseUrl); + if (publicBase.username || publicBase.password || publicBase.search || publicBase.hash || publicBase.pathname !== '/') throw new RuntimeError('INVALID_ENDPOINT','Public Git URL must be an origin without credentials'); + if(publicBase.protocol!=='https:' && !(process.env.NODE_ENV!=='production' && config.allowLocalHttp && publicBase.protocol==='http:' && ['127.0.0.1','localhost','[::1]'].includes(publicBase.hostname))) throw new RuntimeError('INSECURE_ENDPOINT','Public Git URL must be HTTPS (explicit loopback HTTP is development-only)'); + await mkdir(config.root,{recursive:true,mode:0o700});const root=await realpath(config.root); + const gitEnv={PATH:process.env.PATH,LANG:'C.UTF-8',GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_NOSYSTEM:'1',GIT_AUTHOR_NAME:'WishForge',GIT_AUTHOR_EMAIL:'platform@wishforge.invalid',GIT_COMMITTER_NAME:'WishForge',GIT_COMMITTER_EMAIL:'platform@wishforge.invalid'}; + const git=(cwd:string,args:string[],input?:string)=>checkedCommand({executable:'git',args:['-c','core.hooksPath=/dev/null',...args],cwd,input,env:gitEnv}); + const location=async(tenantId:string,projectId:string)=> { + safeIdentifier(tenantId);safeIdentifier(projectId); + const parent=path.join(root,tenantId);await mkdir(parent,{recursive:true,mode:0o700}); + if(!(await realpath(parent)).startsWith(`${root}${path.sep}`)) throw new RuntimeError('REPOSITORY_SCOPE','Repository parent escaped the storage root'); + const repository = path.join(parent,`${projectId}.git`); + const resolved = await realpath(repository).catch(error => { if (error.code === 'ENOENT') return repository; throw error; }); + if (resolved !== repository) throw new RuntimeError('REPOSITORY_SCOPE','Repository links are not permitted'); + return repository; + }; + const server=createServer((request,response)=>{void(async()=>{ + const url=new URL(request.url ?? '/',publicBase); + if(url.pathname==='/health' && request.method==='GET') { json(response,200,{status:'ok',service:'git-storage'});return; } + if(['/repos','/tokens'].includes(url.pathname) && request.method==='POST') { + const auth=request.headers.authorization ?? ''; + if(!auth.startsWith('Bearer ') || !sameSecret(auth.slice(7),config.adminToken)) {json(response,401,{error:'UNAUTHORIZED'});return;} + const body=await jsonBody(request);const tenantId=String(body.tenantId ?? ''),projectId=String(body.projectId ?? ''); + const repository=await location(tenantId,projectId); + if(url.pathname==='/repos') { + if(body.defaultBranch!==undefined && typeof body.defaultBranch!=='string') throw new RuntimeError('INVALID_REF','defaultBranch must be a safe Git branch name'); + const requestedBranch=requireBranchName(body.defaultBranch as string | undefined ?? 'main'); + const lockPath=`${repository}.provision.lock`; + const lock=await open(lockPath,'wx',0o600).catch(()=>{throw new RuntimeError('REPOSITORY_BUSY','Repository provisioning is already in progress');}); + try { + if(!await stat(repository).then(()=>true,error=>{if(error.code==='ENOENT')return false;throw error;})) { + await git(path.dirname(repository),['init','--bare',`--initial-branch=${requestedBranch}`,repository]); + const tree=await git(repository,['hash-object','-t','tree','--stdin'],''); + const commit=await git(repository,['commit-tree',tree,'-m','Initialize WishForge project']); + await git(repository,['update-ref',`refs/heads/${requestedBranch}`,commit]); + await git(repository,['config','http.receivepack','true']); + await git(repository,['config','receive.denyNonFastForwards','true']); + await git(repository,['config','receive.denyDeletes','true']); + } + const headRef=await git(repository,['symbolic-ref','--quiet','HEAD']); + if(!headRef.startsWith('refs/heads/'))throw new RuntimeError('REPOSITORY_DEFAULT_BRANCH_UNAVAILABLE','Repository HEAD is not a branch; existing state was not changed'); + const defaultBranch=requireBranchName(headRef.slice('refs/heads/'.length)); + const initialCommit=await git(repository,['rev-parse','--verify',`${headRef}^{commit}`]); + json(response,200,{repositoryUrl:new URL(`/git/${tenantId}/${projectId}.git`,publicBase).href,initialCommit,defaultBranch}); + } finally {await lock.close();await unlink(lockPath);} + } else { + await stat(repository); + if(body.permission!=='read' && body.permission!=='write') throw new RuntimeError('INVALID_PERMISSION','Git permission must be read or write'); + const ttl=Number(body.ttlSeconds ?? 300);if(!Number.isInteger(ttl)||ttl<30||ttl>900)throw new RuntimeError('INVALID_TTL','Token TTL must be 30..900 seconds'); + const issued=Math.floor(Date.now()/1000);const claims:GitClaims={aud:'wishforge-git',tenantId,projectId,permission:body.permission,iat:issued,exp:issued+ttl,...(typeof body.runId==='string'?{runId:safeIdentifier(body.runId)}:{})}; + json(response,200,{token:issueGitToken(claims,config.tokenSecret),expiresAt:new Date(claims.exp*1000).toISOString()}); + } + return; + } + const match=/^\/git\/([A-Za-z0-9][A-Za-z0-9_-]{0,100})\/([A-Za-z0-9][A-Za-z0-9_-]{0,100})\.git\/(info\/refs|git-upload-pack|git-receive-pack)$/.exec(url.pathname); + if(!match) {json(response,404,{error:'NOT_FOUND'});return;} + const tenantId=match[1]!,projectId=match[2]!,operation=match[3]!; + const service=operation==='info/refs'?url.searchParams.get('service'):operation; + if(!['git-upload-pack','git-receive-pack'].includes(service ?? '') || (operation==='info/refs'?request.method!=='GET':request.method!=='POST')) {json(response,400,{error:'INVALID_GIT_OPERATION'});return;} + const authorization=request.headers.authorization ?? ''; + if(!authorization.startsWith('Bearer ')) {response.setHeader('www-authenticate','Bearer realm="wishforge-git"');json(response,401,{error:'UNAUTHORIZED'});return;} + const claims=verifyGitToken(authorization.slice(7),config.tokenSecret,{tenantId,projectId,write:service==='git-receive-pack'}); + const repository=await location(tenantId,projectId);await stat(repository); + const child=spawn('git',['http-backend'],{env:{...gitEnv,GIT_PROJECT_ROOT:root,GIT_HTTP_EXPORT_ALL:'1',PATH_INFO:`/${tenantId}/${projectId}.git/${operation}`,REQUEST_METHOD:request.method!,QUERY_STRING:url.searchParams.toString(),CONTENT_TYPE:String(request.headers['content-type'] ?? ''),CONTENT_LENGTH:String(request.headers['content-length'] ?? ''),REMOTE_USER:claims.runId ?? 'wishforge',REMOTE_ADDR:request.socket.remoteAddress ?? '',HTTP_GIT_PROTOCOL:String(request.headers['git-protocol'] ?? '')},stdio:['pipe','pipe','pipe'],shell:false}); + let headers=Buffer.alloc(0),headersSent=false,bytes=0; + const timer=setTimeout(()=>child.kill('SIGKILL'),300_000); + request.on('data',chunk=>{bytes+=chunk.length;if(bytes>(config.maxPackBytes ?? 512*1024*1024)){child.kill('SIGKILL');request.destroy();}}); + request.on('aborted',()=>child.kill('SIGKILL'));response.on('close',()=>{if(!response.writableEnded)child.kill('SIGKILL');}); + child.stdout.on('data',(chunk:Buffer)=>{ + if(headersSent){response.write(chunk);return;} + headers=Buffer.concat([headers,chunk]);const end=headers.indexOf('\r\n\r\n'); + if(end===-1){if(headers.length>64*1024)child.kill('SIGKILL');return;} + let status=200;const parsed:Record={}; + for(const line of headers.subarray(0,end).toString().split('\r\n')){const separator=line.indexOf(':');if(separator<1)continue;const name=line.slice(0,separator).toLowerCase(),value=line.slice(separator+1).trim();if(name==='status')status=parseInt(value,10);else if(['content-type','cache-control','expires','pragma','content-encoding'].includes(name))parsed[name]=value;} + response.writeHead(status,parsed);headersSent=true;response.write(headers.subarray(end+4));headers=Buffer.alloc(0); + }); + child.stderr.on('data',()=>undefined);child.stdin.on('error',()=>undefined); + child.on('error',()=>{clearTimeout(timer);if(!headersSent)json(response,503,{error:'GIT_BACKEND_UNAVAILABLE'});else response.destroy();}); + child.on('close',code=>{clearTimeout(timer);if(!headersSent)json(response,code===0?502:503,{error:'GIT_BACKEND_FAILED'});else response.end();}); + request.pipe(child.stdin); + })().catch(error=>{if(response.headersSent){response.destroy();return;}const code=error instanceof RuntimeError?error.code:'GIT_SERVICE_ERROR';json(response,code==='UNAUTHORIZED'?401:code==='REPOSITORY_BUSY'?409:400,{error:code});});}); + return server; +} diff --git a/apps/git-service/test/service.test.ts b/apps/git-service/test/service.test.ts new file mode 100644 index 0000000..517a8ae --- /dev/null +++ b/apps/git-service/test/service.test.ts @@ -0,0 +1,50 @@ +import { it, expect, vi } from 'vitest'; +import { mkdtemp, rm, writeFile, symlink, mkdir } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { GitWorkspace } from '@wishforge/runtime'; +import { createGitService, issueGitToken, verifyGitToken } from '../src/service.js'; + +it('refuses the development HTTP override in production before creating storage',async()=>{vi.stubEnv('NODE_ENV','production');try{await expect(createGitService({root:'/unused-production-fixture',publicBaseUrl:'http://127.0.0.1:4504',adminToken:'admin-'.repeat(8),tokenSecret:'signing-'.repeat(8),allowLocalHttp:true})).rejects.toMatchObject({code:'INSECURE_ENDPOINT'});}finally{vi.unstubAllEnvs();}}); + +it('enforces repository, permission and expiry scope on short-lived Git tokens',()=>{ + const secret='s'.repeat(32);const token=issueGitToken({aud:'wishforge-git',tenantId:'tenant',projectId:'project',permission:'read',iat:100,exp:400},secret); + expect(verifyGitToken(token,secret,{tenantId:'tenant',projectId:'project',write:false},200).permission).toBe('read'); + expect(()=>verifyGitToken(token,secret,{tenantId:'other',projectId:'project',write:false},200)).toThrow(); + expect(()=>verifyGitToken(token,secret,{tenantId:'tenant',projectId:'project',write:true},200)).toThrow(); + expect(()=>verifyGitToken(token,secret,{tenantId:'tenant',projectId:'project',write:false},500)).toThrow(); +}); + +it('provisions a real bare repository and serves authenticated clone/CAS push over smart HTTP',async()=>{ + const root=await mkdtemp(path.join(os.tmpdir(),'wishforge-git-service-')); + const admin='admin-'.repeat(8);const server=await createGitService({root:path.join(root,'repos'),publicBaseUrl:'http://127.0.0.1:4504',adminToken:admin,tokenSecret:'signing-'.repeat(8),allowLocalHttp:true}); + await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);}); + const address=server.address();if(!address || typeof address==='string')throw new Error('no port'); + const base=`http://127.0.0.1:${address.port}`; + const post=async(route:string,body:unknown)=>{const response=await fetch(`${base}${route}`,{method:'POST',headers:{authorization:`Bearer ${admin}`,'content-type':'application/json'},body:JSON.stringify(body)});expect(response.status).toBe(200);return response.json() as Promise>;}; + try{ + const repo=await post('/repos',{tenantId:'tenant',projectId:'project',defaultBranch:'release/v1'});expect(repo.initialCommit).toMatch(/^[a-f0-9]{40}$/);expect(repo.defaultBranch).toBe('release/v1'); + const repeated=await post('/repos',{tenantId:'tenant',projectId:'project',defaultBranch:'main'});expect(repeated.defaultBranch).toBe('release/v1');expect(repeated.initialCommit).toBe(repo.initialCommit); + expect((await post('/repos',{tenantId:'tenant',projectId:'default-main'})).defaultBranch).toBe('main'); + const repositoryUrl=`${base}/git/tenant/project.git`; + const reader=await post('/tokens',{tenantId:'tenant',projectId:'project',permission:'read'}); + const writer=await post('/tokens',{tenantId:'tenant',projectId:'project',permission:'write'}); + const git=new GitWorkspace(undefined,{allowLocalHttp:true,credential:{token:reader.token!,repositoryUrl}}); + const checkout=await git.create({root:path.join(root,'clones'),runId:'run',repository:repositoryUrl,targetBranch:'release/v1'}); + await writeFile(path.join(checkout.workspace,'README.md'),'A persistent project\n'); + const checkpoint=await git.checkpoint(checkout.workspace,checkout.baseCommit,'run','test'); + const push={repository:checkout.workspace,targetRef:'refs/heads/release/v1',expectedTargetCommit:checkout.baseCommit,candidateCommit:checkpoint.sourceCommit,verifiedCommit:checkpoint.sourceCommit}; + await expect(git.pushVerifiedCandidate(push)).rejects.toThrow(); + git.setCredential({token:writer.token!,repositoryUrl});await git.pushVerifiedCandidate(push); + const second=await git.create({root:path.join(root,'clones'),runId:'second',repository:repositoryUrl,targetBranch:'release/v1'}); + expect(second.baseCommit).toBe(checkpoint.sourceCommit); + const afterPush=await post('/repos',{tenantId:'tenant',projectId:'project',defaultBranch:'other'});expect(afterPush.defaultBranch).toBe('release/v1');expect(afterPush.initialCommit).toBe(checkpoint.sourceCommit); + const unsafe=await fetch(`${base}/repos`,{method:'POST',headers:{authorization:`Bearer ${admin}`,'content-type':'application/json'},body:JSON.stringify({tenantId:'tenant',projectId:'invalid-branch',defaultBranch:'main:other'})});expect(unsafe.status).toBe(400); + const cross=await fetch(`${base}/git/other/project.git/info/refs?service=git-upload-pack`,{headers:{authorization:`Bearer ${reader.token!}`}}); + expect(cross.status).toBe(401); + await mkdir(path.join(root, 'outside.git')); + await symlink(path.join(root, 'outside.git'), path.join(root, 'repos', 'tenant', 'escape.git')); + const escaped=await fetch(`${base}/repos`,{method:'POST',headers:{authorization:`Bearer ${admin}`,'content-type':'application/json'},body:JSON.stringify({tenantId:'tenant',projectId:'escape'})}); + expect(escaped.status).toBe(400);expect((await escaped.json()).error).toBe('REPOSITORY_SCOPE'); + }finally{server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()));await rm(root,{recursive:true,force:true});} +},15000); diff --git a/apps/git-service/tsconfig.json b/apps/git-service/tsconfig.json new file mode 100644 index 0000000..7f4b8b9 --- /dev/null +++ b/apps/git-service/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../../tsconfig.base.json", "compilerOptions": { "noEmit": true, "types": ["node"] }, "include": ["src/**/*.ts", "test/**/*.ts"] } diff --git a/apps/ide/.dockerignore b/apps/ide/.dockerignore new file mode 100644 index 0000000..cf8e70a --- /dev/null +++ b/apps/ide/.dockerignore @@ -0,0 +1,5 @@ +node_modules +lib +src-gen +workspace +test diff --git a/apps/ide/.gitignore b/apps/ide/.gitignore new file mode 100644 index 0000000..d23a762 --- /dev/null +++ b/apps/ide/.gitignore @@ -0,0 +1,11 @@ +node_modules/ +plugins/ +lib/ +src-gen/ +workspace/ +webpack.config.js +gen-webpack.config.js +tsconfig.json +*.tsbuildinfo +esbuild.mjs +gen-esbuild.*.mjs diff --git a/apps/ide/Dockerfile b/apps/ide/Dockerfile new file mode 100644 index 0000000..9eecae5 --- /dev/null +++ b/apps/ide/Dockerfile @@ -0,0 +1,17 @@ +FROM node:22.14.0-bookworm AS build +RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ libsecret-1-dev libx11-dev libxkbfile-dev libudev-dev && rm -rf /var/lib/apt/lists/* +WORKDIR /opt/wishforge-ide +ENV PUPPETEER_SKIP_DOWNLOAD=true +COPY package.json package-lock.json ./ +COPY policy ./policy +COPY collaboration ./collaboration +COPY coordination ./coordination +COPY security ./security +RUN npm ci --no-audit --no-fund +COPY scripts ./scripts +COPY product.json ./product.json +RUN npm run plugins:download && npm run build:production && mkdir /workspace && chown -R node:node /workspace && chmod -R go-w /opt/wishforge-ide +USER node +ENV NODE_ENV=production WISHFORGE_IDE_HOST=0.0.0.0 WISHFORGE_IDE_PORT=4300 WISHFORGE_WORKSPACE_PATH=/workspace +EXPOSE 4300 +CMD ["node", "scripts/start.mjs"] diff --git a/apps/ide/README.md b/apps/ide/README.md new file mode 100644 index 0000000..3bda0ab --- /dev/null +++ b/apps/ide/README.md @@ -0,0 +1,160 @@ +# WishForge Theia application + +This independent Node/browser application pins Eclipse Theia **1.76.0** and +`@theia/collaboration`. It is intentionally excluded from the root npm workspaces +because Theia has a large dependency tree and native modules. Its own lockfile is +the reproducible installation boundary. It provides the actual IDE framework, +not the console's source-code preview panel. + +```sh +cd apps/ide +PUPPETEER_SKIP_DOWNLOAD=true npm ci +npm run plugins:download +npm run build +npm start +``` + +The local address is `http://127.0.0.1:4300`. Start OCT using the `ide` Compose +profile for isolated protocol checks only. Room admission uses an isolated instance per workspace behind the gateway. The +local `@wishforge/ide-policy` extension disables room commands/status unless +`WF_COLLABORATION_GATEWAY_URL` names the current authenticated workspace route; +the start wrapper blocks public OCT fallback. `WISHFORGE_WORKSPACE_PATH` selects the +workspace directory. Native builds need Python, make/C++ and the OS development +libraries; Linux prerequisites are included in the Dockerfile. + +The pinned VS Code built-in extension archive supplies the Git, language and +JavaScript debugging extensions. Its `vscode.python` package supplies Python +syntax/grammar support; it is **not** a Python debugger. `plugins:download` also +installs the separately pinned `ms-python.python` **2026.4.0** dependency and +`ms-python.debugpy` **2026.6.0**, with the debugger's bundled Python libraries, +and `ms-pyright.pyright` **1.1.402** for Python completion, hover and diagnostics. +No global `pip` installation is needed. Python itself must be present in the +workspace image or a project virtual environment; set its path in `launch.json`. +Download completion and each runtime interaction must be checked. +Theia 1.76 no longer publishes the legacy `@theia/git` or `@theia/preview` packages; +this package uses SCM/plugin support and `@theia/editor-preview`. + +## Python debugger installation and acceptance + +`npm run plugins:download:python` downloads only these three pinned Python packages. The lockfile at +`scripts/python-debugger.lock.json` pins official Open VSX VSIX checksums for +Linux x64/ARM64 and macOS x64/ARM64. Unsupported platforms fail explicitly. +The downloader checks the SHA-256, package identity, size and extraction paths, +then unpacks each extension atomically: Theia's system `local-dir` loader does not +load a bare VSIX. For an offline build, supply the three already-downloaded files: + +```sh +npm run plugins:download:python -- --archive /path/to/debugpy.vsix --python-archive /path/to/python.vsix --pyright-archive /path/to/pyright.vsix +npm run plugins:verify +``` + +The local macOS ARM64 acceptance used Theia 1.76.0 and Python 3.14.5 through the +authenticated gateway. Without a debugger lease F5 was rejected by the backend; +after acquiring control, a real Python process paused at a line-2 breakpoint with +`count: 1`, and F10 advanced to line 3 with `count: 2`. The call stack and variables +were visible. The debug process was stopped and the prior Node launch config +restored. Evidence: `/private/tmp/wishforge-python-debug-ui.json` and +`/private/tmp/wishforge-python-debug-controller.png`. + +The same local browser also verified Python/Pyright and the existing bundled +TypeScript service separately: string-method completion, a typed function hover, +and an invalid numeric argument reported by `Pyright(reportArgumentType)` and +`ts(2345)` respectively. Temporary source fixtures were removed afterward; no +package installation or network `pip` command was involved. Evidence: +`/private/tmp/wishforge-language-services-ui.json`, with language-specific +completion/hover/diagnostic PNGs under `/private/tmp/wishforge-`. The upstream +`INVALID tab` diagnostic remains recorded; these checks do not assert that every +IDE interaction is warning-free. + +Linux and macOS x64 packages are pinned but have not received runtime acceptance. +Pylance and Python Environments are recommendations, not installed dependencies; +their workflows are outside this acceptance. Pyright provides the separately +verified language services. +The backend still reports upstream localization/activation and Node-version +warnings, so this is not a zero-warning compatibility claim. + +## Operator-managed extensions + +Extensions can be viewed in the IDE, whose extension view is marked +“管理员管理”. Dynamic registry/VSIX installation, updates, removal and enable/disable +requests are rejected by the backend with `EXTENSIONS_MANAGED_BY_ADMIN`, including +requests that claim to be system extensions. Direct deployer/bulk paths are also +closed. This applies in development and production; hiding a button is not the +enforcement mechanism. + +At startup the backend loads only the image's fixed system directory. It ignores +user extension directories, `THEIA_PLUGINS`, recommendations and injected install +arguments. The initial catalog contains 92 built-in extensions from the official +`1.108.2` archive plus the three Python extensions (95 in total). Every builtin's ID, version and +file-content digest must match `policy/managed-plugins.lock.json`; Python files +must match their SHA-pinned official VSIX contents. Missing, extra or altered +extensions fail closed. `npm run plugins:verify` runs the same checks at image +build time. Python bytecode generation is disabled to keep installed content +immutable. + +The builtin catalog is generated from the exact upstream archive, whose published +SHA-256 is `05a20cf3e671c8d328b04d9ce72b25688b0e762e4a3f5592f31a21ee38280367`. +`node scripts/catalog-builtin-plugins.mjs /path/to/vscode-builtin-extensions-1.108.2.tar.gz` +reproduces it only after verifying that archive. It does not approve or sign an +arbitrary runtime plugin directory. Changes to approved packages require an +operator-reviewed lockfile/image update and compatibility acceptance. + +Seven focused tests cover the real Theia server/deployer classes, forged system +arguments, direct/bulk mutation calls, retained installed-plugin reads, additional +plugins, altered content/version and symlinks. In the rebuilt local IDE a real +“Install Extension VSIX” action reached `ManagedPluginServer.install` and was +rejected with `EXTENSIONS_MANAGED_BY_ADMIN`; the administrator notice and existing +Python/debugger entries remained visible. Evidence is recorded in +`/private/tmp/wishforge-managed-extensions-ui.json`. + +The Docker image leaves the application, plugins and catalog root-owned; only +the workspace is handed to the runtime user. Production also requires the +provisioner's read-only root filesystem. A local writable checkout and a terminal +running as the backend's same UID can still alter that backend or its policy: +these installation gates are not hard isolation against hostile users sharing +such a workspace. + +## Production boundary + +Theia itself is a privileged workspace process: terminal, file, plugin and debug +APIs must sit behind an authenticated workspace gateway and tenant-specific +runtime. Never expose port 4300 directly. The start wrapper requires +`WISHFORGE_GATEWAY_ENFORCED=true` in production; +that flag is an operator assertion, not an implemented gateway or a security test. +Use TLS, per-workspace origins/cookies, WebSocket origin checks, short-lived +audience-bound sessions, and authorize every upgrade and API request. + +Only project owners/editors may enter an editing workspace or OCT room. Viewers +use the console's read-only code review surface; they must not receive an IDE +session or room token. Theia 1.76's built-in collaboration read-only controls are +not complete, so a hidden button is not an authorization boundary. The workspace ACL-to-OCT bridge and actual two-browser co-edit/save flow have +local acceptance evidence. The policy extension also implements coordinated saved +revisions, IndexedDB draft comparison recovery and a backend-enforced debugger +lease; see `policy/README.md`. Production CNI and hostile-terminal isolation remain +separate requirements. Collaboration is disabled +when the dedicated instance and current workspace gateway path are absent. + +OCT 0.3.1 stores session state in memory. A volume or a saved room ID does not make +the CRDT/session durable. On restart, restore saved workspace files and metadata, +start a new room, reauthorize members, and show that unsaved edits may be absent. +Do not claim lossless room recovery, multi-host failover or horizontal scaling. + +Before agent integration/build/deploy, a save barrier must gather active editor +acknowledgements at one revision, persist changes, freeze a commit/snapshot and +bind validation to its digest. A timeout or concurrent edit invalidates the +barrier. The policy extension now implements this coordinated snapshot command using +actual editor callbacks and a durable revision store. The human commits the saved +workspace and explicitly imports that snapshot into the run. The API and worker +compare its exact Git bytes, revision and activity before integration/build, and +hold a fenced project integration lease. A new edit invalidates the input and +returns the run to waiting. This gate is implemented; automatic human-repository +synchronization remains separate. See [workspace handoff](../../docs/workspace-handoff.md) +and [verified status](../../docs/acceptance-traceability.md). + +Sources: [Theia architecture](https://theia-ide.org/docs/architecture/), +[Theia 1.76 collaboration source](https://github.com/eclipse-theia/theia/blob/v1.76.0/packages/collaboration/src/browser/collaboration-frontend-contribution.ts), +[OCT 0.3.1 source](https://github.com/eclipse-oct/open-collaboration-tools/tree/ef757242e1bc5bd4a74f1baf068aa047decaad13), +[official builtin release](https://github.com/eclipse-theia/vscode-builtin-extensions/releases/tag/1.108.2), +[Python debugger](https://github.com/microsoft/vscode-python-debugger), +[Open VSX debugger package](https://open-vsx.org/extension/ms-python/debugpy/2026.6.0), +[fixed Pyright package](https://open-vsx.org/extension/ms-pyright/pyright/1.1.402). diff --git a/apps/ide/collaboration/Dockerfile b/apps/ide/collaboration/Dockerfile new file mode 100644 index 0000000..b4b7d32 --- /dev/null +++ b/apps/ide/collaboration/Dockerfile @@ -0,0 +1,6 @@ +# Build the pinned upstream runtime first with infra/oct/Dockerfile. +FROM wishforge/oct:0.3.1-wf1 +COPY --chown=node:node start-isolated.mjs /opt/oct/start-isolated.mjs +ENV WF_OCT_HOST=0.0.0.0 +EXPOSE 8100 +CMD ["node", "/opt/oct/start-isolated.mjs"] diff --git a/apps/ide/collaboration/README.md b/apps/ide/collaboration/README.md new file mode 100644 index 0000000..f869b78 --- /dev/null +++ b/apps/ide/collaboration/README.md @@ -0,0 +1,127 @@ +# Workspace-isolated OCT collaboration + +This directory supplies the tested collaboration-server launcher and the prefix +adapter consumed by the WishForge Theia policy extension. Each workspace owns +one Open Collaboration Tools 0.3.1 process. Room registries and signing keys are +never shared between workspaces. The authoritative identity remains the +WishForge gateway session; OCT's `user` display name is unverified presentation +text, not a tenant identity or permission grant. + +## Verified upstream behavior + +The following were inspected in the installed Theia 1.76.0 / OCT packages and +validated against running OCT 0.3.1 containers: + +- The server has root HTTP routes `/api/meta`, `/api/login/initial`, + `/api/login/simple`, `/api/login/poll/:token`, `/api/login/validate` and + `/api/session/*`. There is no server basepath option. Socket.IO uses its + default `/socket.io/` Engine.IO path. The separate `/websocket` server is + commented out, so a generic WebSocket-only OCT transport does not work. +- `OCT_ACTIVATE_SIMPLE_LOGIN=true` enables the display-name form. No external + OAuth account is required. The default provider metadata contains absolute + endpoint `/api/login/simple`. +- The protocol HTTP `getUrl` method preserves a base prefix. Its stock + Socket.IO transport calls `io(url)` without a `path` option, which interprets + the URL pathname as a Socket.IO namespace and still requests `/socket.io/`. + Theia's stock form handler also resolves an absolute provider endpoint + against the origin, dropping a workspace prefix. +- Upstream defaults to a static development signing key and no JWT expiry. + `start-isolated.mjs` supplies a fresh random per-process key, an eight-hour + JWT expiry and only the display-name form endpoint. Restarting a server + invalidates prior room capabilities and requires creating/rejoining a room. +- Theia's protocol 0.3.0 and the server protocol 0.3.1 are compatible because + the protocol checks equal major/minor versions in the 0.x series. + +Primary source locations: +[OCT server implementation](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-server/src/collaboration-server.ts), +[simple login](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-server/src/auth-endpoints/simple-login-endpoint.ts), +[credential manager](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-server/src/credentials-manager.ts), +[protocol connection provider](https://github.com/eclipse-oct/open-collaboration-tools/blob/ef757242e1bc5bd4a74f1baf068aa047decaad13/packages/open-collaboration-protocol/src/connection-provider.ts), +[Theia collaboration contribution](https://github.com/eclipse-theia/theia/blob/v1.76.0/packages/collaboration/src/browser/collaboration-frontend-contribution.ts). +The pinned npm package code and live fixture, rather than a generic description +of OCT, are the acceptance evidence for this implementation. + +## Gateway and client contract + +The API workspace authorization response provides trusted fields: + +```json +{ + "tenantId": "tenant-id", + "projectId": "project-id", + "workspaceId": "workspace-id", + "role": "developer", + "upstreamUrl": "http://workspace-service:3000", + "collaborationUpstreamUrl": "http://workspace-service:8100" +} +``` + +Only the trusted workspace provisioner sets these upstreams. A public caller +cannot choose an arbitrary OCT target. The gateway authorizes operation `edit` +for every HTTP request and WebSocket upgrade under +`/workspaces//collaboration/`. It strips that prefix and proxies to the +workspace's `collaborationUpstreamUrl`. It keeps `x-oct-*` protocol headers, +strips platform bearer tokens/cookies before forwarding, and periodically +reauthorizes upgraded connections. Viewers cannot enter collaboration. + +The Theia backend receives: + +```text +WF_COLLABORATION_GATEWAY_URL=https://ide.example/workspaces//collaboration/ +``` + +The client factory requires that URL to share the browser origin and current +workspace ID. It passes the origin to Socket.IO and explicitly sets its path to +`/workspaces//collaboration/socket.io`. Polling is used for the authenticated +initial handshake, followed by WebSocket upgrade. This preserves the OCT header +contract in browsers where direct WebSocket custom headers are unavailable. +The factory rewrites the known form endpoint to relative `api/login/simple` +before handing it to Theia's form UI. It does not allow arbitrary OAuth URLs. + +## Isolated process and image + +```sh +docker --context colima build -t wishforge/oct:0.3.1-wf1 infra/oct +docker --context colima build -t wishforge/oct-workspace:0.3.1-wf1 apps/ide/collaboration +``` + +Run one sidecar per workspace with `WF_WORKSPACE_ID`, `WF_TENANT_ID`, +`WF_OCT_PORT=8100`, `WF_OCT_HOST=0.0.0.0`, and +`WISHFORGE_GATEWAY_ENFORCED=true`. The gateway is the only authorized network +entry. In Kubernetes, place it in the workspace Kata Pod, allow port 8100 only +from the gateway and do not publish an ingress directly to OCT. The container +needs no workspace volume or other workspace's room state. Its root filesystem +can be read-only; drop Linux capabilities and disallow privilege escalation. + +The programmatic launcher avoids OCT 0.3.1's CLI `parseInt` port option bug. A +loopback-only local process can use the default `WF_OCT_HOST=127.0.0.1`. +The shared development OCT container in `infra/compose.yaml` is not used to host +production workspace rooms. + +## Verification + +```sh +node --test apps/ide/collaboration/test/client-factory.test.cjs +WF_OCT_INTEGRATION=1 node --test --test-force-exit apps/ide/collaboration/test/isolated-oct.test.mjs +``` + +The real protocol test starts two unique, loopback-bound Docker containers and +uses the actual gateway, opaque sessions, the pinned protocol clients, +Socket.IO encryption and Yjs documents. It proves host-to-guest and +guest-to-host edit convergence, viewer rejection, foreign-workspace cookie +rejection, copied invitation rejection, cross-instance JWT rejection and +revocation-driven connection closure. It stops only its generated containers. +Its control-plane authorization endpoint is a fixture; this is protocol and +routing evidence, not a production OIDC/Kata acceptance test. + +Node's Engine.IO cookie jar replaces manually injected fixture cookies when +`withCredentials=true`. The Node test overrides that option to false while +providing its fixture Cookie header. The browser client keeps +`withCredentials=true` and relies on the gateway's real HttpOnly cookie. + +Actual two-browser Theia create/join, host-approved guest admission, bidirectional +remote-file edits and host-save persistence passed on 2026-10-17 through the real +local API and gateway. Both contexts used the development platform identity; +production multi-identity OIDC, acknowledged save barriers, draft recovery after +restart and network isolation remain separate validations. OCT 0.3.1 keeps +rooms in memory; this implementation does not claim persistent room recovery. diff --git a/apps/ide/collaboration/client-factory.cjs b/apps/ide/collaboration/client-factory.cjs new file mode 100644 index 0000000..bd662b4 --- /dev/null +++ b/apps/ide/collaboration/client-factory.cjs @@ -0,0 +1,37 @@ +/** Prefix-aware OCT adapter for Theia 1.76 / open-collaboration-protocol 0.3.x. + * Platform authentication remains the workspace gateway's HttpOnly session. + * OCT display names and room tokens never grant access to a workspace. + */ +function collaborationBase(raw, browserLocation) { + const location = new URL(browserLocation); + const base = new URL(raw, location.origin); + const match = /^\/workspaces\/([a-zA-Z0-9][a-zA-Z0-9_-]*)\//.exec(location.pathname); + if (!match || base.origin !== location.origin || base.username || base.password || base.search || base.hash || base.pathname !== `/workspaces/${match[1]}/collaboration/`) throw new Error('Collaboration must use this workspace authenticated gateway path'); + return base; +} +function normalizeAuthMetadata(meta) { + const providers = (meta.providers ?? []).filter(provider => provider.type === 'form' && provider.name === 'unverified' && provider.endpoint === '/api/login/simple').map(provider => ({ ...provider, endpoint: 'api/login/simple' })); + if (providers.length !== 1) throw new Error('Workspace collaboration requires its isolated display-name provider'); + return { ...meta, providers, loginPageUrl: undefined }; +} +function createPrefixTransport({ io, SocketIoTransport }, baseUrl) { + const base = new URL(baseUrl); + return { id: 'socket.io', createTransport(_url, headers) { + // io(baseUrl) treats the pathname as a namespace and silently uses /socket.io. + // Explicit path and origin keep both Engine.IO polling and WS upgrade scoped. + const socket = io(base.origin, { path: `${base.pathname}socket.io`, extraHeaders: headers, withCredentials: true, transports: ['polling', 'websocket'] }); + return new SocketIoTransport(socket); + } }; +} +function createPrefixConnectionProvider(deps, options) { + const base = collaborationBase(options.url, options.browserLocation); + return new deps.ConnectionProvider({ + url: base.href, + client: options.client, + fetch: (url, init) => options.fetch(url, { ...init, credentials: 'same-origin' }), + authenticationHandler: (token, metadata) => options.authenticationHandler(token, normalizeAuthMetadata(metadata)), + transports: [createPrefixTransport(deps, base.href)], + userToken: options.userToken, + }); +} +module.exports = { collaborationBase, normalizeAuthMetadata, createPrefixTransport, createPrefixConnectionProvider }; diff --git a/apps/ide/collaboration/start-isolated.mjs b/apps/ide/collaboration/start-isolated.mjs new file mode 100644 index 0000000..0e12d1d --- /dev/null +++ b/apps/ide/collaboration/start-isolated.mjs @@ -0,0 +1,30 @@ +import 'reflect-metadata'; +import { randomBytes, webcrypto } from 'node:crypto'; +import { Container } from 'inversify'; +import { initializeProtocol } from 'open-collaboration-protocol'; +import { CollaborationServer, CredentialsManager, AuthEndpoint, SimpleLoginEndpoint } from 'open-collaboration-server'; + +const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,199}$/.test(value); +if (!id(process.env.WF_WORKSPACE_ID) || !id(process.env.WF_TENANT_ID)) throw new Error('Each OCT instance requires its own WF_WORKSPACE_ID and WF_TENANT_ID'); +const hostname = process.env.WF_OCT_HOST ?? '127.0.0.1'; +if (!['127.0.0.1', '0.0.0.0'].includes(hostname)) throw new Error('Invalid isolated OCT listen address'); +if (hostname !== '127.0.0.1' && process.env.WISHFORGE_GATEWAY_ENFORCED !== 'true') throw new Error('Network binding requires an enforced workspace gateway and default-deny network policy'); +const port = Number(process.env.WF_OCT_PORT ?? 8100); +if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid isolated OCT port'); +// Never use OCT's shared development signing key. A restart invalidates all room +// capabilities because upstream room state is in memory and cannot be recovered. +process.env.OCT_JWT_PRIVATE_KEY = randomBytes(48).toString('base64url'); +process.env.OCT_ACTIVATE_SIMPLE_LOGIN = 'true'; +process.env.OCT_SERVER_OWNER = `WishForge workspace ${process.env.WF_WORKSPACE_ID}`; +initializeProtocol({ cryptoModule: webcrypto }); +const { default: serverModule } = await import(new URL('./inversify-module.js', import.meta.resolve('open-collaboration-server')).href); +const container = new Container(); +container.load(serverModule); +// This deployment deliberately has one display-name form behind the gateway; +// no external OAuth providers or account registration flows are activated. +container.rebind(AuthEndpoint).toService(SimpleLoginEndpoint); +const credentials = container.get(CredentialsManager); +credentials.getJwtExpiration = async () => '8h'; +const server = container.get(CollaborationServer); +// Call the typed API instead of the 0.3.1 Commander parseInt/radix port bug. +server.startServer({ hostname, port }); diff --git a/apps/ide/collaboration/test/client-factory.test.cjs b/apps/ide/collaboration/test/client-factory.test.cjs new file mode 100644 index 0000000..d92c62f --- /dev/null +++ b/apps/ide/collaboration/test/client-factory.test.cjs @@ -0,0 +1,23 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { collaborationBase, normalizeAuthMetadata, createPrefixTransport } = require('../client-factory.cjs'); +test('collaboration URLs remain within the authenticated workspace and same origin', () => { + const location = 'https://ide.example/workspaces/alpha/index.html'; + assert.equal(collaborationBase('https://ide.example/workspaces/alpha/collaboration/', location).pathname, '/workspaces/alpha/collaboration/'); + for (const url of ['https://external.example/workspaces/alpha/collaboration/', 'https://ide.example/workspaces/beta/collaboration/', 'https://ide.example/socket.io/', 'https://ide.example/workspaces/alpha/collaboration/?token=secret']) assert.throws(() => collaborationBase(url, location)); +}); +test('simple display-name form URL cannot escape the workspace basepath', () => { + const meta = normalizeAuthMetadata({ providers: [{ type: 'form', name: 'unverified', endpoint: '/api/login/simple' }, { type: 'web', name: 'github', endpoint: 'https://external.example' }] }); + assert.equal(meta.providers.length, 1); + assert.equal(new URL(meta.providers[0].endpoint, 'https://ide.example/workspaces/alpha/collaboration/').pathname, '/workspaces/alpha/collaboration/api/login/simple'); + assert.throws(() => normalizeAuthMetadata({ providers: [], loginPageUrl: 'https://external.example/login' })); +}); +test('Socket.IO uses origin namespace plus a workspace-specific Engine.IO path', () => { + let observed; const socket = {}; + const adapter = createPrefixTransport({ io: (...args) => { observed = args; return socket; }, SocketIoTransport: class { constructor(value) { this.socket = value; } } }, 'https://ide.example/workspaces/alpha/collaboration/'); + const transport = adapter.createTransport('ignored', { 'x-oct-jwt': 'room-token' }); + assert.equal(transport.socket, socket); assert.equal(observed[0], 'https://ide.example'); + assert.equal(observed[1].path, '/workspaces/alpha/collaboration/socket.io'); + assert.deepEqual(observed[1].transports, ['polling', 'websocket']); + assert.equal(observed[1].extraHeaders['x-oct-jwt'], 'room-token'); +}); diff --git a/apps/ide/collaboration/test/isolated-oct.test.mjs b/apps/ide/collaboration/test/isolated-oct.test.mjs new file mode 100644 index 0000000..cb3e0e6 --- /dev/null +++ b/apps/ide/collaboration/test/isolated-oct.test.mjs @@ -0,0 +1,98 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { randomUUID, webcrypto } from 'node:crypto'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { createGateway } from '../../gateway/server.mjs'; +import factory from '../client-factory.cjs'; +const require = createRequire(new URL('../../package.json', import.meta.url)); +const protocol = await import(pathToFileURL(require.resolve('open-collaboration-protocol')).href); +const { io } = await import(pathToFileURL(require.resolve('socket.io-client')).href); +const { OpenCollaborationYjsProvider } = await import(pathToFileURL(require.resolve('open-collaboration-yjs')).href); +const Y = await import('../../node_modules/yjs/dist/yjs.mjs'); +const { Awareness } = await import('../../node_modules/y-protocols/awareness.js'); +protocol.initializeProtocol({ cryptoModule: webcrypto }); +const execute = promisify(execFile); +const docker = (...args) => execute('docker', ['--context', process.env.WF_TEST_DOCKER_CONTEXT ?? 'colima', ...args], { timeout: 30_000 }); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +async function until(check, message) { const end = Date.now() + 10_000; do { if (await check()) return; await sleep(25); } while (Date.now() < end); throw new Error(message); } +async function listen(server) { await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); return `http://127.0.0.1:${server.address().port}`; } + +test('two isolated OCT instances support scoped Socket.IO/Yjs collaboration and reject invite/token reuse across workspaces', { skip: process.env.WF_OCT_INTEGRATION !== '1', timeout: 60_000 }, async () => { + const names = [], connections = [], docs = [], awareness = [], sockets = []; + let api, gateway; const revoked = new Set(); + const members = { alice: { workspace: 'workspace-a', role: 'developer' }, bob: { workspace: 'workspace-a', role: 'developer' }, charlie: { workspace: 'workspace-b', role: 'developer' }, viewer: { workspace: 'workspace-a', role: 'viewer' } }; + try { + const origins = {}; + for (const workspace of ['workspace-a', 'workspace-b']) { + const name = `wishforge-oct-test-${randomUUID().slice(0, 8)}`; names.push(name); + await docker('run', '-d', '--rm', '--name', name, '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--tmpfs', '/tmp:rw,noexec,nosuid,size=16m', '-p', '127.0.0.1::8100', '-e', `WF_WORKSPACE_ID=${workspace}`, '-e', 'WF_TENANT_ID=fixture-tenant', '-e', 'WISHFORGE_GATEWAY_ENFORCED=true', 'wishforge/oct-workspace:0.3.1-wf1'); + const port = (await docker('port', name, '8100/tcp')).stdout.trim().split(':').at(-1); origins[workspace] = `http://127.0.0.1:${port}`; + await until(async () => { try { return (await fetch(`${origins[workspace]}/api/meta`)).ok; } catch { return false; } }, 'OCT did not start'); + } + api = http.createServer(async (req, res) => { + let text = ''; for await (const bytes of req) text += bytes; + const request = JSON.parse(text), who = members[request.userToken], workspace = req.url.split('/')[3]; + if (!who || revoked.has(request.userToken) || who.workspace !== workspace) { res.writeHead(403); res.end(); return; } + assert.equal(request.operation, 'edit'); + res.setHeader('content-type', 'application/json'); res.end(JSON.stringify({ data: { tenantId: 'fixture-tenant', projectId: `project-${workspace}`, workspaceId: workspace, role: who.role, upstreamUrl: origins[workspace], collaborationUpstreamUrl: origins[workspace] } })); + }); + const apiOrigin = await listen(api); + // Reserve a local port before gateway construction, which requires its public origin. + const reserve = http.createServer(); const publicUrl = await listen(reserve); await new Promise(resolve => reserve.close(resolve)); + gateway = createGateway({ publicUrl, tenantId: 'fixture-tenant', serviceToken: 'gateway-fixture-token', apiOrigin, allowedUpstreamOrigins: Object.values(origins), allowedCollaborationOrigins: Object.values(origins), reauthorizeMs: 50 }); + await new Promise(resolve => gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1', resolve)); + async function session(user) { + const workspace = members[user].workspace; + const launch = await fetch(`${publicUrl}/launch`, { method: 'POST', headers: { authorization: `Bearer ${user}`, 'content-type': 'application/json' }, body: JSON.stringify({ workspaceId: workspace }) }); + if (!launch.ok) return { status: launch.status }; + const { launchUrl } = await launch.json(); const response = await fetch(launchUrl, { redirect: 'manual' }); + return { status: response.status, cookie: response.headers.get('set-cookie').split(';')[0], workspace }; + } + const alice = await session('alice'), bob = await session('bob'), charlie = await session('charlie'); + assert.equal((await session('viewer')).status, 403); + function client(user, displayName) { + const url = `${publicUrl}/workspaces/${user.workspace}/collaboration/`; + const localFetch = (target, init = {}) => fetch(target, { ...init, headers: { ...init.headers, cookie: user.cookie, origin: publicUrl } }); + return factory.createPrefixConnectionProvider({ ...protocol, io: (origin, options) => { const socket = io(origin, { ...options, withCredentials: false, extraHeaders: { ...options.extraHeaders, Cookie: user.cookie, Origin: publicUrl } }); sockets.push(socket); socket.on('connect_error', error => console.error('OCT socket connection error:', error.message, error.description, error.context?.status, error.context?.responseText?.slice(0,300))); return socket; } }, { url, browserLocation: `${publicUrl}/workspaces/${user.workspace}/`, client: 'WishForge integration', fetch: localFetch, authenticationHandler: async (token, metadata) => { + assert.equal(metadata.providers[0].endpoint, 'api/login/simple'); + return (await localFetch(new URL(metadata.providers[0].endpoint, url), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ token, user: displayName }) })).ok; + } }); + } + const hostProvider = client(alice, 'Host display name'), guestProvider = client(bob, 'Guest display name'); + const claim = await hostProvider.createRoom({ abortSignal: AbortSignal.timeout(10_000) }); + const host = await hostProvider.connect(claim.roomToken); connections.push(host); + let hostIdentity; host.peer.onInfo((_origin, peer) => { hostIdentity = peer; }); + host.peer.onJoinRequest(async () => ({ workspace: { name: 'fixture', folders: ['source'] } })); + host.room.onJoin((_origin, peer) => host.peer.init(peer.id, { protocol: protocol.VERSION, host: hostIdentity, guests: [peer], permissions: { readonly: false }, capabilities: {}, workspace: { name: 'fixture', folders: ['source'] } })); + await until(() => !!hostIdentity, 'Host peer did not connect'); + const guestClaim = await guestProvider.joinRoom({ roomId: claim.roomId, abortSignal: AbortSignal.timeout(10_000) }); + const guest = await guestProvider.connect(guestClaim.roomToken, guestClaim.host); connections.push(guest); guest.peer.onInfo(() => {}); + let initialized = false; guest.peer.onInit(() => { initialized = true; }); + await until(() => initialized, 'Guest did not receive encrypted initialization'); + for (const connection of [host, guest]) { const doc = new Y.Doc(); const state = new Awareness(doc); docs.push(doc); awareness.push(state); const provider = new OpenCollaborationYjsProvider(connection, doc, state); provider.connect(); } + docs[0].getText('source/example.ts').insert(0, 'const greeting = "hello";'); + await until(() => docs[1].getText('source/example.ts').toString().includes('hello'), 'Host edit did not reach guest'); + docs[1].getText('source/example.ts').insert(docs[1].getText('source/example.ts').length, '\n// guest edit'); + await until(() => docs[0].getText('source/example.ts').toString().includes('guest edit'), 'Guest edit did not reach host'); + assert.equal(docs[0].getText('source/example.ts').toString(), docs[1].getText('source/example.ts').toString()); + assert.equal((await fetch(`${publicUrl}/workspaces/workspace-a/collaboration/api/meta`, { headers: { cookie: charlie.cookie } })).status, 401); + const outsider = client(charlie, 'Allowed in other workspace'); + await assert.rejects(() => outsider.joinRoom({ roomId: claim.roomId, abortSignal: AbortSignal.timeout(5_000) }), /Room not found/); + const tokenCheck = await fetch(`${origins['workspace-b']}/api/login/validate`, { method: 'POST', headers: { 'x-oct-jwt': hostProvider.authToken } }); + assert.equal((await tokenCheck.json()).valid, false, 'Per-instance keys must reject another workspace OCT JWT'); + revoked.add('bob'); + await until(() => sockets[1].disconnected, 'Revoked member websocket was not closed'); + assert.equal((await fetch(`${publicUrl}/workspaces/workspace-a/collaboration/api/meta`, { headers: { cookie: bob.cookie } })).status, 403); + } catch (error) { + for (const name of names) console.error((await docker('logs', '--tail', '15', name)).stdout); + throw error; + } finally { + for (const state of awareness) state.destroy(); for (const doc of docs) doc.destroy(); for (const connection of connections) connection.dispose(); for (const socket of sockets) socket.disconnect(); + if (gateway) await gateway.close(); if (api) await new Promise(resolve => api.close(resolve)); + await Promise.all(names.map(name => docker('stop', '-t', '1', name).catch(() => undefined))); + } +}); diff --git a/apps/ide/coordination/README.md b/apps/ide/coordination/README.md new file mode 100644 index 0000000..3f72938 --- /dev/null +++ b/apps/ide/coordination/README.md @@ -0,0 +1,33 @@ +# Workspace coordination engine + +`require('./index.cjs')` exports `Coordinator` and `CoordinationError`. It uses only Node built-ins. Run `node --test apps/ide/coordination/test/*.test.cjs` from the repository root. + +Create one coordinator per workspace backend with `new Coordinator({ workspaceRoot, stateDirectory, now?, limits? })`. Both paths and optional limits come from trusted provisioning configuration. The state directory must be outside the source tree, on the same local filesystem throughout the backend's lifetime, and should be inaccessible to workspace writers in a hardened deployment. The current Theia integration runs backend and terminal under the same UID, so that privilege separation is **not** provided by a separate directory or PVC. Its own and its object/manifest directory modes are `0700`, which does not exclude same-UID terminal processes. The engine never writes source files or overwrites editor drafts. + +The caller must authenticate each RPC/HTTP request and supply `actorId` from its trusted session. These methods do not authenticate an arbitrary actor string. Only authorized workspace participants should receive state or call methods. `revoke(actorId)` removes the actor's registered clients, invalidates affected pending barriers, and destroys its debug lease; gateway ACL enforcement must also reject subsequent calls and close revoked connections. + +## Save barrier API + +- `register(actorId, clientId, { documents: [{ uri, version, dirty }], dirty? })` registers/heartbeats a tab. Heartbeats expire after 30 seconds. A client ID cannot change actor. File URIs must be inside the workspace; relative paths are normalized. Other editor URI schemes are opaque document IDs and are never read as filesystem paths. All dirty editors, including unsaved untitled buffers, must be reported. +- `unregister(actorId, clientId)` removes only the caller's tab and invalidates barriers containing that tab, preserving the actor's other tabs. Invoke it on connection close. +- `beginBarrier(actorId)` requires an active client of the creator and freezes active clients, their document version vectors, and a digest of disk content. Returns `{ id, actorId, status, expiresAt, diskDigest, participants }`. Only one pending barrier is allowed, with a 30-second deadline. +- `acknowledge(actorId, barrierId, clientId, payload)` accepts only that client's authenticated actor. The caller invokes the editor's `saveAll`, reports its full clean vector via `register`, then acknowledges with the same vector. All participants must acknowledge; no coordinator or other actor can acknowledge on their behalf. +- `await commitBarrier(actorId, barrierId)` is restricted to the creator. It rejects unacknowledged, expired, dirty, changed-version or revoked participants. New clients or edits invalidate a pending barrier. Disk changes since barrier creation also invalidate it, so if saving changed disk the caller starts a fresh barrier after all saves complete. Retrying a committed barrier returns the same snapshot and revision, including after restart. Every client must register again before participating in new barriers after backend restart. + +Commit returns `{ schemaVersion: 1, id, revision, previousId, workspace, digest, files: [{ path, sha256, size, mode }], createdAt, actorId, barrierId }`. It snapshots regular files under the configured root, rejects symlinks and special files, and excludes generated/runtime directory names `.git`, `node_modules`, `dist`, `build`, `coverage`, `.next`, `.cache`, `src-gen`, `.wishforge`, `.wishforge-runtime`, `.runtime`, `.coordination`. These names are excluded at any depth. New project-specific generated paths require explicit policy updates, not a client-supplied arbitrary path list. + +Resource caps default to `limits: { maxFileBytes: 33554432, maxTotalBytes: 268435456, maxFiles: 20000 }` (32 MiB per file, 256 MiB total and 20,000 files). Overrides must be positive safe integers and cannot come from editor RPC input. Scans reject over-limit source with `SNAPSHOT_LIMIT` before opening the offending file, recheck the open descriptor's size, and read only the validated bounded length so concurrent growth cannot cause an unbounded allocation. Total bytes count every included path, including duplicate content; empty files count toward `maxFiles`. Excluded runtime paths consume no quota. Begin and final verification scans do not retain content blobs. Immediately after the final scan, commit rechecks barrier expiry and all participant heartbeats, acknowledgement, clean state and version vectors; elapsed scanning time does not extend the 30-second deadlines. + +Each manifest refers to SHA-256-addressed blobs in `objects/`. Manifests and blobs are created without replacement and made read-only; the journal head is atomically replaced and fsynced. Recovery verifies the manifest chain and referenced content and reconstructs the head if a crash occurred after the immutable manifest commit but before the journal update. Partial temporary files and unreferenced blobs are not committed snapshots. Corruption fails closed. This is a local filesystem integrity proof, not production immutable storage, an OS-level filesystem freeze, or a guarantee against a privileged process rewriting state. External filesystem writers must also be gated by the caller; the engine detects changes with two full content scans but cannot lock arbitrary external writers. + +## Debug controller API + +- `debugAcquire(actorId)` returns `{ actorId, token, expiresAt }`; only one live lease exists and its token has 256 bits of randomness. +- `debugAcquire(actorId, token)` renews the current lease for 30 seconds. A same-actor caller without the token cannot silently take over another tab. +- `assertDebugController(actorId, token)` must guard every mutating debug request, not just the UI buttons. It validates owner, token and expiry. +- `debugTransfer(actorId, token, targetActorId)` requires an active registered target and rotates the token. The trusted backend must deliver the new token only to the target actor's connection. +- `debugRelease(actorId, token)` releases ownership. `state()` exposes controller owner/deadline, never the token. + +Client membership, barriers and debug leases are intentionally ephemeral. A restarted backend requires fresh registration and debug acquisition, so old tokens or acknowledgements cannot authorize new actions. Durable state is the verified snapshot revision chain and exact saved contents. Only one active backend should own a workspace; the local writer lock guards commit/recovery operations, not distributed live membership. The backend integration is responsible for periodic heartbeats, save requests to all participants, and sending updated state. + +The current backend integration is a cooperative-client control, not an adversarial terminal sandbox. A same-UID terminal can tamper with writable state or replace the backend; a hardened deployment needs a separately privileged coordination service reached directly through the gateway and independently controlled debugger processes. Workspace snapshots are not independent release evidence. diff --git a/apps/ide/coordination/index.cjs b/apps/ide/coordination/index.cjs new file mode 100644 index 0000000..d17e555 --- /dev/null +++ b/apps/ide/coordination/index.cjs @@ -0,0 +1,396 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { createHash, randomBytes } = require('node:crypto'); +const { fileURLToPath } = require('node:url'); + +const EXCLUDED = new Set(['.git', 'node_modules', 'dist', 'build', 'coverage', '.next', '.cache', 'src-gen', '.wishforge', '.wishforge-runtime', '.runtime', '.coordination']); +const CLIENT_TTL_MS = 30_000; +const BARRIER_TTL_MS = 30_000; +const DEBUG_LEASE_MS = 30_000; +const DEFAULT_SNAPSHOT_LIMITS = Object.freeze({ maxFileBytes: 32 * 1024 * 1024, maxTotalBytes: 256 * 1024 * 1024, maxFiles: 20_000 }); + +class CoordinationError extends Error { + constructor(code, message) { super(message); this.name = 'CoordinationError'; this.code = code; } +} +function fail(code, message) { throw new CoordinationError(code, message); } +function sha(value) { return createHash('sha256').update(value).digest('hex'); } +function clone(value) { return JSON.parse(JSON.stringify(value)); } +function inside(root, target) { return target === root || target.startsWith(root + path.sep); } +function identifier(value, name) { + if (typeof value !== 'string' || value.length < 1 || value.length > 256 || /[\u0000-\u001f]/.test(value)) fail('INVALID_INPUT', `Invalid ${name}`); + return value; +} +function directorySync(directory) { + const fd = fs.openSync(directory, fs.constants.O_RDONLY); + try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); } +} +function atomicFile(destination, value, immutable = false) { + const temporary = destination + '.' + randomBytes(16).toString('hex') + '.tmp'; + const fd = fs.openSync(temporary, 'wx', 0o600); + try { fs.writeFileSync(fd, value); fs.fsyncSync(fd); } finally { fs.closeSync(fd); } + try { + if (immutable) { + fs.chmodSync(temporary, 0o400); + fs.linkSync(temporary, destination); // Unlike rename, this must never replace a committed object. + fs.unlinkSync(temporary); + } else fs.renameSync(temporary, destination); + directorySync(path.dirname(destination)); + } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); } +} +function ensurePrivateDirectory(directory) { + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + if (fs.lstatSync(directory).isSymbolicLink() || !fs.statSync(directory).isDirectory()) fail('UNSAFE_STATE_PATH', 'State path must be a real directory'); + fs.chmodSync(directory, 0o700); +} +function prospectiveRealPath(directory) { + let existing = directory; + const missing = []; + while (!fs.existsSync(existing)) { + const parent = path.dirname(existing); + if (parent === existing) fail('UNSAFE_STATE_PATH', 'State directory has no existing ancestor'); + missing.unshift(path.basename(existing)); existing = parent; + } + return path.join(fs.realpathSync(existing), ...missing); +} + +class Coordinator { + constructor({ workspaceRoot, stateDirectory, now = Date.now, limits = {} }) { + if (typeof workspaceRoot !== 'string' || typeof stateDirectory !== 'string' || typeof now !== 'function') fail('INVALID_INPUT', 'Workspace, state directory and clock are required'); + if (!limits || typeof limits !== 'object' || Array.isArray(limits) || Object.keys(limits).some(key => !Object.hasOwn(DEFAULT_SNAPSHOT_LIMITS, key))) fail('INVALID_INPUT', 'Invalid snapshot limits'); + this.limits = Object.freeze({ ...DEFAULT_SNAPSHOT_LIMITS, ...limits }); + for (const [key, value] of Object.entries(this.limits)) if (!Number.isSafeInteger(value) || value <= 0) fail('INVALID_INPUT', `${key} must be a positive safe integer`); + this.requestedWorkspaceRoot = path.resolve(workspaceRoot); + this.workspaceRoot = fs.realpathSync(workspaceRoot); + if (!fs.statSync(this.workspaceRoot).isDirectory()) fail('INVALID_INPUT', 'Workspace root must be a directory'); + const requested = path.resolve(stateDirectory); + if (inside(this.workspaceRoot, requested) || inside(requested, this.workspaceRoot)) fail('UNSAFE_STATE_PATH', 'State directory must be separate from the source workspace'); + if (fs.existsSync(requested) && fs.lstatSync(requested).isSymbolicLink()) fail('UNSAFE_STATE_PATH', 'State directory must not be a symlink'); + this.stateDirectory = prospectiveRealPath(requested); + if (inside(this.workspaceRoot, this.stateDirectory) || inside(this.stateDirectory, this.workspaceRoot)) fail('UNSAFE_STATE_PATH', 'State directory must be separate from the source workspace'); + ensurePrivateDirectory(this.stateDirectory); + this.objectsDirectory = path.join(this.stateDirectory, 'objects'); + this.snapshotsDirectory = path.join(this.stateDirectory, 'snapshots'); + ensurePrivateDirectory(this.objectsDirectory); + ensurePrivateDirectory(this.snapshotsDirectory); + this.now = now; + this.clients = new Map(); + this.barriers = new Map(); + this.debugLease = null; + this._withLock(() => this._recover()); + } + + _withLock(action) { + const lock = path.join(this.stateDirectory, 'writer.lock'); + let fd; + try { fd = fs.openSync(lock, 'wx', 0o600); } + catch (error) { + if (error.code !== 'EEXIST') throw error; + // A crashed writer leaves a lock. Never steal a live or undecodable lock. + let previous; + try { previous = JSON.parse(fs.readFileSync(lock, 'utf8')); } catch { fail('STATE_BUSY', 'State writer lock requires operator inspection'); } + if (!Number.isSafeInteger(previous.pid) || previous.pid <= 0) fail('STATE_BUSY', 'State writer lock is invalid'); + try { process.kill(previous.pid, 0); fail('STATE_BUSY', 'Another coordinator is writing state'); } + catch (probe) { if (probe.code !== 'ESRCH') throw probe; } + fs.unlinkSync(lock); + try { fd = fs.openSync(lock, 'wx', 0o600); } catch { fail('STATE_BUSY', 'Another coordinator is writing state'); } + } + try { fs.writeFileSync(fd, JSON.stringify({ pid: process.pid })); fs.fsyncSync(fd); return action(); } + finally { fs.closeSync(fd); fs.unlinkSync(lock); } + } + + _recover() { + const snapshots = fs.readdirSync(this.snapshotsDirectory).filter(name => /^\d{12}\.json$/.test(name)).sort(); + let revision = 0; + let latest = null; + const commits = new Map(); + for (const name of snapshots) { + const file = path.join(this.snapshotsDirectory, name); + if (!fs.lstatSync(file).isFile()) fail('STATE_CORRUPT', 'Snapshot is not a regular file'); + const snapshot = JSON.parse(fs.readFileSync(file, 'utf8')); + const { id, ...body } = snapshot; + if (snapshot.schemaVersion !== 1 || snapshot.workspace !== this.workspaceRoot || snapshot.revision !== revision + 1 || snapshot.previousId !== (latest?.id ?? null) || id !== sha(JSON.stringify(body)) || name !== `${String(snapshot.revision).padStart(12, '0')}.json`) fail('STATE_CORRUPT', 'Snapshot chain failed integrity verification'); + if (!Array.isArray(snapshot.files) || snapshot.digest !== sha(JSON.stringify(snapshot.files))) fail('STATE_CORRUPT', 'Snapshot manifest failed integrity verification'); + for (const item of snapshot.files) { + if (typeof item.path !== 'string' || path.posix.isAbsolute(item.path) || item.path.split('/').some(part => part === '..' || part === '' || part === '.') || !/^[a-f0-9]{64}$/.test(item.sha256)) fail('STATE_CORRUPT', 'Snapshot contains an unsafe file entry'); + const object = path.join(this.objectsDirectory, item.sha256); + if (!fs.lstatSync(object).isFile()) fail('STATE_CORRUPT', 'Snapshot object is not a regular file'); + const bytes = fs.readFileSync(object); + if (bytes.length !== item.size || sha(bytes) !== item.sha256) fail('STATE_CORRUPT', 'Snapshot content failed integrity verification'); + } + revision = snapshot.revision; + latest = snapshot; + if (commits.has(snapshot.barrierId)) fail('STATE_CORRUPT', 'Save barrier has multiple committed revisions'); + commits.set(snapshot.barrierId, snapshot); + } + const journalPath = path.join(this.stateDirectory, 'journal.json'); + if (fs.existsSync(journalPath)) { + if (!fs.lstatSync(journalPath).isFile()) fail('STATE_CORRUPT', 'Journal is not a regular file'); + const journal = JSON.parse(fs.readFileSync(journalPath, 'utf8')); + if (journal.schemaVersion !== 1 || journal.workspace !== this.workspaceRoot || !Number.isSafeInteger(journal.revision) || journal.revision > revision || journal.revision < 0 || (journal.revision === revision && journal.latestId !== (latest?.id ?? null))) fail('STATE_CORRUPT', 'Journal does not match committed snapshots'); + } + this.revision = revision; + this.latestSnapshot = latest; + this.commits = commits; + // A committed immutable manifest is the transaction record. Repair a stale/missing head after crash. + atomicFile(journalPath, JSON.stringify({ schemaVersion: 1, workspace: this.workspaceRoot, revision, latestId: latest?.id ?? null })); + } + + _documents(payload) { + if (!payload || !Array.isArray(payload.documents) || payload.documents.length > 10_000 || (payload.dirty !== undefined && typeof payload.dirty !== 'boolean')) fail('INVALID_INPUT', 'A document version vector is required'); + const seen = new Set(); + const documents = payload.documents.map(document => { + if (!document || typeof document.uri !== 'string' || document.uri.length < 1 || document.uri.length > 8192 || /[\u0000-\u001f]/.test(document.uri) || !Number.isSafeInteger(document.version) || document.version < 0 || typeof document.dirty !== 'boolean') fail('INVALID_INPUT', 'Invalid document version'); + let uri = document.uri; + if (uri.startsWith('file:')) { + let target; + try { target = fileURLToPath(uri); } catch { fail('INVALID_INPUT', 'Invalid file URI'); } + // macOS /var and /tmp aliases, or a provisioned root alias, refer to the same configured workspace. + if (inside(this.requestedWorkspaceRoot, path.resolve(target))) target = path.resolve(this.workspaceRoot, path.relative(this.requestedWorkspaceRoot, target)); + if (!inside(this.workspaceRoot, path.resolve(target))) fail('OUTSIDE_WORKSPACE', 'Document is outside this workspace'); + uri = path.relative(this.workspaceRoot, target).split(path.sep).join('/'); + } else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(uri)) { + const target = path.resolve(this.workspaceRoot, uri); + if (!inside(this.workspaceRoot, target)) fail('OUTSIDE_WORKSPACE', 'Document is outside this workspace'); + uri = path.relative(this.workspaceRoot, target).split(path.sep).join('/'); + } + // Non-file editor URIs (including collaboration and untitled documents) are opaque IDs, never paths to read. + if (seen.has(uri)) fail('INVALID_INPUT', 'Duplicate document URI'); + seen.add(uri); + return { uri, version: document.version, dirty: document.dirty }; + }).sort((left, right) => left.uri.localeCompare(right.uri)); + return { documents, dirty: payload.dirty === true || documents.some(document => document.dirty) }; + } + + _versions(documents) { return JSON.stringify(documents.map(({ uri, version }) => ({ uri, version }))); } + _invalidate(reason) { + for (const barrier of this.barriers.values()) if (barrier.status === 'pending') { barrier.status = 'invalid'; barrier.reason = reason; } + } + _activeClients() { return [...this.clients.values()].filter(client => this.now() - client.lastSeen < CLIENT_TTL_MS); } + + register(actorId, clientId, payload) { + identifier(actorId, 'actor ID'); identifier(clientId, 'client ID'); + const existing = this.clients.get(clientId); + if (existing && existing.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Client belongs to another actor'); + const normalized = this._documents(payload); + for (const barrier of this.barriers.values()) { + if (barrier.status !== 'pending') continue; + const participant = barrier.participants.find(item => item.clientId === clientId); + if (!participant || this._versions(normalized.documents) !== this._versions(participant.documents) || normalized.dirty) { + barrier.status = 'invalid'; barrier.reason = 'Client membership or document version changed'; + } + } + const client = { actorId, clientId, ...normalized, lastSeen: this.now() }; + this.clients.set(clientId, client); + return clone(client); + } + + unregister(actorId, clientId) { + identifier(actorId, 'actor ID'); identifier(clientId, 'client ID'); + const client = this.clients.get(clientId); + if (!client) return { unregistered: true }; + if (client.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Client belongs to another actor'); + this.clients.delete(clientId); + for (const barrier of this.barriers.values()) if (barrier.status === 'pending' && barrier.participants.some(item => item.clientId === clientId)) { barrier.status = 'invalid'; barrier.reason = 'Participant disconnected'; } + return { unregistered: true }; + } + + _capture(retainBlobs = true) { + const files = []; + const blobs = new Map(); + let totalBytes = 0; + const checkSize = size => { + if (size > BigInt(this.limits.maxFileBytes)) fail('SNAPSHOT_LIMIT', 'Snapshot file exceeds maxFileBytes'); + if (size + BigInt(totalBytes) > BigInt(this.limits.maxTotalBytes)) fail('SNAPSHOT_LIMIT', 'Snapshot exceeds maxTotalBytes'); + }; + const walk = (directory, relative = '') => { + for (const name of fs.readdirSync(directory).sort()) { + if (EXCLUDED.has(name)) continue; + const absolute = path.join(directory, name); + const entry = fs.lstatSync(absolute); + if (entry.isSymbolicLink()) fail('UNSAFE_WORKSPACE_PATH', 'Snapshots reject symbolic links'); + const logical = relative ? relative + '/' + name : name; + if (entry.isDirectory()) { + if (!inside(this.workspaceRoot, fs.realpathSync(absolute))) fail('UNSAFE_WORKSPACE_PATH', 'Directory escaped the workspace'); + walk(absolute, logical); + } else if (entry.isFile()) { + if (files.length >= this.limits.maxFiles) fail('SNAPSHOT_LIMIT', 'Snapshot exceeds maxFiles'); + if (!Number.isSafeInteger(entry.size) || entry.size < 0) fail('SNAPSHOT_LIMIT', 'Snapshot file has unsupported size'); + checkSize(BigInt(entry.size)); + // Check both the path and open descriptor; O_NOFOLLOW rejects last-component symlink races. + if (!inside(this.workspaceRoot, fs.realpathSync(absolute))) fail('UNSAFE_WORKSPACE_PATH', 'File escaped the workspace'); + const fd = fs.openSync(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + let bytes; + try { + const before = fs.fstatSync(fd, { bigint: true }); + if (!before.isFile() || before.ino !== BigInt(entry.ino) || before.dev !== BigInt(entry.dev)) fail('DISK_CHANGED', 'File changed while reading'); + checkSize(before.size); + // A file may grow after fstat. Never let readFileSync allocate from + // that mutable size; read only the already-validated bounded length. + bytes = Buffer.alloc(Number(before.size)); + let read = 0; + while (read < bytes.length) { + const count = fs.readSync(fd, bytes, read, bytes.length - read, null); + if (!count) break; + read += count; + } + const extra = fs.readSync(fd, Buffer.alloc(1), 0, 1, null); + const after = fs.fstatSync(fd, { bigint: true }); + checkSize(after.size); + if (read !== bytes.length || extra !== 0 || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || after.size !== BigInt(bytes.length)) fail('DISK_CHANGED', 'File changed while reading'); + } finally { fs.closeSync(fd); } + totalBytes += bytes.length; + const digest = sha(bytes); + if (retainBlobs) blobs.set(digest, bytes); + files.push({ path: logical, sha256: digest, size: bytes.length, mode: entry.mode & 0o777 }); + } else fail('UNSAFE_WORKSPACE_PATH', 'Snapshots support regular files and directories only'); + } + }; + walk(this.workspaceRoot); + return { files, digest: sha(JSON.stringify(files)), blobs }; + } + + beginBarrier(actorId) { + identifier(actorId, 'actor ID'); + for (const barrier of this.barriers.values()) if (barrier.status === 'pending' && this.now() < barrier.expiresAt) fail('BARRIER_BUSY', 'A save barrier is already pending'); + const active = this._activeClients(); + if (!active.some(client => client.actorId === actorId)) fail('CLIENT_REQUIRED', 'Register an active client before starting a barrier'); + const disk = this._capture(false); + const barrier = { + id: randomBytes(24).toString('hex'), actorId, status: 'pending', createdAt: this.now(), expiresAt: this.now() + BARRIER_TTL_MS, + diskDigest: disk.digest, participants: active.map(client => ({ actorId: client.actorId, clientId: client.clientId, documents: clone(client.documents), acknowledged: false })), + }; + this.barriers.set(barrier.id, barrier); + // Bound ephemeral metadata without discarding an in-flight barrier. + if (this.barriers.size > 100) for (const [id, previous] of this.barriers) if (previous.status !== 'pending' || previous.expiresAt <= this.now()) { this.barriers.delete(id); break; } + return clone(barrier); + } + + _barrier(id) { + const barrier = this.barriers.get(id); + if (!barrier) fail('BARRIER_NOT_FOUND', 'Save barrier does not exist'); + if (barrier.status !== 'pending') fail('BARRIER_INVALID', barrier.reason || 'Save barrier is no longer pending'); + if (this.now() >= barrier.expiresAt) { barrier.status = 'expired'; fail('BARRIER_EXPIRED', 'Save barrier expired'); } + return barrier; + } + + acknowledge(actorId, barrierId, clientId, payload) { + identifier(actorId, 'actor ID'); identifier(clientId, 'client ID'); + const barrier = this._barrier(barrierId); + const participant = barrier.participants.find(item => item.clientId === clientId); + const client = this.clients.get(clientId); + if (!participant || !client || participant.actorId !== actorId || client.actorId !== actorId) fail('CLIENT_OWNERSHIP', 'Only the participant may acknowledge its own saved documents'); + const normalized = this._documents(payload); + if (normalized.dirty || client.dirty) fail('DIRTY_DOCUMENTS', 'All documents must be saved and registered clean before acknowledgement'); + if (this._versions(normalized.documents) !== this._versions(participant.documents) || this._versions(client.documents) !== this._versions(participant.documents)) { + barrier.status = 'invalid'; barrier.reason = 'Document version changed'; fail('VERSION_CHANGED', barrier.reason); + } + if (this.now() - client.lastSeen >= CLIENT_TTL_MS) fail('CLIENT_EXPIRED', 'Client heartbeat expired'); + participant.acknowledged = true; + return clone(barrier); + } + + _assertParticipants(barrier) { + for (const participant of barrier.participants) { + const client = this.clients.get(participant.clientId); + if (!participant.acknowledged) fail('ACK_REQUIRED', 'Every frozen participant must acknowledge saving'); + if (!client || client.actorId !== participant.actorId || this.now() - client.lastSeen >= CLIENT_TTL_MS) fail('CLIENT_EXPIRED', 'A participant disconnected or expired'); + if (client.dirty) fail('DIRTY_DOCUMENTS', 'A participant has unsaved documents'); + if (this._versions(client.documents) !== this._versions(participant.documents)) fail('VERSION_CHANGED', 'A participant changed document versions'); + } + } + + async commitBarrier(actorId, barrierId) { + identifier(actorId, 'actor ID'); + const committed = this.commits.get(barrierId); + if (committed) { + if (committed.actorId !== actorId) fail('BARRIER_OWNERSHIP', 'Only the barrier creator may retrieve its committed result'); + return clone(committed); + } + const barrier = this._barrier(barrierId); + if (barrier.actorId !== actorId) fail('BARRIER_OWNERSHIP', 'Only the barrier creator may commit it'); + this._assertParticipants(barrier); + return this._withLock(() => { + this._recover(); + const recovered = this.commits.get(barrierId); + if (recovered) { + if (recovered.actorId !== actorId) fail('BARRIER_OWNERSHIP', 'Only the barrier creator may retrieve its committed result'); + barrier.status = 'committed'; barrier.snapshotId = recovered.id; barrier.revision = recovered.revision; + return clone(recovered); + } + const disk = this._capture(); + if (disk.digest !== barrier.diskDigest) { barrier.status = 'invalid'; barrier.reason = 'Disk changed during save barrier'; fail('DISK_CHANGED', barrier.reason); } + for (const [digest, bytes] of disk.blobs) { + const object = path.join(this.objectsDirectory, digest); + if (fs.existsSync(object)) { + if (!fs.lstatSync(object).isFile() || sha(fs.readFileSync(object)) !== digest) fail('STATE_CORRUPT', 'Existing content-addressed object is invalid'); + } else atomicFile(object, bytes, true); + } + // Re-read immediately before committing; saved snapshot content is never read from mutable source later. + if (this._capture(false).digest !== disk.digest) { barrier.status = 'invalid'; barrier.reason = 'Disk changed while materializing snapshot'; fail('DISK_CHANGED', barrier.reason); } + this._barrier(barrierId); + this._assertParticipants(barrier); + const body = { + schemaVersion: 1, workspace: this.workspaceRoot, revision: this.revision + 1, previousId: this.latestSnapshot?.id ?? null, + digest: disk.digest, files: disk.files, createdAt: this.now(), actorId, barrierId, + }; + const snapshot = { id: sha(JSON.stringify(body)), ...body }; + atomicFile(path.join(this.snapshotsDirectory, `${String(snapshot.revision).padStart(12, '0')}.json`), JSON.stringify(snapshot), true); + this.revision = snapshot.revision; + this.latestSnapshot = snapshot; + atomicFile(path.join(this.stateDirectory, 'journal.json'), JSON.stringify({ schemaVersion: 1, workspace: this.workspaceRoot, revision: this.revision, latestId: snapshot.id })); + this.commits.set(barrierId, snapshot); + barrier.status = 'committed'; barrier.snapshotId = snapshot.id; barrier.revision = snapshot.revision; + return clone(snapshot); + }); + } + + _liveDebugLease() { + if (this.debugLease && this.now() >= this.debugLease.expiresAt) this.debugLease = null; + return this.debugLease; + } + debugAcquire(actorId, token) { + identifier(actorId, 'actor ID'); + const current = this._liveDebugLease(); + if (current) { + if (current.actorId !== actorId || current.token !== token) fail('DEBUG_BUSY', 'Debug control is held by a live lease'); + current.expiresAt = this.now() + DEBUG_LEASE_MS; + return clone(current); + } + this.debugLease = { actorId, token: randomBytes(32).toString('hex'), expiresAt: this.now() + DEBUG_LEASE_MS }; + return clone(this.debugLease); + } + assertDebugController(actorId, token) { + const lease = this._liveDebugLease(); + if (!lease || lease.actorId !== actorId || typeof token !== 'string' || token !== lease.token) fail('DEBUG_FORBIDDEN', 'An active debug controller lease is required'); + return { actorId, expiresAt: lease.expiresAt }; + } + debugTransfer(actorId, token, targetActorId) { + identifier(targetActorId, 'target actor ID'); + this.assertDebugController(actorId, token); + if (!this._activeClients().some(client => client.actorId === targetActorId)) fail('CLIENT_REQUIRED', 'Target controller must have an active registered client'); + this.debugLease = { actorId: targetActorId, token: randomBytes(32).toString('hex'), expiresAt: this.now() + DEBUG_LEASE_MS }; + return clone(this.debugLease); + } + debugRelease(actorId, token) { this.assertDebugController(actorId, token); this.debugLease = null; return { released: true }; } + revoke(actorId) { + identifier(actorId, 'actor ID'); + for (const [id, client] of this.clients) if (client.actorId === actorId) this.clients.delete(id); + for (const barrier of this.barriers.values()) if (barrier.status === 'pending' && (barrier.actorId === actorId || barrier.participants.some(item => item.actorId === actorId))) { barrier.status = 'invalid'; barrier.reason = 'Participant access revoked'; } + if (this.debugLease?.actorId === actorId) this.debugLease = null; + return { revoked: true }; + } + state() { + const lease = this._liveDebugLease(); + return clone({ schemaVersion: 1, revision: this.revision, latestSnapshot: this.latestSnapshot, clients: this._activeClients(), barriers: [...this.barriers.values()].map(barrier => ({ ...barrier, status: barrier.status === 'pending' && this.now() >= barrier.expiresAt ? 'expired' : barrier.status })), debugController: lease ? { actorId: lease.actorId, expiresAt: lease.expiresAt } : null }); + } + inputState() { + const state=this.state(); + const clients=state.clients.map(({actorId,clientId,documents,dirty})=>({actorId,clientId,documents,dirty})).sort((a,b)=>a.clientId.localeCompare(b.clientId)); + const snapshot=state.latestSnapshot; + return { latestSnapshot:snapshot?{id:snapshot.id,revision:snapshot.revision,digest:snapshot.digest,files:snapshot.files}:null,currentDiskDigest:this._capture(false).digest,activityDigest:sha(JSON.stringify(clients)),dirty:clients.some(client=>client.dirty),activeClients:clients.length }; + } +} + +module.exports = { Coordinator, CoordinationError, EXCLUDED: Object.freeze([...EXCLUDED]), CLIENT_TTL_MS, BARRIER_TTL_MS, DEBUG_LEASE_MS, DEFAULT_SNAPSHOT_LIMITS }; diff --git a/apps/ide/coordination/package.json b/apps/ide/coordination/package.json new file mode 100644 index 0000000..de61273 --- /dev/null +++ b/apps/ide/coordination/package.json @@ -0,0 +1,8 @@ +{ + "name": "@wishforge/ide-coordination", + "version": "0.1.0", + "private": true, + "main": "index.cjs", + "scripts": { "test": "node --test test/*.test.cjs" }, + "engines": { "node": ">=22" } +} diff --git a/apps/ide/coordination/test/coordinator.test.cjs b/apps/ide/coordination/test/coordinator.test.cjs new file mode 100644 index 0000000..c83716c --- /dev/null +++ b/apps/ide/coordination/test/coordinator.test.cjs @@ -0,0 +1,407 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { pathToFileURL } = require('node:url'); +const { Coordinator, CLIENT_TTL_MS, DEBUG_LEASE_MS, BARRIER_TTL_MS, DEFAULT_SNAPSHOT_LIMITS } = require('../index.cjs'); + +function fixture(t, extraOptions = {}) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-coordination-')); + const workspaceRoot = path.join(directory, 'source'); + const stateDirectory = path.join(directory, 'coordination'); + fs.mkdirSync(workspaceRoot); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'export const answer = 42;\n'); + let time = 1_000; + const options = { workspaceRoot, stateDirectory, now: () => time, ...extraOptions }; + const coordinator = new Coordinator(options); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + return { directory, workspaceRoot, stateDirectory, coordinator, options, advance: ms => { time += ms; } }; +} +const clean = (version = 1) => ({ documents: [{ uri: 'app.ts', version, dirty: false }] }); +const dirty = (version = 1) => ({ documents: [{ uri: 'app.ts', version, dirty: true }] }); +function code(expected) { return error => error.code === expected; } +function acknowledged(coordinator, actor = 'alice', client = 'alice-tab') { + coordinator.register(actor, client, clean()); + const barrier = coordinator.beginBarrier(actor); + coordinator.acknowledge(actor, barrier.id, client, clean()); + return barrier; +} + +test('saved immutable manifest records exact content and revision outside source without writing drafts', async t => { + const { coordinator: engine, workspaceRoot, stateDirectory } = fixture(t); + const original = fs.readFileSync(path.join(workspaceRoot, 'app.ts')); + for (const name of ['.git', 'node_modules', 'dist', 'build', '.next', 'src-gen', '.wishforge-runtime']) { + fs.mkdirSync(path.join(workspaceRoot, name)); + fs.writeFileSync(path.join(workspaceRoot, name, 'excluded'), 'runtime output'); + } + fs.mkdirSync(path.join(workspaceRoot, 'src')); + fs.writeFileSync(path.join(workspaceRoot, 'src', 'main.py'), 'print(42)\n'); + const snapshot = await engine.commitBarrier('alice', acknowledged(engine).id); + assert.equal(snapshot.revision, 1); + assert.deepEqual(snapshot.files.map(file => file.path), ['app.ts', 'src/main.py']); + assert.deepEqual(fs.readFileSync(path.join(workspaceRoot, 'app.ts')), original); + const manifestPath = path.join(stateDirectory, 'snapshots', fs.readdirSync(path.join(stateDirectory, 'snapshots'))[0]); + const savedManifest = fs.readFileSync(manifestPath); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'new content after snapshot'); + assert.deepEqual(fs.readFileSync(path.join(stateDirectory, 'objects', snapshot.files[0].sha256)), original); + assert.deepEqual(fs.readFileSync(manifestPath), savedManifest); + assert.equal(fs.statSync(stateDirectory).mode & 0o777, 0o700); + assert.equal(fs.statSync(path.join(stateDirectory, 'objects')).mode & 0o777, 0o700); + assert.equal(fs.statSync(manifestPath).mode & 0o777, 0o400); + snapshot.files[0].path = 'mutated-client-copy'; + assert.equal(engine.state().latestSnapshot.files[0].path, 'app.ts'); +}); + +test('constructor limits have bounded defaults and reject nonpositive or unsafe configuration', t => { + const { coordinator: engine, options } = fixture(t); + assert.deepEqual(engine.limits, { maxFileBytes: 32 * 1024 * 1024, maxTotalBytes: 256 * 1024 * 1024, maxFiles: 20_000 }); + assert.deepEqual(engine.limits, DEFAULT_SNAPSHOT_LIMITS); + for (const key of Object.keys(DEFAULT_SNAPSHOT_LIMITS)) for (const value of [0, -1, 1.5, NaN, Infinity, '32', null, undefined, Number.MAX_SAFE_INTEGER + 1]) { + assert.throws(() => new Coordinator({ ...options, limits: { [key]: value } }), code('INVALID_INPUT')); + } + for (const limits of [null, [], 'limits', { unknownLimit: 1 }, { toString: 1 }]) assert.throws(() => new Coordinator({ ...options, limits }), code('INVALID_INPUT')); +}); + +test('single-file resource limit rejects before opening source for reading', t => { + const { coordinator: engine, workspaceRoot } = fixture(t, { limits: { maxFileBytes: 8 } }); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), '123456789'); + engine.register('alice', 'a', clean()); + const open = fs.openSync; + let sourceOpened = false; + fs.openSync = (file, ...args) => { if (typeof file === 'string' && file.endsWith('/app.ts')) sourceOpened = true; return open(file, ...args); }; + try { assert.throws(() => engine.beginBarrier('alice'), code('SNAPSHOT_LIMIT')); } + finally { fs.openSync = open; } + assert.equal(sourceOpened, false); + assert.equal(engine.state().revision, 0); +}); + +test('source growth after fd stat is read only into the bounded allocation then rejected', t => { + const { coordinator: engine, workspaceRoot } = fixture(t, { limits: { maxFileBytes: 3 } }); + const source = path.join(workspaceRoot, 'app.ts'); + fs.writeFileSync(source, 'abc'); + engine.register('alice', 'a', clean()); + const read = fs.readSync; + let grew = false; + const allocations = []; + fs.readSync = (fd, buffer, ...args) => { + allocations.push(buffer.length); + if (!grew) { grew = true; fs.appendFileSync(source, 'defghijklmnop'); } + return read(fd, buffer, ...args); + }; + try { assert.throws(() => engine.beginBarrier('alice'), code('SNAPSHOT_LIMIT')); } + finally { fs.readSync = read; } + assert.equal(grew, true); + assert.deepEqual(allocations, [3, 1]); + assert.equal(engine.state().revision, 0); +}); + +test('aggregate bytes and file count caps reject duplicate content and empty files', t => { + const bytes = fixture(t, { limits: { maxFileBytes: 8, maxTotalBytes: 9 } }); + fs.writeFileSync(path.join(bytes.workspaceRoot, 'app.ts'), '12345'); + fs.writeFileSync(path.join(bytes.workspaceRoot, 'second.ts'), '12345'); + bytes.coordinator.register('alice', 'a', clean()); + assert.throws(() => bytes.coordinator.beginBarrier('alice'), code('SNAPSHOT_LIMIT')); + const count = fixture(t, { limits: { maxFiles: 1 } }); + fs.writeFileSync(path.join(count.workspaceRoot, 'app.ts'), ''); + fs.writeFileSync(path.join(count.workspaceRoot, 'second.ts'), ''); + count.coordinator.register('alice', 'a', clean()); + assert.throws(() => count.coordinator.beginBarrier('alice'), code('SNAPSHOT_LIMIT')); +}); + +test('exact configured limits permit a snapshot while excluded runtime files do not consume caps', async t => { + const { coordinator: engine, workspaceRoot } = fixture(t, { limits: { maxFileBytes: 5, maxTotalBytes: 10, maxFiles: 2 } }); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), '12345'); + fs.writeFileSync(path.join(workspaceRoot, 'second.ts'), '67890'); + fs.mkdirSync(path.join(workspaceRoot, 'node_modules')); + fs.writeFileSync(path.join(workspaceRoot, 'node_modules', 'large'), 'excluded-runtime-file'); + const snapshot = await engine.commitBarrier('alice', acknowledged(engine).id); + assert.equal(snapshot.files.length, 2); + assert.equal(snapshot.files.reduce((total, file) => total + file.size, 0), 10); +}); + +test('commit checks barrier expiry again after the final filesystem scan', async t => { + const { coordinator: engine, advance, stateDirectory } = fixture(t); + const barrier = acknowledged(engine); + const capture = engine._capture.bind(engine); + let captures = 0; + engine._capture = (...args) => { const result = capture(...args); if (++captures === 2) advance(BARRIER_TTL_MS); return result; }; + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_EXPIRED')); + assert.equal(engine.state().revision, 0); + assert.deepEqual(fs.readdirSync(path.join(stateDirectory, 'snapshots')), []); +}); + +test('commit checks stale participant heartbeats after scanning even when barrier itself remains valid', async t => { + const { coordinator: engine, advance, stateDirectory } = fixture(t); + engine.register('alice', 'a', clean()); + advance(10_000); + const barrier = engine.beginBarrier('alice'); + engine.acknowledge('alice', barrier.id, 'a', clean()); + const capture = engine._capture.bind(engine); + let captures = 0; + engine._capture = (...args) => { const result = capture(...args); if (++captures === 2) advance(CLIENT_TTL_MS - 10_000); return result; }; + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('CLIENT_EXPIRED')); + assert.equal(engine.state().revision, 0); + assert.deepEqual(fs.readdirSync(path.join(stateDirectory, 'snapshots')), []); +}); + +test('all concurrent participants must acknowledge their own clean saved version', async t => { + const { coordinator: engine } = fixture(t); + engine.register('alice', 'a', clean()); + engine.register('bob', 'b', dirty()); + const barrier = engine.beginBarrier('alice'); + assert.throws(() => engine.acknowledge('alice', barrier.id, 'b', clean()), code('CLIENT_OWNERSHIP')); + assert.throws(() => engine.acknowledge('bob', barrier.id, 'b', clean()), code('DIRTY_DOCUMENTS')); + engine.acknowledge('alice', barrier.id, 'a', clean()); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('ACK_REQUIRED')); + engine.register('bob', 'b', clean()); + engine.acknowledge('bob', barrier.id, 'b', clean()); + await assert.rejects(engine.commitBarrier('bob', barrier.id), code('BARRIER_OWNERSHIP')); + const snapshot = await engine.commitBarrier('alice', barrier.id); + assert.equal(snapshot.revision, 1); +}); + +test('dirty buffers or version drift after acknowledgement invalidate the barrier permanently', async t => { + const { coordinator: engine } = fixture(t); + const barrier = acknowledged(engine); + engine.register('alice', 'alice-tab', dirty(1)); + engine.register('alice', 'alice-tab', clean(1)); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID')); + const second = acknowledged(engine); + engine.register('alice', 'alice-tab', clean(2)); + await assert.rejects(engine.commitBarrier('alice', second.id), code('BARRIER_INVALID')); + assert.equal(engine.state().revision, 0); +}); + +test('dirty edit before acknowledgement cannot be hidden by a later clean heartbeat', async t => { + const { coordinator: engine } = fixture(t); + engine.register('alice', 'a', clean()); + const barrier = engine.beginBarrier('alice'); + engine.register('alice', 'a', dirty()); + engine.register('alice', 'a', clean()); + assert.throws(() => engine.acknowledge('alice', barrier.id, 'a', clean()), code('BARRIER_INVALID')); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID')); +}); + +test('new client joins cannot bypass the frozen participant set and client IDs cannot change actor', async t => { + const { coordinator: engine } = fixture(t); + const barrier = acknowledged(engine); + assert.throws(() => engine.register('bob', 'alice-tab', clean()), code('CLIENT_OWNERSHIP')); + engine.register('bob', 'bob-tab', dirty()); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID')); +}); + +test('unregister invalidates that client barrier without revoking other actor tabs', async t => { + const { coordinator: engine } = fixture(t); + engine.register('alice', 'a', clean()); + engine.register('alice', 'another-tab', clean()); + engine.register('bob', 'b', clean()); + const barrier = engine.beginBarrier('alice'); + assert.throws(() => engine.unregister('bob', 'a'), code('CLIENT_OWNERSHIP')); + engine.unregister('alice', 'a'); + assert.deepEqual(engine.state().clients.map(client => client.clientId), ['another-tab', 'b']); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID')); + assert.deepEqual(engine.unregister('alice', 'a'), { unregistered: true }); +}); + +test('an acknowledgement may not forge document version or omit frozen documents', t => { + const { coordinator: engine } = fixture(t); + engine.register('alice', 'a', clean()); + let barrier = engine.beginBarrier('alice'); + assert.throws(() => engine.acknowledge('alice', barrier.id, 'a', clean(0)), code('VERSION_CHANGED')); + barrier = engine.beginBarrier('alice'); + assert.throws(() => engine.acknowledge('alice', barrier.id, 'a', { documents: [] }), code('VERSION_CHANGED')); +}); + +test('disk mutation after barrier start refuses snapshot even with clean unchanged editor versions', async t => { + const { coordinator: engine, workspaceRoot, stateDirectory } = fixture(t); + const barrier = acknowledged(engine); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'changed by external process'); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('DISK_CHANGED')); + assert.equal(engine.state().revision, 0); + assert.deepEqual(fs.readdirSync(path.join(stateDirectory, 'snapshots')), []); +}); + +test('mutation while snapshot blobs are materialized is detected by the second capture', async t => { + const { coordinator: engine, workspaceRoot } = fixture(t); + const barrier = acknowledged(engine); + const capture = engine._capture.bind(engine); + let calls = 0; + engine._capture = () => { + const captured = capture(); + if (++calls === 1) fs.writeFileSync(path.join(workspaceRoot, 'new-after-read.ts'), 'race'); + return captured; + }; + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('DISK_CHANGED')); + assert.equal(engine.state().revision, 0); +}); + +test('snapshot revisions and exact content recover after restart and stale journal repair', async t => { + const { coordinator: engine, workspaceRoot, stateDirectory, options } = fixture(t); + const first = await engine.commitBarrier('alice', acknowledged(engine).id); + const oldJournal = fs.readFileSync(path.join(stateDirectory, 'journal.json')); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'revision two'); + const second = await engine.commitBarrier('alice', acknowledged(engine).id); + assert.equal(second.previousId, first.id); + fs.writeFileSync(path.join(stateDirectory, 'journal.json'), oldJournal); + fs.writeFileSync(path.join(stateDirectory, 'journal.json.crash.tmp'), 'partial JSON'); + fs.writeFileSync(path.join(stateDirectory, 'snapshots', 'uncommitted.tmp'), 'partial JSON'); + const recovered = new Coordinator(options); + assert.equal(recovered.state().revision, 2); + assert.equal(recovered.state().latestSnapshot.id, second.id); + assert.equal(JSON.parse(fs.readFileSync(path.join(stateDirectory, 'journal.json'))).latestId, second.id); + assert.deepEqual(recovered.state().clients, []); + assert.deepEqual(recovered.state().barriers, []); + const third = await recovered.commitBarrier('alice', acknowledged(recovered).id); + assert.equal(third.revision, 3); + assert.equal(third.previousId, second.id); +}); + +test('commit response loss is safely retried once before and after backend restart', async t => { + const { coordinator: engine, options } = fixture(t); + const barrier = acknowledged(engine); + const snapshot = await engine.commitBarrier('alice', barrier.id); + assert.deepEqual(await engine.commitBarrier('alice', barrier.id), snapshot); + const recovered = new Coordinator(options); + assert.deepEqual(await recovered.commitBarrier('alice', barrier.id), snapshot); + assert.equal(recovered.state().revision, 1); + await assert.rejects(recovered.commitBarrier('bob', barrier.id), code('BARRIER_OWNERSHIP')); +}); + +test('crash after manifest persistence but before journal update recovers a single committed snapshot', async t => { + const { coordinator: engine, options, stateDirectory } = fixture(t); + const barrier = acknowledged(engine); + const rename = fs.renameSync; + let journalWrites = 0; + fs.renameSync = (from, to) => { + if (to === path.join(engine.stateDirectory, 'journal.json') && ++journalWrites === 2) throw Object.assign(new Error('injected journal disk failure'), { code: 'EIO' }); + return rename(from, to); + }; + try { await assert.rejects(engine.commitBarrier('alice', barrier.id), /injected journal disk failure/); } + finally { fs.renameSync = rename; } + assert.equal(JSON.parse(fs.readFileSync(path.join(stateDirectory, 'journal.json'))).revision, 0); + const recovered = new Coordinator(options); + const snapshot = await recovered.commitBarrier('alice', barrier.id); + assert.equal(snapshot.revision, 1); + assert.equal(recovered.state().revision, 1); + assert.equal(fs.readdirSync(path.join(stateDirectory, 'snapshots')).filter(name => name.endsWith('.json')).length, 1); +}); + +test('recovery refuses content-addressed object tampering and never reconstructs it from newer source', async t => { + const { coordinator: engine, stateDirectory, options } = fixture(t); + const snapshot = await engine.commitBarrier('alice', acknowledged(engine).id); + const object = path.join(stateDirectory, 'objects', snapshot.files[0].sha256); + fs.chmodSync(object, 0o600); + fs.writeFileSync(object, 'tampered'); + assert.throws(() => new Coordinator(options), code('STATE_CORRUPT')); +}); + +test('rejects state inside source, symlink escapes and file URIs outside workspace', t => { + const { coordinator: engine, workspaceRoot, directory } = fixture(t); + assert.throws(() => new Coordinator({ workspaceRoot, stateDirectory: path.join(workspaceRoot, '.state') }), code('UNSAFE_STATE_PATH')); + assert.throws(() => new Coordinator({ workspaceRoot, stateDirectory: directory }), code('UNSAFE_STATE_PATH')); + fs.symlinkSync(workspaceRoot, path.join(directory, 'source-alias')); + assert.throws(() => new Coordinator({ workspaceRoot, stateDirectory: path.join(directory, 'source-alias', 'should-not-create') }), code('UNSAFE_STATE_PATH')); + assert.equal(fs.existsSync(path.join(workspaceRoot, 'should-not-create')), false); + assert.throws(() => engine.register('alice', 'a', { documents: [{ uri: pathToFileURL(path.join(directory, 'outside')).href, version: 1, dirty: false }] }), code('OUTSIDE_WORKSPACE')); + assert.throws(() => engine.register('alice', 'a', { documents: [{ uri: '../outside', version: 1, dirty: false }] }), code('OUTSIDE_WORKSPACE')); + engine.register('alice', 'a', clean()); + fs.writeFileSync(path.join(directory, 'secret'), 'not in source'); + fs.symlinkSync(path.join(directory, 'secret'), path.join(workspaceRoot, 'escape')); + assert.throws(() => engine.beginBarrier('alice'), code('UNSAFE_WORKSPACE_PATH')); + fs.unlinkSync(path.join(workspaceRoot, 'escape')); + fs.symlinkSync(path.join(directory), path.join(workspaceRoot, 'escape-directory')); + assert.throws(() => engine.beginBarrier('alice'), code('UNSAFE_WORKSPACE_PATH')); +}); + +test('document input validation normalizes file URIs and refuses duplicate vectors', t => { + const { coordinator: engine, workspaceRoot } = fixture(t); + assert.throws(() => engine.register('alice', 'a', { documents: [{ uri: 'app.ts', version: NaN, dirty: false }] }), code('INVALID_INPUT')); + assert.throws(() => engine.register('alice', 'a', { documents: [{ uri: 'app.ts', version: 1, dirty: false }, { uri: pathToFileURL(path.join(workspaceRoot, 'app.ts')).href, version: 1, dirty: false }] }), code('INVALID_INPUT')); + const client = engine.register('alice', 'a', { documents: [{ uri: pathToFileURL(path.join(workspaceRoot, 'app.ts')).href, version: 1, dirty: false }, { uri: 'untitled:unsaved', version: 0, dirty: true }] }); + assert.equal(client.documents[0].uri, 'app.ts'); + assert.equal(client.dirty, true); +}); + +test('expired clients and barriers cannot silently disappear into a successful snapshot', async t => { + const { coordinator: engine, advance } = fixture(t); + const barrier = acknowledged(engine); + assert.throws(() => engine.beginBarrier('alice'), code('BARRIER_BUSY')); + advance(CLIENT_TTL_MS); + assert.deepEqual(engine.state().clients, []); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_EXPIRED')); + assert.throws(() => engine.beginBarrier('alice'), code('CLIENT_REQUIRED')); +}); + +test('debug controller tokens are exclusive, redacted, renewable and expire exactly at deadline', t => { + const { coordinator: engine, advance } = fixture(t); + const lease = engine.debugAcquire('alice'); + assert.match(lease.token, /^[a-f0-9]{64}$/); + assert.equal(engine.state().debugController.actorId, 'alice'); + assert.equal('token' in engine.state().debugController, false); + assert.throws(() => engine.debugAcquire('bob'), code('DEBUG_BUSY')); + assert.throws(() => engine.debugAcquire('alice'), code('DEBUG_BUSY')); + assert.throws(() => engine.assertDebugController('bob', lease.token), code('DEBUG_FORBIDDEN')); + advance(10_000); + const renewed = engine.debugAcquire('alice', lease.token); + assert.equal(renewed.token, lease.token); + assert.equal(renewed.expiresAt, lease.expiresAt + 10_000); + advance(DEBUG_LEASE_MS); + assert.throws(() => engine.assertDebugController('alice', lease.token), code('DEBUG_FORBIDDEN')); + const replacement = engine.debugAcquire('bob'); + assert.notEqual(replacement.token, lease.token); + assert.throws(() => engine.debugRelease('alice', lease.token), code('DEBUG_FORBIDDEN')); + engine.debugRelease('bob', replacement.token); + assert.equal(engine.state().debugController, null); +}); + +test('debug transfer rotates token and requires live target; revoke invalidates controller and barriers', async t => { + const { coordinator: engine } = fixture(t); + engine.register('alice', 'a', clean()); + engine.register('bob', 'b', clean()); + const lease = engine.debugAcquire('alice'); + assert.throws(() => engine.debugTransfer('alice', lease.token, 'unconnected'), code('CLIENT_REQUIRED')); + const transferred = engine.debugTransfer('alice', lease.token, 'bob'); + assert.notEqual(transferred.token, lease.token); + assert.throws(() => engine.assertDebugController('alice', lease.token), code('DEBUG_FORBIDDEN')); + assert.throws(() => engine.assertDebugController('bob', lease.token), code('DEBUG_FORBIDDEN')); + engine.assertDebugController('bob', transferred.token); + const barrier = engine.beginBarrier('alice'); + engine.acknowledge('alice', barrier.id, 'a', clean()); + engine.acknowledge('bob', barrier.id, 'b', clean()); + engine.revoke('bob'); + assert.throws(() => engine.assertDebugController('bob', transferred.token), code('DEBUG_FORBIDDEN')); + assert.equal(engine.state().clients.some(client => client.actorId === 'bob'), false); + await assert.rejects(engine.commitBarrier('alice', barrier.id), code('BARRIER_INVALID')); +}); + +test('restart invalidates all prior debug tokens and barriers without overwriting source', async t => { + const { coordinator: engine, options, workspaceRoot } = fixture(t); + const barrier = acknowledged(engine); + const lease = engine.debugAcquire('alice'); + const recovered = new Coordinator(options); + await assert.rejects(recovered.commitBarrier('alice', barrier.id), code('BARRIER_NOT_FOUND')); + assert.throws(() => recovered.assertDebugController('alice', lease.token), code('DEBUG_FORBIDDEN')); + assert.equal(fs.readFileSync(path.join(workspaceRoot, 'app.ts'), 'utf8'), 'export const answer = 42;\n'); +}); + +test('integration state tracks dirty documents, membership and disk without treating heartbeats as edits', async t => { + const { coordinator: engine, workspaceRoot, advance } = fixture(t); + await engine.commitBarrier('alice', acknowledged(engine).id); + const before = engine.inputState(); + assert.equal(before.currentDiskDigest, before.latestSnapshot.digest); + advance(1000); engine.register('alice', 'alice-tab', clean()); + assert.equal(engine.inputState().activityDigest, before.activityDigest); + engine.register('alice', 'alice-tab', dirty(2)); + assert.equal(engine.inputState().dirty, true); + assert.notEqual(engine.inputState().activityDigest, before.activityDigest); + engine.register('alice', 'alice-tab', clean()); + engine.register('bob', 'bob-tab', clean()); + assert.notEqual(engine.inputState().activityDigest, before.activityDigest); + engine.unregister('bob', 'bob-tab'); + fs.writeFileSync(path.join(workspaceRoot, 'app.ts'), 'changed on disk'); + assert.notEqual(engine.inputState().currentDiskDigest, before.currentDiskDigest); + assert.equal(engine.inputState().latestSnapshot.digest, before.latestSnapshot.digest); +}); diff --git a/apps/ide/gateway/README.md b/apps/ide/gateway/README.md new file mode 100644 index 0000000..120ed90 --- /dev/null +++ b/apps/ide/gateway/README.md @@ -0,0 +1,54 @@ +# Workspace authorization gateway + +This separate service protects the Theia HTTP and WebSocket boundary. Start with +`npm ci && npm start` in this directory and environment variables: + +```text +WF_API_URL=http://127.0.0.1:4000 +WF_TENANT_ID=demo +WF_WORKSPACE_GATEWAY_TOKEN= +WF_IDE_PUBLIC_URL=http://127.0.0.1:4400 +WF_IDE_ALLOWED_UPSTREAM_ORIGINS=http://127.0.0.1:4300 +``` + +`POST /launch` accepts a user Bearer token and `{workspaceId}`. The web server +relays this call using its encrypted session, then redirects to the returned +`launchUrl`. The URL contains a 30-second single-use random code, never the user +token. `GET /session?code=...` reauthorizes, consumes the code, sets an opaque +HttpOnly/SameSite cookie and redirects to `/workspaces/:id/`. Use HTTPS in production +for Secure cookies. Proxy/access logs must redact the launch-code query string. + +Every HTTP request and WebSocket handshake calls the control plane's +`POST /internal/workspaces/:id/authorize` with the dedicated service token, +fixed `X-WishForge-Tenant`, and `{userToken, operation}`. Open WebSockets recheck +authorization every second with a 3-second authorization timeout (at most about +4 seconds until a changed grant or unavailable authorization service is observed) +and close on rejection, expiry, moved upstream or unavailable control plane. +User credentials and browser cookies are stripped before proxying. Theia 1.76's +separate `theia-connection-token` is captured from the allowed upstream and kept +server-side for subsequent HTTP/WebSocket proxy requests; it is never forwarded +to the browser. Upstream URLs must +come from the control-plane grant and also match the configured origin allowlist. +Viewers cannot enter the editing surface, even when an upstream mistakenly returns +a viewer grant. Multiplexed Theia services always require edit permission; callers +cannot select a weaker preview operation. + +The production deployment must make Theia inaccessible except through this gateway. +Use one tenant-bound gateway configuration per tenant. Sessions and codes currently +live in process memory; restart requires relaunch and multiple replicas require a +shared session store or affinity. The gateway does not persist OCT rooms or enforce +fine-grained DAP controller leases/save barriers. The scoped collaboration route proxies HTTP/Socket.IO to a dedicated OCT +instance from the grant, using edit authorization on each request and active +socket revocation. It must be the only reachable network entry to that instance; +production CNI isolation still requires an actual cluster test. + +Tests use real local HTTP/WebSocket servers and cover credentials, replay, viewer +denial, upstream allowlisting, origin checks and active connection revocation. The actual Theia asset/service/WebSocket/editor/terminal path was tested through +the real control plane with local development authentication. Production OIDC +login and project-bound collaboration require separate acceptance. + +`WF_COLLABORATION_ALLOWED_UPSTREAM_ORIGINS` is a separate explicit local allowlist. +With `WF_IDE_ALLOWED_SERVICE_NAMESPACE`, managed IDE services must match exactly +`wf-ide-<24 hex>..svc:3000` and collaboration uses that same service +name on 8100. Public clients cannot select the upstream URL. Theia's own process +cookie is cached by upstream and is never forwarded to the collaboration instance. diff --git a/apps/ide/gateway/main.mjs b/apps/ide/gateway/main.mjs new file mode 100644 index 0000000..d4e3862 --- /dev/null +++ b/apps/ide/gateway/main.mjs @@ -0,0 +1,18 @@ +import { createGateway } from './server.mjs'; +import { readFileSync } from 'node:fs'; + +const production = process.env.NODE_ENV === 'production'; +const publicUrl = process.env.WF_IDE_PUBLIC_URL ?? 'http://127.0.0.1:4400'; +if (production && !publicUrl.startsWith('https://')) throw new Error('Production gateway requires HTTPS public URL'); +const gateway = createGateway({ + publicUrl, + apiOrigin: process.env.WF_API_URL ?? 'http://127.0.0.1:4000', + tenantId: process.env.WF_TENANT_ID ?? 'demo', + serviceToken: process.env.WF_WORKSPACE_GATEWAY_TOKEN, + allowedUpstreamOrigins: (process.env.WF_IDE_ALLOWED_UPSTREAM_ORIGINS ?? (production ? '' : 'http://127.0.0.1:4300')).split(',').filter(Boolean), + allowedServiceNamespace: process.env.WF_IDE_ALLOWED_SERVICE_NAMESPACE, + allowedCollaborationOrigins: (process.env.WF_COLLABORATION_ALLOWED_UPSTREAM_ORIGINS ?? '').split(',').filter(Boolean), + assertionPrivateKey: process.env.WF_IDE_GATEWAY_PRIVATE_KEY_FILE ? readFileSync(process.env.WF_IDE_GATEWAY_PRIVATE_KEY_FILE, 'utf8') : undefined, +}); +gateway.server.listen(Number(process.env.WF_IDE_GATEWAY_PORT ?? 4400), process.env.WF_IDE_GATEWAY_HOST ?? '127.0.0.1', () => console.log(`Workspace gateway listening at ${publicUrl}`)); +for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, async () => { await gateway.close(); process.exit(0); }); diff --git a/apps/ide/gateway/package-lock.json b/apps/ide/gateway/package-lock.json new file mode 100644 index 0000000..1d2610e --- /dev/null +++ b/apps/ide/gateway/package-lock.json @@ -0,0 +1,36 @@ +{ + "name": "@wishforge/ide-gateway", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@wishforge/ide-gateway", + "version": "0.1.0", + "dependencies": { + "ws": "8.21.0" + } + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/apps/ide/gateway/package.json b/apps/ide/gateway/package.json new file mode 100644 index 0000000..b3781c9 --- /dev/null +++ b/apps/ide/gateway/package.json @@ -0,0 +1,8 @@ +{ + "name": "@wishforge/ide-gateway", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { "start": "node main.mjs", "test": "node --test test/*.test.mjs" }, + "dependencies": { "ws": "8.21.0" } +} diff --git a/apps/ide/gateway/server.mjs b/apps/ide/gateway/server.mjs new file mode 100644 index 0000000..c38d9d0 --- /dev/null +++ b/apps/ide/gateway/server.mjs @@ -0,0 +1,215 @@ +import http from 'node:http'; +import https from 'node:https'; +import { randomBytes, timingSafeEqual } from 'node:crypto'; +import { WebSocket, WebSocketServer } from 'ws'; +import assertions from '../security/assertions.cjs'; + +const COOKIE = 'WF_IDE_SESSION'; +const ID = /^[a-zA-Z0-9_-]{1,128}$/; +const EDIT_ROLES = new Set(['owner', 'admin', 'maintainer', 'developer', 'editor']); +class HttpError extends Error { constructor(status, message) { super(message); this.status = status; } } +const random = () => randomBytes(32).toString('base64url'); + +export function createGateway(config) { + const publicUrl = new URL(config.publicUrl); + if (!['http:', 'https:'].includes(publicUrl.protocol) || publicUrl.pathname !== '/' || publicUrl.search || publicUrl.username || publicUrl.password) throw new Error('publicUrl must be an HTTP(S) origin'); + if (!ID.test(config.tenantId) || !config.serviceToken) throw new Error('A fixed tenantId and gateway serviceToken are required'); + const upstreamOrigins = new Set(config.allowedUpstreamOrigins); + const collaborationOrigins = new Set(config.allowedCollaborationOrigins ?? []); + const serviceNamespace = config.allowedServiceNamespace; + if (serviceNamespace && (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(serviceNamespace) || serviceNamespace.length > 63)) throw new Error('Invalid service namespace'); + if (!upstreamOrigins.size && !serviceNamespace) throw new Error('Explicit upstream allowlist required'); + const fetchImpl = config.fetchImpl ?? fetch; + const sessions = new Map(); + const launches = new Map(); + // Theia's own process token is distinct from the caller's authentication. + // Keep it server-side, scoped to an allowed upstream, never in browser cookies. + const upstreamTokens = new Map(); + const sockets = new Set(); + const workspaceSockets=new Map(); + const rawSockets = new Set(); + const sessionTtl = Math.min(config.sessionTtlMs ?? 900000, 900000); + const pollMs = Math.min(config.reauthorizeMs ?? 1000, 1000); + const now = () => Date.now(); + const purge = () => { + for (const map of [sessions, launches]) for (const [key, value] of map) if (value.expiresAt <= now()) map.delete(key); + }; + const timer = setInterval(purge, 5000); timer.unref(); + const wss = new WebSocketServer({ noServer: true, maxPayload: 16 * 1024 * 1024, perMessageDeflate: false }); + + async function authorize(workspaceId, userToken, operation, collaboration = false) { + if (!ID.test(workspaceId) || !userToken || userToken.length > 16384) throw new HttpError(401, 'Authentication required'); + let response; + try { + response = await fetchImpl(`${config.apiOrigin}/internal/workspaces/${encodeURIComponent(workspaceId)}/authorize`, { + method: 'POST', + headers: { authorization: `Bearer ${config.serviceToken}`, 'content-type': 'application/json', 'X-WishForge-Tenant': config.tenantId }, + body: JSON.stringify({ userToken, operation }), signal: AbortSignal.timeout(3000), redirect: 'error', + }); + } catch { throw new HttpError(503, 'Workspace authorization unavailable'); } + if (!response.ok) throw new HttpError([401, 403, 404].includes(response.status) ? response.status : 503, 'Workspace access denied'); + const payload = await response.json(); + const grant = payload.data ?? payload; + if (grant.tenantId !== config.tenantId || grant.workspaceId !== workspaceId || !grant.projectId || !EDIT_ROLES.has(grant.role)) throw new HttpError(403, 'Workspace grant mismatch'); + let upstream; + try { upstream = new URL(collaboration ? grant.collaborationUpstreamUrl : grant.upstreamUrl); } catch { throw new HttpError(502, 'Invalid workspace upstream'); } + const origins = collaboration ? collaborationOrigins : upstreamOrigins; + const serviceAllowed = serviceNamespace && upstream.protocol === 'http:' && upstream.port === (collaboration ? '8100' : '3000') && new RegExp(`^wf-ide-[a-f0-9]{24}\\.${serviceNamespace}\\.svc(?:\\.cluster\\.local)?$`).test(upstream.hostname); + if ((!origins.has(upstream.origin) && !serviceAllowed) || !['http:', 'https:'].includes(upstream.protocol) || upstream.username || upstream.password || upstream.search || upstream.hash) throw new HttpError(502, 'Workspace upstream is not permitted'); + return { ...grant, upstream }; + } + function tokenFor(req, workspaceId) { + const authorization = req.headers.authorization; + if (authorization?.startsWith('Bearer ')) return { userToken: authorization.slice(7), expiresAt: Number.MAX_SAFE_INTEGER }; + const opaque = req.headers.cookie?.split(';').map(v => v.trim()).find(v => v.startsWith(`${COOKIE}=`))?.slice(COOKIE.length + 1); + const session = opaque && sessions.get(opaque); + if (!session || session.expiresAt <= now() || session.workspaceId !== workspaceId) throw new HttpError(401, 'Launch an authenticated IDE session'); + return session; + } + function originCheck(req, required = false) { + if ((required && !req.headers.origin) || (req.headers.origin && req.headers.origin !== publicUrl.origin)) throw new HttpError(403, 'Origin not allowed'); + } + function route(req) { + const parsed = new URL(req.url, publicUrl); + const match = parsed.pathname.match(/^\/workspaces\/([a-zA-Z0-9_-]{1,128})(\/.*)?$/); + if (!match) throw new HttpError(404, 'Workspace route not found'); + let suffix = match[2] ?? '/'; + const collaboration = suffix === '/collaboration' || suffix.startsWith('/collaboration/'); + if (collaboration) suffix = suffix.slice('/collaboration'.length) || '/'; + // Multiplexed Theia services need edit permission. Callers cannot downgrade + // this to preview by supplying a query parameter or header. + const operation = collaboration ? 'edit' : /\/terminals?(?:\/|$)/.test(suffix) ? 'terminal' : /\/debug(?:\/|$)/.test(suffix) ? 'debug' : 'edit'; + return { workspaceId: match[1], suffix, query: parsed.search, operation, collaboration }; + } + function targetFor(grant, routing) { + const target = new URL(grant.upstream); + target.pathname = `${target.pathname.replace(/\/$/, '')}${routing.suffix}`; + target.search = routing.query; + return target; + } + function proxyHeaders(req, target, grant) { + const headers = { ...req.headers }; + for (const key of Object.keys(headers)) if (['authorization', 'cookie', 'connection', 'upgrade', 'proxy-authorization', 'proxy-authenticate', 'te', 'trailer', 'transfer-encoding'].includes(key) || key.startsWith('x-forwarded-') || key.startsWith('x-wishforge-') || key.startsWith('sec-websocket-')) delete headers[key]; + headers.host = target.host; + headers.origin = target.origin; + headers['x-forwarded-host'] = publicUrl.host; + headers['x-forwarded-proto'] = publicUrl.protocol.slice(0, -1); + headers['x-wishforge-tenant'] = grant.tenantId; + headers['x-wishforge-workspace'] = grant.workspaceId; + if (config.assertionPrivateKey) headers['x-wishforge-actor-assertion'] = assertions.signAssertion(config.assertionPrivateKey, grant); + const token = upstreamTokens.get(grant.upstream.href); + if (token) headers.cookie = `theia-connection-token=${token}`; + return headers; + } + function fail(res, error) { + if (res.headersSent) { res.destroy(); return; } + res.writeHead(error.status ?? 500, { 'content-type': 'application/json', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }); + res.end(JSON.stringify({ error: error.status ? error.message : 'Gateway error' })); + } + async function readJson(req) { + let body = ''; + for await (const chunk of req) { body += chunk; if (body.length > 2048) throw new HttpError(413, 'Request too large'); } + try { return JSON.parse(body); } catch { throw new HttpError(400, 'Invalid JSON'); } + } + const server = http.createServer(async (req, res) => { + try { + const url = new URL(req.url, publicUrl); + if (url.pathname === '/healthz' && req.method === 'GET') { res.writeHead(200); res.end('ok'); return; } + if (['/internal/integration-state','/internal/lifecycle-state'].includes(url.pathname) && req.method === 'POST') { + const lifecycle=url.pathname==='/internal/lifecycle-state'; + const supplied=req.headers.authorization?.startsWith('Bearer ')?req.headers.authorization.slice(7):''; + const expected=Buffer.from(config.serviceToken),actual=Buffer.from(supplied); + if(actual.length!==expected.length||!timingSafeEqual(actual,expected)||!config.assertionPrivateKey)throw new HttpError(401,'Integration service authentication required'); + const body=await readJson(req); + if(body.tenantId!==config.tenantId||!ID.test(body.workspaceId??'')||(!lifecycle&&!ID.test(body.runId??'')))throw new HttpError(400,'Invalid integration scope'); + const authorized=await fetchImpl(`${config.apiOrigin}/internal/workspaces/${body.workspaceId}/${lifecycle?'lifecycle-authorize':'integration-authorize'}`,{method:'POST',headers:{authorization:`Bearer ${config.serviceToken}`,'content-type':'application/json','X-WishForge-Tenant':config.tenantId},body:JSON.stringify(lifecycle?{}:{runId:body.runId,generation:body.generation,revision:body.revision}),redirect:'error',signal:AbortSignal.timeout(3000)}); + if(!authorized.ok)throw new HttpError(403,'Integration scope denied'); + const payload=await authorized.json();const grant=payload.data??payload; + if(grant.tenantId!==config.tenantId||grant.workspaceId!==body.workspaceId||grant.purpose!==(lifecycle?'workspace-lifecycle':'integration-state'))throw new HttpError(403,'Integration grant mismatch'); + const target=new URL(grant.upstreamUrl); + const managed=serviceNamespace&&target.protocol==='http:'&&target.port==='3000'&&new RegExp(`^wf-ide-[a-f0-9]{24}\\.${serviceNamespace}\\.svc(?:\\.cluster\\.local)?$`).test(target.hostname); + if((!upstreamOrigins.has(target.origin)&&!managed)||target.username||target.password||target.search||target.hash)throw new HttpError(502,'Integration upstream denied'); + const response=await fetchImpl(new URL(lifecycle?'/_wishforge/lifecycle/state':'/_wishforge/integration/state',target),{headers:{'x-wishforge-actor-assertion':assertions.signAssertion(config.assertionPrivateKey,grant)},redirect:'error',signal:AbortSignal.timeout(10000)}); + if(!response.ok)throw new HttpError(503,'Workspace input state unavailable'); + res.writeHead(200,{'content-type':'application/json','cache-control':'no-store'});const receipt=await response.json();res.end(JSON.stringify(lifecycle?{...receipt,gatewayConnections:workspaceSockets.get(body.workspaceId)?.size??0}:receipt));return; + } + if (url.pathname === '/launch' && req.method === 'POST') { + originCheck(req); + const userToken = req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : undefined; + const body = await readJson(req); + if (!body || Object.keys(body).some(key => key !== 'workspaceId') || !ID.test(body.workspaceId ?? '')) throw new HttpError(400, 'workspaceId is required'); + await authorize(body.workspaceId, userToken, 'edit'); + purge(); if (launches.size >= 1000 || sessions.size >= 1000) throw new HttpError(429, 'Session capacity reached'); + const code = random(); launches.set(code, { workspaceId: body.workspaceId, userToken, expiresAt: now() + 30000 }); + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }); + res.end(JSON.stringify({ launchUrl: `${publicUrl.origin}/session?code=${encodeURIComponent(code)}`, expiresIn: 30 })); return; + } + if (url.pathname === '/session' && req.method === 'GET') { + const code = url.searchParams.get('code'); const launch = launches.get(code); launches.delete(code); + if (!launch || launch.expiresAt <= now()) throw new HttpError(401, 'Launch code is invalid or expired'); + await authorize(launch.workspaceId, launch.userToken, 'edit'); + const opaque = random(); sessions.set(opaque, { ...launch, expiresAt: now() + sessionTtl }); + res.writeHead(303, { + location: `/workspaces/${launch.workspaceId}/`, + 'set-cookie': `${COOKIE}=${opaque}; HttpOnly; SameSite=Strict; Path=/workspaces/${launch.workspaceId}/; Max-Age=${Math.floor(sessionTtl / 1000)}${publicUrl.protocol === 'https:' ? '; Secure' : ''}`, + 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', + }); res.end(); return; + } + originCheck(req); + const routing = route(req); + const session = tokenFor(req, routing.workspaceId); + const grant = await authorize(routing.workspaceId, session.userToken, routing.operation, routing.collaboration); + const target = targetFor(grant, routing); + const proxy = (target.protocol === 'https:' ? https : http).request(target, { method: req.method, headers: proxyHeaders(req, target, grant) }, upstream => { + const headers = { ...upstream.headers, 'referrer-policy': 'no-referrer', 'cache-control': 'no-store' }; + for (const cookie of upstream.headers['set-cookie'] ?? []) { + const token = /^theia-connection-token=([^;\s]{1,512})(?:;|$)/.exec(cookie)?.[1]; + if (token) upstreamTokens.set(grant.upstream.href, token); + } + delete headers['set-cookie']; + if (headers.location) { + const location = new URL(headers.location, target); + if (location.origin === target.origin) headers.location = `/workspaces/${routing.workspaceId}${routing.collaboration ? '/collaboration' : ''}${location.pathname}${location.search}${location.hash}`; + } + res.writeHead(upstream.statusCode ?? 502, headers); upstream.pipe(res); + }); + proxy.on('error', () => fail(res, new HttpError(502, 'Workspace upstream unavailable'))); + proxy.setTimeout(30000, () => proxy.destroy()); + req.on('aborted', () => proxy.destroy()); res.on('close', () => proxy.destroy()); req.pipe(proxy); + } catch (error) { fail(res, error); } + }); + server.on('connection', socket => { rawSockets.add(socket); socket.once('close', () => rawSockets.delete(socket)); }); + server.on('upgrade', async (req, socket, head) => { + socket.on('error', () => {}); + try { + originCheck(req, !req.headers.authorization); + const routing = route(req); const session = tokenFor(req, routing.workspaceId); + const grant = await authorize(routing.workspaceId, session.userToken, routing.operation, routing.collaboration); + const target = targetFor(grant, routing); target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:'; + const protocols = req.headers['sec-websocket-protocol']?.split(',').map(p => p.trim()).filter(Boolean); + const upstream = new WebSocket(target, protocols, { headers: proxyHeaders(req, grant.upstream, grant), maxPayload: 16 * 1024 * 1024, handshakeTimeout: 5000, perMessageDeflate: false }); + let accepted = false; + upstream.once('error', () => { if (!accepted) socket.destroy(); }); + socket.once('close', () => { if (!accepted) upstream.terminate(); }); + upstream.once('open', () => wss.handleUpgrade(req, socket, head, client => { + accepted = true; sockets.add(client); + const workspaceSet=workspaceSockets.get(routing.workspaceId)??new Set();workspaceSockets.set(routing.workspaceId,workspaceSet);workspaceSet.add(client); + const close = () => { clearInterval(poll); sockets.delete(client);workspaceSet.delete(client);if(!workspaceSet.size)workspaceSockets.delete(routing.workspaceId); client.terminate(); upstream.terminate(); }; + client.on('message', (data, binary) => { if (upstream.readyState === WebSocket.OPEN) upstream.send(data, { binary }); }); + upstream.on('message', (data, binary) => { if (client.readyState === WebSocket.OPEN) client.send(data, { binary }); }); + client.on('close', close); upstream.on('close', close); client.on('error', close); upstream.on('error', close); + let checking = false; + const poll = setInterval(async () => { + if (checking) return; checking = true; + try { + if (session.expiresAt <= now()) throw new Error('Session expired'); + const fresh = await authorize(routing.workspaceId, session.userToken, routing.operation, routing.collaboration); + if (fresh.upstream.href !== grant.upstream.href) throw new Error('Workspace moved'); + } catch { close(); } finally { checking = false; } + }, pollMs); poll.unref(); + })); + } catch (error) { socket.end(`HTTP/1.1 ${error.status ?? 500} Access Denied\r\nConnection: close\r\n\r\n`); } + }); + server.on('close', () => { clearInterval(timer); for (const client of sockets) client.terminate(); wss.close(); }); + return { server, close: async () => { for (const client of sockets) client.terminate(); for (const socket of rawSockets) socket.destroy(); await new Promise(resolve => server.close(resolve)); }, sessionCount: () => sessions.size }; +} diff --git a/apps/ide/gateway/test/gateway.test.mjs b/apps/ide/gateway/test/gateway.test.mjs new file mode 100644 index 0000000..6060b7b --- /dev/null +++ b/apps/ide/gateway/test/gateway.test.mjs @@ -0,0 +1,156 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { once } from 'node:events'; +import { WebSocket, WebSocketServer } from 'ws'; +import { createGateway } from '../server.mjs'; +import { generateKeyPairSync } from 'node:crypto'; +import assertions from '../../security/assertions.cjs'; + +async function listen(server) { + server.listen(0, '127.0.0.1'); await once(server, 'listening'); + return `http://127.0.0.1:${server.address().port}`; +} +async function fixture(t, options = {}) { + const state = { revoked: false, role: 'developer', calls: [], receivedHeaders: undefined }; + const upstream = http.createServer((req, res) => { state.receivedHeaders = req.headers; + if (state.connectionToken) { + res.setHeader('set-cookie', `theia-connection-token=${state.connectionToken}; HttpOnly; SameSite=Strict; Path=/`); + if (req.url === '/protected' && req.headers.cookie !== `theia-connection-token=${state.connectionToken}`) { res.writeHead(403); res.end(); return; } + } + res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ path: req.url })); }); + const websocket = new WebSocketServer({ server: upstream }); + websocket.on('connection', socket => socket.on('message', (data, binary) => socket.send(data, { binary }))); + const upstreamUrl = await listen(upstream); + state.upstreamUrl = upstreamUrl; + state.collaborationUpstreamUrl = upstreamUrl; + const auth = http.createServer(async (req, res) => { + let raw = ''; for await (const part of req) raw += part; + const body = JSON.parse(raw); state.calls.push({ path: req.url, headers: req.headers, body }); + if (state.revoked || (req.url.endsWith('/lifecycle-authorize') ? false : req.url.endsWith('/integration-authorize') ? body.runId !== 'run-1' : body.userToken !== 'user-token')) { res.writeHead(403); res.end(); return; } + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ data: { tenantId: 'tenant-a', projectId: 'p1', workspaceId: 'w1', userId:'authenticated-user', role: state.role, purpose:req.url.endsWith('/lifecycle-authorize')?'workspace-lifecycle':req.url.endsWith('/integration-authorize')?'integration-state':undefined, upstreamUrl: state.upstreamUrl, collaborationUpstreamUrl: state.collaborationUpstreamUrl } })); + }); + const apiOrigin = await listen(auth); + // Reserve a local port, then bind the gateway with its actual public origin. + const reservation = http.createServer(); const publicUrl = await listen(reservation); await new Promise(r => reservation.close(r)); + const gateway = createGateway({ publicUrl, apiOrigin, tenantId: 'tenant-a', serviceToken: 'gateway-secret', allowedUpstreamOrigins: [upstreamUrl], allowedCollaborationOrigins:[upstreamUrl], assertionPrivateKey:options.privateKey, reauthorizeMs: 50 }); + gateway.server.listen(Number(new URL(publicUrl).port), '127.0.0.1'); await once(gateway.server, 'listening'); + t.after(async () => { + await gateway.close(); + for (const socket of websocket.clients) socket.terminate(); + websocket.close(); + await Promise.all([new Promise(r => upstream.close(r)), new Promise(r => auth.close(r))]); + }); + const requestLaunch = () => fetch(`${publicUrl}/launch`, { method: 'POST', headers: { authorization: 'Bearer user-token', 'content-type': 'application/json' }, body: JSON.stringify({ workspaceId: 'w1' }) }); + async function session() { + const response = await requestLaunch(); assert.equal(response.status, 200); + const { launchUrl } = await response.json(); + assert.ok(!launchUrl.includes('user-token')); + const exchanged = await fetch(launchUrl, { redirect: 'manual' }); assert.equal(exchanged.status, 303); + return { launchUrl, exchanged, cookie: exchanged.headers.get('set-cookie').split(';')[0] }; + } + return { state, publicUrl, requestLaunch, session }; +} + +test('requires authentication, exchanges a one-time code, and never forwards bearer/cookie', async t => { + const f = await fixture(t); + assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`)).status, 401); + const s = await f.session(); + assert.match(s.exchanged.headers.get('set-cookie'), /HttpOnly/); + assert.match(s.exchanged.headers.get('set-cookie'), /SameSite=Strict/); + assert.equal(s.exchanged.headers.get('referrer-policy'), 'no-referrer'); + assert.equal((await fetch(s.launchUrl, { redirect: 'manual' })).status, 401); + const response = await fetch(`${f.publicUrl}/workspaces/w1/file?name=test`, { headers: { cookie: s.cookie } }); + assert.equal(response.status, 200); assert.deepEqual(await response.json(), { path: '/file?name=test' }); + assert.equal(f.state.receivedHeaders.authorization, undefined); assert.equal(f.state.receivedHeaders.cookie, undefined); + assert.equal(f.state.receivedHeaders['x-wishforge-tenant'], 'tenant-a'); + assert.ok(f.state.calls.every(c => c.headers.authorization === 'Bearer gateway-secret' && c.headers['x-wishforge-tenant'] === 'tenant-a')); + assert.equal((await fetch(`${f.publicUrl}/workspaces/w2/`, { headers: { cookie: s.cookie } })).status, 401); +}); + +test('viewer cannot obtain edit access and caller cannot choose an upstream or downgrade operation', async t => { + const f = await fixture(t); f.state.role = 'viewer'; + assert.equal((await f.requestLaunch()).status, 403); + f.state.role = 'developer'; f.state.upstreamUrl = 'http://169.254.169.254/'; + assert.equal((await f.requestLaunch()).status, 502); + const malformed = await fetch(`${f.publicUrl}/launch`, { method: 'POST', headers: { authorization: 'Bearer user-token', 'content-type': 'application/json' }, body: JSON.stringify({ workspaceId: 'w1', upstreamUrl: 'http://evil.invalid' }) }); + assert.equal(malformed.status, 400); + await fetch(`${f.publicUrl}/workspaces/w1/?operation=preview`, { headers: { authorization: 'Bearer user-token' } }); + assert.equal(f.state.calls.at(-1).body.operation, 'edit'); +}); + +test('HTTP rechecks revocation and rejects cross-origin cookie requests', async t => { + const f = await fixture(t); const s = await f.session(); + assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: s.cookie, origin: 'https://attacker.invalid' } })).status, 403); + f.state.revoked = true; + assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: s.cookie } })).status, 403); +}); + +test('preserves the upstream Theia process token server-side without forwarding client cookies', async t => { + const f = await fixture(t); f.state.connectionToken = 'server-only-process-token'; const s = await f.session(); + const first = await fetch(`${f.publicUrl}/workspaces/w1/`, { headers: { cookie: `${s.cookie}; unrelated=secret` } }); + assert.equal(first.status, 200); assert.equal(first.headers.get('set-cookie'), null); + const protectedResponse = await fetch(`${f.publicUrl}/workspaces/w1/protected`, { headers: { cookie: `${s.cookie}; theia-connection-token=attacker-value` } }); + assert.equal(protectedResponse.status, 200); + assert.equal(f.state.receivedHeaders.cookie, 'theia-connection-token=server-only-process-token'); +}); + +test('gateway signs the API-authorized actor and strips forged workspace identity headers',async t=>{ + const pair=generateKeyPairSync('ed25519');const f=await fixture(t,{privateKey:pair.privateKey.export({type:'pkcs8',format:'pem'})});const s=await f.session(); + const response=await fetch(`${f.publicUrl}/workspaces/w1/`,{headers:{cookie:s.cookie,'x-wishforge-actor-assertion':'forged','x-wishforge-user':'attacker'}}); + assert.equal(response.status,200); + const who=assertions.verifyAssertion(pair.publicKey.export({type:'spki',format:'pem'}),f.state.receivedHeaders['x-wishforge-actor-assertion'],{tenantId:'tenant-a',workspaceId:'w1'}); + assert.equal(who.actorId,'authenticated-user');assert.equal(f.state.receivedHeaders['x-wishforge-user'],undefined); +}); + +test('WebSocket traffic is authenticated and a revoked member is disconnected', { timeout: 5000 }, async t => { + const f = await fixture(t); const s = await f.session(); + const ws = new WebSocket(`${f.publicUrl.replace('http:', 'ws:')}/workspaces/w1/services`, { origin: f.publicUrl, headers: { cookie: s.cookie } }); + await once(ws, 'open'); ws.send('editor-frame'); + const [frame] = await once(ws, 'message'); assert.equal(frame.toString(), 'editor-frame'); + const closed = once(ws, 'close'); f.state.revoked = true; await closed; + assert.ok(f.state.calls.length >= 4); +}); + +test('collaboration HTTP/WS stays behind workspace edit authorization and cannot select another upstream', {timeout:5000}, async t => { + const f=await fixture(t);const s=await f.session(); + const reply=await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/meta`,{headers:{cookie:s.cookie,'x-oct-client':'test'}}); + assert.equal(reply.status,200);assert.deepEqual(await reply.json(),{path:'/api/meta'}); + assert.equal(f.state.calls.at(-1).body.operation,'edit'); + assert.equal(f.state.receivedHeaders['x-oct-client'],'test'); + const ws=new WebSocket(`${f.publicUrl.replace('http:','ws:')}/workspaces/w1/collaboration/socket.io/`,{origin:f.publicUrl,headers:{cookie:s.cookie}}); + await once(ws,'open');ws.send('room-frame');const [frame]=await once(ws,'message');assert.equal(frame.toString(),'room-frame'); + const closed=once(ws,'close');f.state.revoked=true;await closed; + f.state.revoked=false;f.state.collaborationUpstreamUrl='http://169.254.169.254/'; + assert.equal((await fetch(`${f.publicUrl}/workspaces/w1/collaboration/api/meta`,{headers:{cookie:s.cookie}})).status,502); +}); + + +test('integration state relay is service authenticated, scope checked and purpose restricted', async t => { + const pair=generateKeyPairSync('ed25519'); + const f=await fixture(t,{privateKey:pair.privateKey.export({type:'pkcs8',format:'pem'})}); + const request=(token,extra={})=>fetch(`${f.publicUrl}/internal/integration-state`,{method:'POST',headers:{authorization:`Bearer ${token}`,'content-type':'application/json'},body:JSON.stringify({tenantId:'tenant-a',workspaceId:'w1',runId:'run-1',revision:1,generation:'generation-one',...extra})}); + assert.equal((await request('user-token')).status,401); + assert.equal((await request('gateway-secret',{tenantId:'tenant-b'})).status,400); + assert.equal((await request('gateway-secret',{runId:'other-run'})).status,403); + const response=await request('gateway-secret');assert.equal(response.status,200); + assert.deepEqual(await response.json(),{path:'/_wishforge/integration/state'}); + const token=f.state.receivedHeaders['x-wishforge-actor-assertion']; + const key=pair.publicKey.export({type:'spki',format:'pem'}); + assert.equal(assertions.verifyAssertion(key,token,{tenantId:'tenant-a',workspaceId:'w1',purpose:'integration-state'}).purpose,'integration-state'); + assert.throws(()=>assertions.verifyAssertion(key,token,{tenantId:'tenant-a',workspaceId:'w1'}),/PURPOSE/); + f.state.upstreamUrl='http://169.254.169.254/';assert.equal((await request('gateway-secret')).status,502); + f.state.revoked=true;assert.equal((await request('gateway-secret')).status,403); +}); + + +test('lifecycle inspection is read-only scoped and accounts for every live workspace socket',async t=>{ + const pair=generateKeyPairSync('ed25519');const f=await fixture(t,{privateKey:pair.privateKey.export({type:'pkcs8',format:'pem'})}); + const inspect=()=>fetch(`${f.publicUrl}/internal/lifecycle-state`,{method:'POST',headers:{authorization:'Bearer gateway-secret','content-type':'application/json'},body:JSON.stringify({tenantId:'tenant-a',workspaceId:'w1'})}); + let response=await inspect();assert.equal(response.status,200);assert.deepEqual(await response.json(),{path:'/_wishforge/lifecycle/state',gatewayConnections:0}); + const key=pair.publicKey.export({type:'spki',format:'pem'});const token=f.state.receivedHeaders['x-wishforge-actor-assertion']; + assert.equal(assertions.verifyAssertion(key,token,{tenantId:'tenant-a',workspaceId:'w1',purpose:'workspace-lifecycle'}).purpose,'workspace-lifecycle');assert.throws(()=>assertions.verifyAssertion(key,token,{tenantId:'tenant-a',workspaceId:'w1'}),/PURPOSE/); + const session=await f.session();const ws=new WebSocket(`${f.publicUrl.replace('http:','ws:')}/workspaces/w1/services`,{origin:f.publicUrl,headers:{cookie:session.cookie}});await once(ws,'open'); + response=await inspect();assert.equal((await response.json()).gatewayConnections,1);ws.close();await once(ws,'close');response=await inspect();assert.equal((await response.json()).gatewayConnections,0); +}); diff --git a/apps/ide/package-lock.json b/apps/ide/package-lock.json new file mode 100644 index 0000000..ee423b4 --- /dev/null +++ b/apps/ide/package-lock.json @@ -0,0 +1,12978 @@ +{ + "name": "@wishforge/ide", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@wishforge/ide", + "version": "0.1.0", + "dependencies": { + "@theia/callhierarchy": "1.76.0", + "@theia/collaboration": "1.76.0", + "@theia/core": "1.76.0", + "@theia/debug": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/editor-preview": "1.76.0", + "@theia/file-search": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/markers": "1.76.0", + "@theia/messages": "1.76.0", + "@theia/mini-browser": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/navigator": "1.76.0", + "@theia/outline-view": "1.76.0", + "@theia/plugin-ext": "1.76.0", + "@theia/plugin-ext-vscode": "1.76.0", + "@theia/preferences": "1.76.0", + "@theia/process": "1.76.0", + "@theia/scm": "1.76.0", + "@theia/search-in-workspace": "1.76.0", + "@theia/terminal": "1.76.0", + "@theia/typehierarchy": "1.76.0", + "@theia/vsx-registry": "1.76.0", + "@theia/workspace": "1.76.0", + "@wishforge/ide-policy": "file:./policy" + }, + "devDependencies": { + "@theia/cli": "1.76.0" + }, + "engines": { + "node": ">=22.14.0 <27" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@electron/get": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz", + "integrity": "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "env-paths": "^2.2.0", + "fs-extra": "^8.1.0", + "got": "^11.8.5", + "progress": "^2.0.3", + "semver": "^6.2.0", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "global-agent": "^3.0.0" + } + }, + "node_modules/@electron/get/node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "node_modules/@electron/get/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@electron/rebuild": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.1.tgz", + "integrity": "sha512-IS4pG3BysRrCLJ8xTAfvg+IQDbiUoAzdJy2SfjcYKnLDy5DpCdjnPdhS5Zf5UMfrkB24xu0KC+TqcOxg+eG+6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@malept/cross-spawn-promise": "^2.0.0", + "debug": "^4.1.1", + "node-abi": "^4.2.0", + "node-api-version": "^0.2.1", + "node-gyp": "^12.2.0", + "read-binary-file-arch": "^1.0.6" + }, + "bin": { + "electron-rebuild": "lib/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hono/node-server": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.5.tgz", + "integrity": "sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "hono": "^4 || ^5.0.0-0" + } + }, + "node_modules/@inversifyjs/common": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@inversifyjs/common/-/common-1.4.0.tgz", + "integrity": "sha512-qfRJ/3iOlCL/VfJq8+4o5X4oA14cZSBbpAmHsYj8EsIit1xDndoOl0xKOyglKtQD4u4gdNVxMHx4RWARk/I4QA==", + "license": "MIT" + }, + "node_modules/@inversifyjs/core": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@inversifyjs/core/-/core-1.3.5.tgz", + "integrity": "sha512-B4MFXabhNTAmrfgB+yeD6wd/GIvmvWC6IQ8Rh/j2C3Ix69kmqwz9pr8Jt3E+Nho9aEHOQCZaGmrALgtqRd+oEQ==", + "license": "MIT", + "dependencies": { + "@inversifyjs/common": "1.4.0", + "@inversifyjs/reflect-metadata-utils": "0.2.4" + } + }, + "node_modules/@inversifyjs/reflect-metadata-utils": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/@inversifyjs/reflect-metadata-utils/-/reflect-metadata-utils-0.2.4.tgz", + "integrity": "sha512-u95rV3lKfG+NT2Uy/5vNzoDujos8vN8O18SSA5UyhxsGYd4GLQn/eUsGXfOsfa7m34eKrDelTKRUX1m/BcNX5w==", + "license": "MIT", + "peerDependencies": { + "reflect-metadata": "0.2.2" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@jspm/core": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@jspm/core/-/core-2.1.0.tgz", + "integrity": "sha512-3sRl+pkyFY/kLmHl0cgHiFp2xEqErA8N3ECjMs7serSUBmoJ70lBa0PG5t0IM6WJgdZNyyI0R8YFfi5wM8+mzg==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@lumino/algorithm": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/algorithm/-/algorithm-2.0.5.tgz", + "integrity": "sha512-yW5k0IRrNlNDL9/hLOPr0XaMYf7YSZ5a/uJ++a92ziBe7v7a3xzBJ1+Awhb6fMyanE0Mz97UOQIsHa3vWB0UQA==", + "license": "BSD-3-Clause" + }, + "node_modules/@lumino/collections": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/collections/-/collections-2.0.5.tgz", + "integrity": "sha512-iRthCb6cMoq1rcd4OC8dNFU7v/YbJOw647kzqrMxLPlQmMeeY5wHxF/W9qCb01VUI3zyxvh0/ND4DHB4mruJfA==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.5" + } + }, + "node_modules/@lumino/commands": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/@lumino/commands/-/commands-2.3.4.tgz", + "integrity": "sha512-bmCdM7jxX25s9ydKZcWmF7xL051MsG5fJ9IyCHoOPcKm3keuwX3wY1PpVERuooUvU6zZfI7+LFaolWX0eCs2Hw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.5", + "@lumino/coreutils": "^2.2.3", + "@lumino/disposable": "^2.1.6", + "@lumino/domutils": "^2.0.5", + "@lumino/keyboard": "^2.0.5", + "@lumino/signaling": "^2.1.6", + "@lumino/virtualdom": "^2.0.5" + } + }, + "node_modules/@lumino/coreutils": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/@lumino/coreutils/-/coreutils-2.2.3.tgz", + "integrity": "sha512-YxmayMeq8VJCPqo1okpsA3oOoz0eZeG5qedOLmopm+N/GwQT7S34QPPts49omVUwTJ0Xo8fGzOsxnS/LwnVl1Q==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.5" + } + }, + "node_modules/@lumino/disposable": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@lumino/disposable/-/disposable-2.1.6.tgz", + "integrity": "sha512-mTDBsftt+dWkP3MeeLuYjJ7mtOcrMld6Pq4h7EY6HzhPSdPXzvQELZ29vpc1lq6EWz/fzCfpoE+W8AzNUCHTLg==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/signaling": "^2.1.6" + } + }, + "node_modules/@lumino/domutils": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/domutils/-/domutils-2.0.5.tgz", + "integrity": "sha512-4zsSqWqAHvOFJTtvyAZsQu7qL5ZZRu37mTzppZNAI3a91jlIben3NbAMGZiyZeAnv3b9Z7S5sPOVWZKkJyhegg==", + "license": "BSD-3-Clause" + }, + "node_modules/@lumino/dragdrop": { + "version": "2.1.9", + "resolved": "https://registry.npmjs.org/@lumino/dragdrop/-/dragdrop-2.1.9.tgz", + "integrity": "sha512-gwkdJNLrRE8GVh4Z70Yj5fhpasQNDkt8Z/aOneQbL4T1bpsMTwzdn3t/2pIZaWngrEqCGnj0ofUUuQAYZuQMyw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/coreutils": "^2.2.3", + "@lumino/disposable": "^2.1.6" + } + }, + "node_modules/@lumino/keyboard": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/keyboard/-/keyboard-2.0.5.tgz", + "integrity": "sha512-YB7kmE0+ZeZ6oN/Qps6Ln8MXe4rZQh+27ex4GTJuxTMvvbqFhDW6mc/zN6av22HYxDlOF55YlzNhjk2LpD8k7A==", + "license": "BSD-3-Clause" + }, + "node_modules/@lumino/messaging": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/messaging/-/messaging-2.0.5.tgz", + "integrity": "sha512-LNvV9xW6pkVuW8n4vFYxboJFOtt2WRJZMrg3Ta6C6LcfazVQy+ubiC8GRqBMq2ufZ1zclOWQII5QFC1wxFm6dg==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.5", + "@lumino/collections": "^2.0.5" + } + }, + "node_modules/@lumino/properties": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/properties/-/properties-2.0.5.tgz", + "integrity": "sha512-+Yoo9lb/hzNKFXpkRaEC4r7aMe8prbEhscAbA/vyzqmY4NYjZsiqhxHUgyKgtGHosrrpY59Qv4ha+5csU08zsw==", + "license": "BSD-3-Clause" + }, + "node_modules/@lumino/signaling": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@lumino/signaling/-/signaling-2.1.6.tgz", + "integrity": "sha512-PEB2nuNyippF/vj28oiDm7Zy8vAeVq07NE59L79GhaTe9i37TCjtA3+67DJnVGn1+fQPfexs6HdrY/90JFFwiw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.5", + "@lumino/coreutils": "^2.2.3" + } + }, + "node_modules/@lumino/virtualdom": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@lumino/virtualdom/-/virtualdom-2.0.5.tgz", + "integrity": "sha512-Qgvtv9Iruny+p2y/jPWo9tOcUqS+Nlcwg14+m+xJEclFyVTpY8gGJKTDY8Y1wVO5PpQjRPNdbF8lxzrGR/89IA==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.5" + } + }, + "node_modules/@lumino/widgets": { + "version": "2.7.5", + "resolved": "https://registry.npmjs.org/@lumino/widgets/-/widgets-2.7.5.tgz", + "integrity": "sha512-i11PlbTsZYIvC/uhcC4FeeLnu/7vveG8WzXFbxPunjT1yGjleqQIPlpMOAJ5d4PwCKqeM8LYttYke6ZOXvXDLA==", + "license": "BSD-3-Clause", + "dependencies": { + "@lumino/algorithm": "^2.0.4", + "@lumino/commands": "^2.3.3", + "@lumino/coreutils": "^2.2.2", + "@lumino/disposable": "^2.1.5", + "@lumino/domutils": "^2.0.4", + "@lumino/dragdrop": "^2.1.8", + "@lumino/keyboard": "^2.0.4", + "@lumino/messaging": "^2.0.4", + "@lumino/properties": "^2.0.4", + "@lumino/signaling": "^2.1.5", + "@lumino/virtualdom": "^2.0.4" + } + }, + "node_modules/@malept/cross-spawn-promise": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz", + "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/malept" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund" + } + ], + "license": "Apache-2.0", + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.32.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", + "integrity": "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.0.5", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/express/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", + "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/negotiator/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/type-is/node_modules/content-type": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz", + "integrity": "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.4.tgz", + "integrity": "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.4.tgz", + "integrity": "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.4.tgz", + "integrity": "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.4.tgz", + "integrity": "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.4.tgz", + "integrity": "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", + "cpu": [ + "arm" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@puppeteer/browsers": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.0.4.tgz", + "integrity": "sha512-HGM8iAmGTf+Y7t0373szVbTmt3d7vPkYL/1bpOkOFO0YUYLgSeuYBCzESklogNPvOBnZ/MRD5f07OkpqH1trtA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "modern-tar": "^0.7.6", + "yargs": "^17.7.2" + }, + "bin": { + "browsers": "lib/main-cli.js" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "proxy-agent": ">=8.0.1" + }, + "peerDependenciesMeta": { + "proxy-agent": { + "optional": true + } + } + }, + "node_modules/@sindresorhus/df": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@sindresorhus/df/-/df-3.1.1.tgz", + "integrity": "sha512-SME/vtXaJcnQ/HpeV6P82Egy+jThn11IKfwW8+/XVoRD0rmPHVTeKMtww1oWdVnMykzVPjmrDN9S8NBndPEHCQ==", + "license": "MIT", + "dependencies": { + "execa": "^2.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@sindresorhus/is": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", + "integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/is?sponsor=1" + } + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "license": "MIT" + }, + "node_modules/@stroncium/procfs": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@stroncium/procfs/-/procfs-1.2.1.tgz", + "integrity": "sha512-X1Iui3FUNZP18EUvysTHxt+Avu2nlVzyf90YM8OYgP6SGzTzzX/0JgObfO1AQQDzuZtNNz29bVh8h5R97JrjxA==", + "license": "CC0-1.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/@szmarczak/http-timer": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz", + "integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==", + "dev": true, + "license": "MIT", + "dependencies": { + "defer-to-connect": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@theia/ai-core": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/ai-core/-/ai-core-1.76.0.tgz", + "integrity": "sha512-eAYdhG3pXW2uKkslIouuzE+shg2+LiMES8ONRAq4n6JiuKdy0ycWg86yg+bNaUXmju78MMeq9mdXGp1a5ENV/w==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/output": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "@theia/workspace": "1.76.0", + "@types/js-yaml": "^4.0.9", + "fast-deep-equal": "^3.1.3", + "js-yaml": "^4.3.2", + "tslib": "^2.8.1", + "undici": "^7.29.1" + } + }, + "node_modules/@theia/ai-core-ui": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/ai-core-ui/-/ai-core-ui-1.76.0.tgz", + "integrity": "sha512-BA1dp3PlSHsH6UF6Q/V/4mCtIA/LRsoK3ruAvtDQErLvm0LktLd1uUG7WmLbIxjA77tlSGYDWNavC3ABRoYWUQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/ai-core": "1.76.0", + "@theia/core": "1.76.0", + "@theia/preferences": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/ai-mcp": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/ai-mcp/-/ai-mcp-1.76.0.tgz", + "integrity": "sha512-/aNNIgaMq4ZFOpCmgXALmXCjcw019QGSL/1buV/zLTwPcdnGPg8s0DeJUsqiFeyeUPyvQQl4PXqZWAwiFaQfsw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.30.0", + "@theia/ai-core": "1.76.0", + "@theia/ai-core-ui": "1.76.0", + "@theia/core": "1.76.0", + "@theia/workspace": "1.76.0" + } + }, + "node_modules/@theia/application-manager": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/application-manager/-/application-manager-1.76.0.tgz", + "integrity": "sha512-paYQvGBc6bUCVnfVPYo2BZPtFJumm4/5OO2M7yq342dBEezRIy/9bFIOEHs5wDCiC48Vqq1G2g3e36Jp752isw==", + "dev": true, + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@electron/rebuild": "^4.2.0", + "@theia/application-package": "1.76.0", + "@theia/bundle-plugin": "1.76.0", + "@theia/ffmpeg": "1.76.0", + "@theia/plugin-utils": "1.76.0", + "@types/fs-extra": "^4.0.15", + "@types/semver": "^7.8.0", + "esbuild": "^0.28.2", + "esbuild-plugin-copy": "^2.1.1", + "esbuild-plugins-node-modules-polyfill": "^1.8.3", + "fs-extra": "^4.0.3", + "http-server": "^14.1.1", + "semver": "^7.8.5", + "tslib": "^2.8.1", + "yargs": "^17.7.3" + }, + "peerDependencies": { + "@theia/electron": "*" + }, + "peerDependenciesMeta": { + "@theia/electron": { + "optional": true + } + } + }, + "node_modules/@theia/application-package": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/application-package/-/application-package-1.76.0.tgz", + "integrity": "sha512-XREacI7NkTjxbHE5EIqcwg8mYc1BMiebz61XDMiqGhR2PG+/36+DAZvymO2fk/eQtbGen4iyXRpDH7L7DASriA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/request": "1.76.0", + "@types/fs-extra": "^4.0.15", + "@types/semver": "^7.8.0", + "@types/write-json-file": "^2.2.1", + "deepmerge": "^4.3.1", + "fs-extra": "^4.0.3", + "is-electron": "^2.2.2", + "nano": "^10.1.4", + "resolve-package-path": "^4.0.3", + "semver": "^7.8.5", + "tslib": "^2.8.1", + "write-json-file": "^2.3.0" + } + }, + "node_modules/@theia/bulk-edit": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/bulk-edit/-/bulk-edit-1.76.0.tgz", + "integrity": "sha512-5pgYuaZY8K5A6umJalMUVJcW18b792JbVVWkKedGweaSH9vNhjYKWfD2WieipQs71xmyzUSWUSoHRdJRrrANIA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/workspace": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/bundle-plugin": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/bundle-plugin/-/bundle-plugin-1.76.0.tgz", + "integrity": "sha512-NP7+Dx2UfrxppOb3gnbuBBccGwtoAkhRihNQvwMKZ7dWtyj2f+86Zg79nQf0PSGcmsCSov8NFGzLrnyKjId43A==", + "dev": true, + "license": "EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0", + "dependencies": { + "detect-libc": "^2.1.2", + "resolve-package-path": "^4.0.3", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/callhierarchy": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/callhierarchy/-/callhierarchy-1.76.0.tgz", + "integrity": "sha512-b+CCB9dod9HJh5D7QM9r+ey68amsYneI5uvG8FaR561QiX5NUbdAPlOYQVrJOv8HqDee+nJtfghJj1JYw9ny1w==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "ts-md5": "^1.3.1", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/cli": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/cli/-/cli-1.76.0.tgz", + "integrity": "sha512-pc7jNa/r+WisySRRb3OJvc84YYzcohBLDsVbkN+trbMtczwzUhxtAHyU/3NzivwsshD98uEOLeai1X8mzsEf0Q==", + "dev": true, + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/application-manager": "1.76.0", + "@theia/application-package": "1.76.0", + "@theia/ffmpeg": "1.76.0", + "@theia/localization-manager": "1.76.0", + "@theia/ovsx-client": "1.76.0", + "@theia/request": "1.76.0", + "@types/chai": "^4.3.0", + "@types/mocha": "^10.0.10", + "@types/node-fetch": "^2.6.13", + "chai": "^4.3.10", + "chalk": "4.0.0", + "decompress": "^4.2.1", + "escape-string-regexp": "4.0.0", + "glob": "^8.1.0", + "http-server": "^14.1.1", + "limiter": "^2.1.0", + "log-update": "^4.0.0", + "mocha": "^11.8.0", + "patch-package": "^8.0.1", + "puppeteer": "25.1.0", + "puppeteer-core": "25.1.0", + "puppeteer-to-istanbul": "1.4.0", + "temp": "^0.9.4", + "tslib": "^2.8.1", + "yargs": "^17.7.3" + }, + "bin": { + "theia": "bin/theia.js", + "theia-patch": "bin/theia-patch.js" + } + }, + "node_modules/@theia/collaboration": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/collaboration/-/collaboration-1.76.0.tgz", + "integrity": "sha512-MSPNKud734inJL7lZS7j/6x13QWqK5r5fVC0Xn8DLXQv0BF2AV0FZvSau63b4O+0owXT37j0ooafOZNhBXPDoQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/workspace": "1.76.0", + "lib0": "^0.2.117", + "open-collaboration-protocol": "0.3.0", + "open-collaboration-yjs": "0.3.0", + "socket.io-client": "^4.8.3", + "y-protocols": "^1.0.7", + "yjs": "^13.6.32" + } + }, + "node_modules/@theia/console": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/console/-/console-1.76.0.tgz", + "integrity": "sha512-K49uLgNIb83hyISstRIdmvyx9o3STQpvMEdrfbvo7p3zXweiIjtTM3kBNMKFnjYIMKjcVkbFkjz0r+nQxyGFzg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "anser": "^2.3.5", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/core": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/core/-/core-1.76.0.tgz", + "integrity": "sha512-E1hJGgzHbu/Whqo8pxU9MkAblOnnGedPybPOVRspZjuKF8ApRof6cNpSrUeFevrGPmF5Jesd2NqchtvIExXGRg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@babel/runtime": "^7.29.7", + "@lumino/algorithm": "^2.0.5", + "@lumino/commands": "^2.3.4", + "@lumino/coreutils": "^2.2.3", + "@lumino/domutils": "^2.0.5", + "@lumino/dragdrop": "^2.1.9", + "@lumino/messaging": "^2.0.5", + "@lumino/properties": "^2.0.5", + "@lumino/signaling": "^2.1.6", + "@lumino/virtualdom": "^2.0.5", + "@lumino/widgets": "2.7.5", + "@parcel/watcher": "^2.6.0", + "@theia/application-package": "1.76.0", + "@theia/request": "1.76.0", + "@types/body-parser": "^1.19.6", + "@types/express": "^4.17.25", + "@types/fs-extra": "^4.0.15", + "@types/lodash.debounce": "4.0.3", + "@types/lodash.throttle": "^4.1.9", + "@types/markdown-it": "^14.2.0", + "@types/markdown-it-emoji": "^3.0.1", + "@types/route-parser": "^0.1.7", + "@types/safer-buffer": "^2.1.3", + "@types/ws": "^8.18.1", + "@types/yargs": "^17.0.35", + "@vscode/codicons": "0.0.45", + "ajv": "^6.15.0", + "async-mutex": "^0.4.1", + "body-parser": "^1.20.8", + "cookie": "^1.1.1", + "dompurify": "^3.4.15", + "drivelist": "^12.0.2", + "express": "^4.22.2", + "fast-json-stable-stringify": "^2.1.0", + "file-icons-js": "~1.0.3", + "font-awesome": "^4.7.0", + "fs-extra": "^4.0.3", + "fuzzy": "^0.1.3", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.1", + "iconv-lite": "^0.6.3", + "inversify": "^6.2.2", + "jschardet": "^2.3.0", + "keytar": "7.9.0", + "lodash.debounce": "^4.0.8", + "lodash.throttle": "^4.1.1", + "markdown-it": "^14.3.1", + "markdown-it-anchor": "^9.2.1", + "markdown-it-emoji": "^3.1.0", + "msgpackr": "^1.12.1", + "p-debounce": "^2.1.0", + "perfect-scrollbar": "1.5.5", + "react-tooltip": "^4.5.1", + "react-virtuoso": "^2.19.1", + "reflect-metadata": "^0.2.2", + "route-parser": "^0.0.5", + "safer-buffer": "^2.1.2", + "socket.io": "^4.8.3", + "socket.io-client": "^4.8.3", + "tslib": "^2.8.1", + "uuid": "^11.1.1", + "vscode-languageserver-protocol": "3.17.5", + "vscode-uri": "3.0.8", + "ws": "^8.21.3", + "yargs": "^17.7.3" + }, + "peerDependencies": { + "@theia/electron": "*", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "peerDependenciesMeta": { + "@theia/electron": { + "optional": true + }, + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@theia/debug": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/debug/-/debug-1.76.0.tgz", + "integrity": "sha512-fdW1IVQyDyid0WHvLvvAwnLnSq5weh4+oHiMSHFy3vuTy9BRrcieKSjU1b9gWtMM6f9wKDtHLuLGgYzdE57rTg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/console": "1.76.0", + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/markers": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/output": "1.76.0", + "@theia/process": "1.76.0", + "@theia/task": "1.76.0", + "@theia/terminal": "1.76.0", + "@theia/test": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "@theia/workspace": "1.76.0", + "@vscode/debugprotocol": "^1.68.0", + "fast-deep-equal": "^3.1.3", + "jsonc-parser": "^3.3.1", + "p-debounce": "^2.1.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/editor": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/editor/-/editor-1.76.0.tgz", + "integrity": "sha512-HeC696z+LkwHdTYq6v3/Z5b9LQdOHgVmqGsqWrb/RwB8n47p2PbX8p3ORGTlLsbo3ItAb7pET1nRxee4j8ssMw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/editor-preview": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/editor-preview/-/editor-preview-1.76.0.tgz", + "integrity": "sha512-pL9Zl5mbVamYTa9/C7tNoEG75cnaaB4IFXmZMZaoRXzjhIG2jiOCge0xg+qI/F4iVMq3kSyndSfmqTRcZhZsxQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/navigator": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/ffmpeg": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/ffmpeg/-/ffmpeg-1.76.0.tgz", + "integrity": "sha512-lLhUcV1SE0/AEdJsHHo3RIPhm2/b2cfr1AO0ZjsMhXHxf0ITjJgqZ4smasH9poTuQeVaV3cxbh9Cflcpi0t1mw==", + "dev": true, + "hasInstallScript": true, + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@electron/get": "^2.0.3", + "tslib": "^2.8.1", + "unzipper": "^0.9.15" + } + }, + "node_modules/@theia/file-search": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/file-search/-/file-search-1.76.0.tgz", + "integrity": "sha512-hwdu99xJw8CGdoH9guCu+CJdq/9MWdSLIhtp7c5tk2Jo4OfZxLbfB5PMfuBAq9Elh1KR9cwL2iKas+cphKKwcQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/process": "1.76.0", + "@theia/workspace": "1.76.0", + "@vscode/ripgrep": "^1.18.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/filesystem": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/filesystem/-/filesystem-1.76.0.tgz", + "integrity": "sha512-k/aS4GktTXZA4o8Zw+e+bFDMjWQlGNCQrWHnTaxZO/tCVaqhs4MwUh1nJ+iWTmzHfE1SeK86uFmdOsm2b6z2og==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@types/body-parser": "^1.19.6", + "@types/multer": "^1.4.13", + "@types/tar-fs": "^1.16.3", + "@types/tar-stream": "^3.1.4", + "async-mutex": "^0.3.2", + "body-parser": "^1.20.8", + "http-status-codes": "^1.4.0", + "ignore": "^6.0.2", + "minimatch": "^10.2.6", + "multer": "^2.3.0", + "opfs-worker": "1.3.1", + "rimraf": "^5.0.10", + "stat-mode": "^1.0.0", + "tar-fs": "^3.1.3", + "tar-stream": "^3.2.1", + "trash": "^7.2.0", + "tslib": "^2.8.1", + "vscode-languageserver-textdocument": "^1.0.14" + } + }, + "node_modules/@theia/filesystem/node_modules/async-mutex": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz", + "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.1" + } + }, + "node_modules/@theia/localization-manager": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/localization-manager/-/localization-manager-1.76.0.tgz", + "integrity": "sha512-0fCsCkDxjoBUzIZvdyXi/xMsAOqUPVph1X9SMgP/BMxogMGuDDAiDb7e5wFZitkWvs3WMh6NW6vtB2CO3w/NyA==", + "dev": true, + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@types/bent": "^7.3.8", + "@types/fs-extra": "^4.0.15", + "bent": "^7.3.12", + "chalk": "4.0.0", + "deepmerge": "^4.3.1", + "fs-extra": "^4.0.3", + "glob": "^7.2.3", + "limiter": "^2.1.0", + "tslib": "^2.8.1", + "typescript": "~5.9.3" + } + }, + "node_modules/@theia/localization-manager/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@theia/localization-manager/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@theia/localization-manager/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "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 i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@theia/localization-manager/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@theia/localization-manager/node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/@theia/markers": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/markers/-/markers-1.76.0.tgz", + "integrity": "sha512-R3rfh0GsxYg0yjxKJ0RiDR/FhUJSBghdFlnuT58E3i3kPfqNYtUhhqszRF3ISvxmsjsGQv5tQwkmnfPX5fv7eg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/workspace": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/messages": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/messages/-/messages-1.76.0.tgz", + "integrity": "sha512-95GnsKvj65wlUIY4yg51wUHnemiJ4QTz0+9PpUSKGxbLPVb/2rH8L6CpmH8nTWgRNj+fxtHhBXh8anW0bcqIYw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "react-perfect-scrollbar": "^1.5.8", + "ts-md5": "^1.3.1", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/mini-browser": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/mini-browser/-/mini-browser-1.76.0.tgz", + "integrity": "sha512-53ZNSKS3PZq5VTHCsS92/lISAjObhCFyW1nK77J1aCvU/rl49pdUbL7eoM/1NXEJqjhqlfAGUcQIq8PWs0HloQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/filesystem": "1.76.0", + "@types/mime-types": "^2.1.4", + "mime-types": "^2.1.35", + "pdfobject": "^2.3.1", + "tslib": "^2.8.1", + "vhost": "^3.0.2" + } + }, + "node_modules/@theia/monaco": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/monaco/-/monaco-1.76.0.tgz", + "integrity": "sha512-i1y6PUEw65mSlqnpmxqeboUuDvMlxGIcifYvMDIMtanWHX1eRhwP/si85NB8OC0PLScHsyDP7Cd/tVsq+cu5Cw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/markers": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/outline-view": "1.76.0", + "@theia/workspace": "1.76.0", + "fast-plist": "^0.1.3", + "idb": "^4.0.5", + "jsonc-parser": "^3.3.1", + "tslib": "^2.8.1", + "vscode-oniguruma": "2.0.1", + "vscode-textmate": "^9.3.2" + } + }, + "node_modules/@theia/monaco-editor-core": { + "version": "1.108.201", + "resolved": "https://registry.npmjs.org/@theia/monaco-editor-core/-/monaco-editor-core-1.108.201.tgz", + "integrity": "sha512-svIRZuZTqzNontpe6n9f8RPRBtPaOyuB1btpMJ2tcNodjTuTgs2OB/FIhRp5WF17v7negIbA9WzroXt+uzSGng==", + "license": "MIT", + "dependencies": { + "dompurify": "3.2.7", + "marked": "14.0.0" + } + }, + "node_modules/@theia/monaco-editor-core/node_modules/dompurify": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.7.tgz", + "integrity": "sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/@theia/navigator": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/navigator/-/navigator-1.76.0.tgz", + "integrity": "sha512-Xuc4XUVtFBYPJqjxF+uPFnEsKZIDGlf5Qt55lgp2GrXskjUyO5jirF+Q9O6KUg+MYm+hlQ1r5g0hKowNTf0uyQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/workspace": "1.76.0", + "minimatch": "^10.2.6", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/notebook": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/notebook/-/notebook-1.76.0.tgz", + "integrity": "sha512-nm6wh8F9i/0owEjQo4Hx9dbFIps2/6hyjBSpP2lLKnHAADCI2MePNhMQZcbcTtilxIAqPL3xRS+1jc54/gTXOw==", + "license": "EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/outline-view": "1.76.0", + "advanced-mark.js": "^2.7.1", + "react-perfect-scrollbar": "^1.5.8", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/outline-view": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/outline-view/-/outline-view-1.76.0.tgz", + "integrity": "sha512-1k+1mF+EwZqvuxwZmU/IBsX/r4V0qK3DIbTkDNXRZJrldLD/1a+6BUBTVrymUIgFeCA8A83/ZmNUZAFXC9PeyA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/output": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/output/-/output-1.76.0.tgz", + "integrity": "sha512-68N1MRqUaf1t+r6i4ePGfgwuSZlTsBfiGntwH3O7AyAIxksV2+Ok+oBGKQR0HkSyVGeSmx8BFILr3HRWwO/8dA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "p-queue": "^8.1.1", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/ovsx-client": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/ovsx-client/-/ovsx-client-1.76.0.tgz", + "integrity": "sha512-epYFvWHiYKoqTK/UjuUN26SMQ1qs2vZmodqL+2rdcG6rbnsyawBByYL6wDT+pT/lrmiunElLz67/ChDMohQSgg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/request": "1.76.0", + "limiter": "^2.1.0", + "semver": "^7.8.5", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/plugin": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/plugin/-/plugin-1.76.0.tgz", + "integrity": "sha512-OPXjKL+gm3JH3vbGhatHc5IQ/aylvRy1qmhQ9YNghk4eV2AnKTYrd2r4o/jeDXDmsNxWM5sfOCmhhqfC3PljTw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0" + }, + "node_modules/@theia/plugin-ext": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/plugin-ext/-/plugin-ext-1.76.0.tgz", + "integrity": "sha512-lEnGlysG8MQT6P8HIB+uBZmwluYoTgU0i4iQygTOVsQ0BiLH9gmKERSxZSf+3wL3IGRoL9tt+v211IibPxZJdQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/ai-core": "1.76.0", + "@theia/ai-mcp": "1.76.0", + "@theia/bulk-edit": "1.76.0", + "@theia/callhierarchy": "1.76.0", + "@theia/console": "1.76.0", + "@theia/core": "1.76.0", + "@theia/debug": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/editor-preview": "1.76.0", + "@theia/file-search": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/markers": "1.76.0", + "@theia/messages": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/navigator": "1.76.0", + "@theia/notebook": "1.76.0", + "@theia/output": "1.76.0", + "@theia/plugin": "1.76.0", + "@theia/plugin-utils": "1.76.0", + "@theia/preferences": "1.76.0", + "@theia/scm": "1.76.0", + "@theia/search-in-workspace": "1.76.0", + "@theia/task": "1.76.0", + "@theia/telemetry": "1.76.0", + "@theia/terminal": "1.76.0", + "@theia/test": "1.76.0", + "@theia/timeline": "1.76.0", + "@theia/typehierarchy": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "@theia/workspace": "1.76.0", + "@types/mime": "^2.0.3", + "@vscode/debugprotocol": "^1.68.0", + "@vscode/proxy-agent": "^0.13.2", + "async-mutex": "^0.4.1", + "decompress": "^4.2.1", + "escape-html": "^1.0.3", + "filenamify": "^4.3.0", + "is-electron": "^2.2.2", + "jsonc-parser": "^3.3.1", + "lodash.clonedeep": "^4.5.0", + "macaddress": "^0.5.4", + "mime": "^2.6.0", + "node-pty": "1.2.0-beta.12", + "semver": "^7.8.5", + "tslib": "^2.8.1", + "vhost": "^3.0.2", + "vscode-textmate": "^9.3.2" + } + }, + "node_modules/@theia/plugin-ext-vscode": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/plugin-ext-vscode/-/plugin-ext-vscode-1.76.0.tgz", + "integrity": "sha512-ZT3HkN69Q79VKhmapvgJU4P/ZTTxHctidKE3ienks40Ewu8Qx0wFHFr/AgJ4wg9xxjvc+Smz81pJPgqBUz/Y/w==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/callhierarchy": "1.76.0", + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/navigator": "1.76.0", + "@theia/outline-view": "1.76.0", + "@theia/plugin": "1.76.0", + "@theia/plugin-ext": "1.76.0", + "@theia/plugin-utils": "1.76.0", + "@theia/scm": "1.76.0", + "@theia/terminal": "1.76.0", + "@theia/typehierarchy": "1.76.0", + "@theia/userstorage": "1.76.0", + "@theia/workspace": "1.76.0", + "decompress": "^4.2.1", + "filenamify": "^4.3.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/plugin-utils": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/plugin-utils/-/plugin-utils-1.76.0.tgz", + "integrity": "sha512-KAVDGoFakhNAXuyKf/MlFR9h57mUvfUDKyW4GodLC3bHtsAR51zn+N7YI5bsYIDPRJGK31jkw6KEfbmN+RARsA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@types/fs-extra": "^4.0.15", + "fs-extra": "^4.0.3", + "jsonc-parser": "^3.3.1", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/preferences": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/preferences/-/preferences-1.76.0.tgz", + "integrity": "sha512-xEoxMl4Ya4W9CPeUI5zOP6krJsa3M+a87UUSpCxBSQRwUVzQN6/sfkpuCLO4lvqQ1aprwY3qPgYp4SP+9nn9ow==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/userstorage": "1.76.0", + "@theia/workspace": "1.76.0", + "async-mutex": "^0.3.2", + "fast-deep-equal": "^3.1.3", + "jsonc-parser": "^3.3.1", + "p-debounce": "^2.1.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/preferences/node_modules/async-mutex": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz", + "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.1" + } + }, + "node_modules/@theia/process": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/process/-/process-1.76.0.tgz", + "integrity": "sha512-Yly21WJS2Nd3LvokrYXE1t5IRM2kIyhkG1u+0CTXtb3zue9kD32fWc+yvpCAF4yIB0a3ijNnJG1x0wdfEcAC5w==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "node-pty": "1.2.0-beta.12", + "string-argv": "^0.1.2", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/request": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/request/-/request-1.76.0.tgz", + "integrity": "sha512-jVzLoja+kvIUZmbeY1Dh8Yz5Tq56DP7Zp/w2hgCymrfr2DL59sPdBZFGsQfpHgZaLW3No1c1zamMWmrHrKDXzg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "tslib": "^2.8.1", + "undici": "^7.29.1" + } + }, + "node_modules/@theia/scm": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/scm/-/scm-1.76.0.tgz", + "integrity": "sha512-2porrDle9dLs3ONLDF/IlmHi0gqbAZDpcEY6Gx+3EJ6VGGxL04zSjiOD1F/uQzGweoNKxUa4f7VHWhqkJ9etKw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@types/diff": "^5.2.3", + "diff": "^5.2.2", + "p-debounce": "^2.1.0", + "react-textarea-autosize": "^8.5.9", + "ts-md5": "^1.3.1", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/search-in-workspace": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/search-in-workspace/-/search-in-workspace-1.76.0.tgz", + "integrity": "sha512-s/BI7Ip2rIxKs2aQ4YnXZkKx0iC8jL+jB+SsulbOAmPIKBgs3PThTzjeRQI0IXXRoiDsmxYyKUpvTbXGt2k06w==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/navigator": "1.76.0", + "@theia/process": "1.76.0", + "@theia/workspace": "1.76.0", + "@vscode/ripgrep": "^1.18.0", + "minimatch": "^10.2.6", + "react-textarea-autosize": "^8.5.9", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/task": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/task/-/task-1.76.0.tgz", + "integrity": "sha512-7ZBEo8Hy3k8CicLtt00AE3cKBXk542LicfOc64Zd4d8Y+bSRwFqHHcLdnm9fAKChHeulKXv9Z/FG9zAm5ojZ9Q==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/markers": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/monaco-editor-core": "1.108.201", + "@theia/process": "1.76.0", + "@theia/terminal": "1.76.0", + "@theia/userstorage": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "@theia/workspace": "1.76.0", + "async-mutex": "^0.3.2", + "jsonc-parser": "^3.3.1", + "p-debounce": "^2.1.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/task/node_modules/async-mutex": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.3.2.tgz", + "integrity": "sha512-HuTK7E7MT7jZEh1P9GtRW9+aTWiDWWi9InbZ5hjxrnRa39KS4BW04+xLBhYNS2aXhHUIKZSw3gj4Pn1pj+qGAA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.1" + } + }, + "node_modules/@theia/telemetry": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/telemetry/-/telemetry-1.76.0.tgz", + "integrity": "sha512-yuqk0RP3l96fFoAlqE35lFjuGb2Zv+KslUyDNPXEcxDDRt/KTjcS+784V4zUYBNSbCBdhRTqNnqkgM6uUsbdWA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/terminal": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/terminal/-/terminal-1.76.0.tgz", + "integrity": "sha512-M9uYbgpmU4IYGYDvAH6oIcgxOCETxEJvXRs1Tir7I+8AJ6I8r6sdRhSCKc0q3re3avmIkaJzfATIhGVZXPgz9w==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/file-search": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/process": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "@theia/workspace": "1.76.0", + "tslib": "^2.8.1", + "xterm": "^5.3.0", + "xterm-addon-fit": "^0.8.0", + "xterm-addon-search": "^0.13.0", + "xterm-addon-webgl": "^0.16.0" + } + }, + "node_modules/@theia/test": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/test/-/test-1.76.0.tgz", + "integrity": "sha512-TGdbzjEbUJQGYvpGUn0UkhuMy2AldmuRXgLS9Ac735YxddTn30XC/13twODMQLWdyutgQp9qU8pFVr5c+DtC5w==", + "license": "EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/navigator": "1.76.0", + "@theia/terminal": "1.76.0", + "xterm": "^5.3.0", + "xterm-addon-fit": "^0.8.0" + } + }, + "node_modules/@theia/timeline": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/timeline/-/timeline-1.76.0.tgz", + "integrity": "sha512-coqJsh1MrDN62G6w/DS1Q6Ced0fjUxa3t0kCcADze69IGJ1T061G33tzsyk5PvR/s1PtHaGvo0O7U1XN7akBDw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/navigator": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/typehierarchy": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/typehierarchy/-/typehierarchy-1.76.0.tgz", + "integrity": "sha512-FwD5YOaOWPcCgx8fIcJYUGVv70sCLu1oX/tCwN5PXGJddtcscKaXXErsMias1V2ZJILSY88q+3/KDu5hjHpq1A==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/userstorage": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/userstorage/-/userstorage-1.76.0.tgz", + "integrity": "sha512-/sbWKkBhL96Gy8gNKqjhGfiCdTNzREjJgjAfBBoSVqdZoI6aeHVIMDd07BYWHhKI171YzqHxeSW2rtgRssxncw==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/filesystem": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/variable-resolver": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/variable-resolver/-/variable-resolver-1.76.0.tgz", + "integrity": "sha512-TtrMHLPNGt/lLs4kAXqIhkvapE9+rjznJ6sC54GyJHhhjVXxGGuCMJlXPtgEAYtj3v/JbyatkblBs3F4k5tOYg==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/vsx-registry": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/vsx-registry/-/vsx-registry-1.76.0.tgz", + "integrity": "sha512-SW8bRaSeT/DcJKBnMDfKQgBdl18a6cIBAZdorzDCpQyRH3lcb0Y+HkZPEhDwgEOf2LoJAtMfeAVBNwKyEKCzYQ==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/navigator": "1.76.0", + "@theia/ovsx-client": "1.76.0", + "@theia/plugin-ext": "1.76.0", + "@theia/plugin-ext-vscode": "1.76.0", + "@theia/preferences": "1.76.0", + "@theia/workspace": "1.76.0", + "limiter": "^2.1.0", + "luxon": "^2.5.2", + "p-debounce": "^2.1.0", + "semver": "^7.8.5", + "tslib": "^2.8.1" + } + }, + "node_modules/@theia/workspace": { + "version": "1.76.0", + "resolved": "https://registry.npmjs.org/@theia/workspace/-/workspace-1.76.0.tgz", + "integrity": "sha512-KxR85wdO1HFB3P30zozHp2X/m2BSjeB8VyRQdS/360qOl6rZksJPIfHlDedlbZiD/j6gbVgWnwHVAagZTWn8BA==", + "license": "EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0", + "dependencies": { + "@theia/core": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/variable-resolver": "1.76.0", + "jsonc-parser": "^3.3.1", + "tslib": "^2.8.1", + "valid-filename": "^2.0.1" + } + }, + "node_modules/@tootallnate/once": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", + "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/bent": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/@types/bent/-/bent-7.3.8.tgz", + "integrity": "sha512-yZ09JA1KsA5Fl6Oh/ahK00+H5bV0qCy2bYnyfiFY42wnaMK4n7IDC6HaFe3WW45Zhnak7iqJBKlWD0nVxzrGWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/body-parser": { + "version": "1.19.6", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", + "integrity": "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==", + "license": "MIT", + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/cacheable-request": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz", + "integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/http-cache-semantics": "*", + "@types/keyv": "^3.1.4", + "@types/node": "*", + "@types/responselike": "^1.0.0" + } + }, + "node_modules/@types/chai": { + "version": "4.3.20", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.20.tgz", + "integrity": "sha512-/pC9HAB5I/xMlc5FP77qjCnI16ChlJfW0tGa0IUcFn38VJrTV6DeZ60NU5KZBtaOZqjdpwTWohz5HU1RrhiYxQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/cors": { + "version": "2.8.19", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", + "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/diff": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.3.tgz", + "integrity": "sha512-K0Oqlrq3kQMaO2RhfrNQX5trmt+XLyom88zS0u84nnIcLvFnRUMRRHmrGny5GSM+kNO9IZLARsdQHDzkhAgmrQ==", + "license": "MIT" + }, + "node_modules/@types/express": { + "version": "4.17.25", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", + "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "^1" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.19.9", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.9.tgz", + "integrity": "sha512-QP2ESEe/ImWY0HDwNAnK9PvEffUyhLTnWkk7KXzHfyeWAnlrDe1fN77bXl6ia8KT3wPlmA7t9/VPRpnf4Ex9sg==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/fs-extra": { + "version": "4.0.15", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-4.0.15.tgz", + "integrity": "sha512-zU/EU2kZ1tv+p4pswQLntA7dFQq84wXrSCfmLjZvMbLjf4N46cPOWHg+WKfc27YnEOQ0chVFlBui55HRsvzHPA==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/http-cache-semantics": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz", + "integrity": "sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/http-errors": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", + "license": "MIT" + }, + "node_modules/@types/js-yaml": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz", + "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==", + "license": "MIT" + }, + "node_modules/@types/keyv": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz", + "integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/linkify-it": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.26", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.26.tgz", + "integrity": "sha512-48NWfiY6oNcKOh47Z4h+sIvwcQR91h6KPhaYKgeMIrkT2jV82Gy90SErj60vW8jQbeMSOSbhIv3bZ7JoqPPVhA==", + "license": "MIT" + }, + "node_modules/@types/lodash.debounce": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@types/lodash.debounce/-/lodash.debounce-4.0.3.tgz", + "integrity": "sha512-/2RpcexzkSH16nENwuL/Gd3Y2xvdkNwX32KPESB/D8K2c6HBs7GdSnoj6ngyFWNT1UhXNrIpJd0lgSC3Rmt/3g==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/lodash.throttle": { + "version": "4.1.9", + "resolved": "https://registry.npmjs.org/@types/lodash.throttle/-/lodash.throttle-4.1.9.tgz", + "integrity": "sha512-PCPVfpfueguWZQB7pJQK890F2scYKoDUL3iM522AptHWn7d5NQmeS/LTEHIcLr5PaTzl3dK2Z0xSUHHTHwaL5g==", + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, + "node_modules/@types/markdown-it": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.2.0.tgz", + "integrity": "sha512-NoQ2yGlLWj4wpxMs+TYmRKk3thDrQ97agr7sFqfLsAlvoS8SNQuTrlObhFqG9iugdTtgOE9jpJ6FNM4ZGsa5xQ==", + "license": "MIT", + "dependencies": { + "@types/linkify-it": "^5", + "@types/mdurl": "^2" + } + }, + "node_modules/@types/markdown-it-emoji": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/markdown-it-emoji/-/markdown-it-emoji-3.0.1.tgz", + "integrity": "sha512-cz1j8R35XivBqq9mwnsrP2fsz2yicLhB8+PDtuVkKOExwEdsVBNI+ROL3sbhtR5occRZ66vT0QnwFZCqdjf3pA==", + "license": "MIT", + "dependencies": { + "@types/markdown-it": "^14" + } + }, + "node_modules/@types/mdurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "license": "MIT" + }, + "node_modules/@types/mime": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-2.0.3.tgz", + "integrity": "sha512-Jus9s4CDbqwocc5pOAnh8ShfrnMcPHuJYzVcSUU7lrh8Ni5HuIqX3oilL86p3dlTrk0LzHRCgA/GQ7uNCw6l2Q==", + "license": "MIT" + }, + "node_modules/@types/mime-types": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-2.1.4.tgz", + "integrity": "sha512-lfU4b34HOri+kAY5UheuFMWPDOI+OPceBSHZKp69gEyTL/mmJ4cnU6Y/rlme3UL3GyOn6Y42hyIEw0/q8sWx5w==", + "license": "MIT" + }, + "node_modules/@types/mocha": { + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz", + "integrity": "sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/multer": { + "version": "1.4.13", + "resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.13.tgz", + "integrity": "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw==", + "license": "MIT", + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/node": { + "version": "26.6.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", + "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.13", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", + "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.4" + } + }, + "node_modules/@types/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==", + "license": "MIT" + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "license": "MIT" + }, + "node_modules/@types/responselike": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz", + "integrity": "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/route-parser": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@types/route-parser/-/route-parser-0.1.7.tgz", + "integrity": "sha512-haO+3HVio/4w+yuMJTjqfSo0ivOV8WnXaOReVD6QN729UGBEyizWNGc2Jd0OLsJDucIod4aJSsPLBeLj2uzMCQ==", + "license": "MIT" + }, + "node_modules/@types/safer-buffer": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@types/safer-buffer/-/safer-buffer-2.1.3.tgz", + "integrity": "sha512-5o3RcpBa7mUFnnnoMa9UIGOf9naD4DCKKMYzqkm9OSY7NNTd26k7adNC+fphcVRI9BUJglBs2yJQiRZYqBF/8w==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/semver": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==", + "license": "MIT" + }, + "node_modules/@types/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@types/send/-/send-1.2.1.tgz", + "integrity": "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.10", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.10.tgz", + "integrity": "sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==", + "license": "MIT", + "dependencies": { + "@types/http-errors": "*", + "@types/node": "*", + "@types/send": "<1" + } + }, + "node_modules/@types/serve-static/node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "license": "MIT" + }, + "node_modules/@types/serve-static/node_modules/@types/send": { + "version": "0.17.6", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.6.tgz", + "integrity": "sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==", + "license": "MIT", + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/tar-fs": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/@types/tar-fs/-/tar-fs-1.16.3.tgz", + "integrity": "sha512-Y+fdeg11tb9J3UNIatNtrTPM1i8U+WLv2mMhZ3W13mtU19stCgrXJ4iXLkTpoF8jqHi3T/qTS8+fQ3IPzXxpuA==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/tar-stream": "*" + } + }, + "node_modules/@types/tar-stream": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/@types/tar-stream/-/tar-stream-3.1.5.tgz", + "integrity": "sha512-zCUA6CSDw0t2cpQiZixpyzfubpeuVZmBr5wztvuCG4bhy7reX/9wGXdZxEzz2CjMFLQ32UPR/01jzUUSRJeCeQ==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, + "node_modules/@types/write-json-file": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@types/write-json-file/-/write-json-file-2.2.1.tgz", + "integrity": "sha512-JdO/UpPm9RrtQBNVcZdt3M7j3mHO/kXaea9LBGx3UgWJd1f9BkIWP7jObLBG6ZtRyqp7KzLFEsaPhWcidVittA==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "license": "MIT" + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@virtuoso.dev/react-urx": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/@virtuoso.dev/react-urx/-/react-urx-0.2.13.tgz", + "integrity": "sha512-MY0ugBDjFb5Xt8v2HY7MKcRGqw/3gTpMlLXId2EwQvYJoC8sP7nnXjAxcBtTB50KTZhO0SbzsFimaZ7pSdApwA==", + "license": "MIT", + "dependencies": { + "@virtuoso.dev/urx": "^0.2.13" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": ">=16" + } + }, + "node_modules/@virtuoso.dev/urx": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/@virtuoso.dev/urx/-/urx-0.2.13.tgz", + "integrity": "sha512-iirJNv92A1ZWxoOHHDYW/1KPoi83939o83iUBQHIim0i3tMeSKEh+bxhJdTHQ86Mr4uXx9xGUTq69cp52ZP8Xw==", + "license": "MIT" + }, + "node_modules/@vscode/codicons": { + "version": "0.0.45", + "resolved": "https://registry.npmjs.org/@vscode/codicons/-/codicons-0.0.45.tgz", + "integrity": "sha512-1KAZ7XCMagp5Gdrlr4bbbcAqgcIL623iO1wW6rfcSVGAVUQvR0WP7bQx1SbJ11gmV3fdQTSEFIJQ/5C+HuVasw==", + "license": "CC-BY-4.0" + }, + "node_modules/@vscode/debugprotocol": { + "version": "1.68.0", + "resolved": "https://registry.npmjs.org/@vscode/debugprotocol/-/debugprotocol-1.68.0.tgz", + "integrity": "sha512-2J27dysaXmvnfuhFGhfeuxfHRXunqNPxtBoR3koiTOA9rdxWNDTa1zIFLCFMSHJ9MPTPKFcBeblsyaCJCIlQxg==", + "license": "MIT" + }, + "node_modules/@vscode/proxy-agent": { + "version": "0.13.2", + "resolved": "https://registry.npmjs.org/@vscode/proxy-agent/-/proxy-agent-0.13.2.tgz", + "integrity": "sha512-BSUd0NTj44WvG4O9A6N+4R1XhxtPqCYltWeHyNkquX9T//a1US+cd8fxzcZCPd3z7dygdYIPkZAKM+CrefWWOA==", + "license": "MIT", + "dependencies": { + "@tootallnate/once": "^1.1.2", + "agent-base": "^6.0.2", + "debug": "^4.3.1", + "http-proxy-agent": "^4.0.1", + "https-proxy-agent": "^5.0.0", + "socks-proxy-agent": "^5.0.0" + }, + "optionalDependencies": { + "@vscode/windows-ca-certs": "^0.3.1" + } + }, + "node_modules/@vscode/proxy-agent/node_modules/http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "license": "MIT", + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@vscode/ripgrep": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep/-/ripgrep-1.18.0.tgz", + "integrity": "sha512-ns5lWe44tSfbTMbVUsyB+I1819PVSw4AdpgK0RNkzfWfwy6+3IUNSxwSrfTno1/oWaS/hERNz+XLWVyga2aJBQ==", + "license": "MIT", + "optionalDependencies": { + "@vscode/ripgrep-darwin-arm64": "1.18.0", + "@vscode/ripgrep-darwin-x64": "1.18.0", + "@vscode/ripgrep-linux-arm": "1.18.0", + "@vscode/ripgrep-linux-arm64": "1.18.0", + "@vscode/ripgrep-linux-ia32": "1.18.0", + "@vscode/ripgrep-linux-ppc64": "1.18.0", + "@vscode/ripgrep-linux-riscv64": "1.18.0", + "@vscode/ripgrep-linux-s390x": "1.18.0", + "@vscode/ripgrep-linux-x64": "1.18.0", + "@vscode/ripgrep-win32-arm64": "1.18.0", + "@vscode/ripgrep-win32-ia32": "1.18.0", + "@vscode/ripgrep-win32-x64": "1.18.0" + } + }, + "node_modules/@vscode/ripgrep-darwin-arm64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-darwin-arm64/-/ripgrep-darwin-arm64-1.18.0.tgz", + "integrity": "sha512-r3ktHSvbFycQNF6sl7sNDPocpsI7J+mEzh1IaZFkY0spm3k2Z9t8hPAeOK7+p0l6p6/swkQC14XWX01low+94Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@vscode/ripgrep-darwin-x64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-darwin-x64/-/ripgrep-darwin-x64-1.18.0.tgz", + "integrity": "sha512-25b4gWbL138dGuQU244ebCKKc0q05ULBMoFSz9oAEUHNeqK/lOJViDS7DRvbDazzAzSEdan391Znks/R5mkaTQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@vscode/ripgrep-linux-arm": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-arm/-/ripgrep-linux-arm-1.18.0.tgz", + "integrity": "sha512-GDAvufNDHu8zqLEmXstalQF0Wh6wQvdsBi/Vg3Yi3CK4a8XoFXqqXVEHEZ9xQz3t0NfoSEc9JbvK9DDS6FxyxQ==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-linux-arm64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-arm64/-/ripgrep-linux-arm64-1.18.0.tgz", + "integrity": "sha512-lQ/5zTG++U0E3IhVgS4EPTTn/U4okncaRMM5GOFfOYZywS4nuD31GhkHbNYlDk5CuDC68+hYJ0/eQeyCKJDA+g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-linux-ia32": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-ia32/-/ripgrep-linux-ia32-1.18.0.tgz", + "integrity": "sha512-YWLkSUtFd4Jh5EepIhA9RJSfv3uMAVMo+2rBIGHPBnvgLrZciIs2cDKei1/p6Wc/aCzUoHyMAg2R6tw4ZCBKGg==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-linux-ppc64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-ppc64/-/ripgrep-linux-ppc64-1.18.0.tgz", + "integrity": "sha512-quXVY8fwQ8O/lvU1yrSqSl3jlUzysRSb+AfUfCL/tRtphxsKlFvPAejryZ6vg4Bgvn8XL74xb4qMCDmWgYrT5w==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-linux-riscv64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-riscv64/-/ripgrep-linux-riscv64-1.18.0.tgz", + "integrity": "sha512-f5kBQBrWfQt8Q7OhSORuNDei5dkYagBj3y4jImSUXGMy8B/Ke7SltSRcUtjPv166FAFfHCAmWuZp3+cWnX2/Vw==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-linux-s390x": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-s390x/-/ripgrep-linux-s390x-1.18.0.tgz", + "integrity": "sha512-rTOcJFGGcl2c07RUOWUo4U1ndnemKhY6A9hnMB18uk7jSgJc0d/QLBGWMWpumdtoJtpizn/wIv5mXIisJukusQ==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-linux-x64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-linux-x64/-/ripgrep-linux-x64-1.18.0.tgz", + "integrity": "sha512-mQ3bVrUpnD2vs7QT0vX90Lt0cnUq467uFtEktIdsJJmW296RoSULRGqWgzG1AKxyBpNDD6l4ZO4qKf6SgyC23Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@vscode/ripgrep-win32-arm64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-win32-arm64/-/ripgrep-win32-arm64-1.18.0.tgz", + "integrity": "sha512-vfTIjq1OHnzUjxZcHVQAMbnggp8dpGf+0QKFOZHwWPqFwXxQC8eCWM+5NUdoJ6yrElCeMzoUTXoK/LdZaniB+Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@vscode/ripgrep-win32-ia32": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-win32-ia32/-/ripgrep-win32-ia32-1.18.0.tgz", + "integrity": "sha512-//rfAE+BOw5AC2EMmepmiE36jUuevtQYNQqqlw1s3m9FlRxjxEut97RkRPHAu9BG4mSojatZx+kXZXNdyI9caQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@vscode/ripgrep-win32-x64": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/@vscode/ripgrep-win32-x64/-/ripgrep-win32-x64-1.18.0.tgz", + "integrity": "sha512-KNPvtElldqILHdnAetujPaowkNbpqJy3ssIGGN6F6Kve9Qi+nNLI2DN01O83JjCEVQbCzl8Ov3QZ9Eov3BR8Dg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@vscode/windows-ca-certs": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@vscode/windows-ca-certs/-/windows-ca-certs-0.3.4.tgz", + "integrity": "sha512-DcDLjBpu8srh6wUiZqEMyhXHzNDO81ecZOttL3+1u3Iht4CS6Qtxy5WkTPX/aDgbheASO/MK8yg6uLq58RzEWg==", + "hasInstallScript": true, + "license": "BSD", + "optional": true, + "os": [ + "win32" + ], + "dependencies": { + "node-addon-api": "^8.2.0" + } + }, + "node_modules/@vscode/windows-ca-certs/node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/@wishforge/ide-policy": { + "resolved": "policy", + "link": true + }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/advanced-mark.js": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/advanced-mark.js/-/advanced-mark.js-2.7.1.tgz", + "integrity": "sha512-OVoypiDXWqP+BCfXznAvwiyXZth/SF36R8SCsqptAA+0CdpX8DX9FH1qZ1OhrJxOeaSF4AgkeCFd+6EmsNAqww==", + "license": "MIT" + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/aggregate-error": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", + "license": "MIT", + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/anser": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/anser/-/anser-2.3.5.tgz", + "integrity": "sha512-vcZjxvvVoxTeR5XBNJB38oTu/7eDCZlwdz32N1eNgpyPF7j/Z7Idf+CUwQOkKKpJ7RJyjxgLHCM7vdIK0iCNMQ==", + "license": "MIT" + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "license": "Python-2.0" + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/async-mutex": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.4.1.tgz", + "integrity": "sha512-WfoBo4E/TbCX1G95XTjbWTE3X2XLG0m1Xbv2cwOtuPdyH9CZvnaA5nCt1ucjaKEgW2A5IF71hxrRhr83Je5xjA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/axios": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/b4a": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz", + "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==", + "license": "Apache-2.0", + "peerDependencies": { + "react-native-b4a": "*" + }, + "peerDependenciesMeta": { + "react-native-b4a": { + "optional": true + } + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/bare-events": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz", + "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", + "license": "Apache-2.0", + "peerDependencies": { + "bare-abort-controller": "*" + }, + "peerDependenciesMeta": { + "bare-abort-controller": { + "optional": true + } + } + }, + "node_modules/bare-fs": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.4.tgz", + "integrity": "sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ==", + "license": "Apache-2.0", + "dependencies": { + "bare-events": "^2.5.4", + "bare-path": "^3.0.0", + "bare-stream": "^2.6.4", + "bare-url": "^2.2.2", + "fast-fifo": "^1.3.2" + }, + "engines": { + "bare": ">=1.28.0" + }, + "peerDependencies": { + "bare-buffer": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + } + } + }, + "node_modules/bare-path": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz", + "integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==", + "license": "Apache-2.0" + }, + "node_modules/bare-stream": { + "version": "2.13.4", + "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz", + "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==", + "license": "Apache-2.0", + "dependencies": { + "b4a": "^1.8.1", + "streamx": "^2.25.0", + "teex": "^1.0.1" + }, + "peerDependencies": { + "bare-abort-controller": "*", + "bare-buffer": "*", + "bare-events": "*" + }, + "peerDependenciesMeta": { + "bare-abort-controller": { + "optional": true + }, + "bare-buffer": { + "optional": true + }, + "bare-events": { + "optional": true + } + } + }, + "node_modules/bare-url": { + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.5.tgz", + "integrity": "sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q==", + "license": "Apache-2.0", + "dependencies": { + "bare-path": "^3.0.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/basic-auth": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz", + "integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/basic-auth/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/bent": { + "version": "7.3.12", + "resolved": "https://registry.npmjs.org/bent/-/bent-7.3.12.tgz", + "integrity": "sha512-T3yrKnVGB63zRuoco/7Ybl7BwwGZR0lceoVG5XmQyMIH9s19SV5m+a8qam4if0zQuAmOQTyPTPmsQBdAorGK3w==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "bytesish": "^0.4.1", + "caseless": "~0.12.0", + "is-stream": "^2.0.0" + } + }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/binary": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", + "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffers": "~0.1.1", + "chainsaw": "~0.1.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/bl/-/bl-1.2.3.tgz", + "integrity": "sha512-pvcNpa0UU69UT341rO6AYy4FVAIkUHuZXRIWbq+zHnsVcRzDDjIAhGuuYoi0d//cwIwtt4pkpKycWEfjdV+vww==", + "license": "MIT", + "dependencies": { + "readable-stream": "^2.3.5", + "safe-buffer": "^5.1.1" + } + }, + "node_modules/bluebird": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", + "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.8", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz", + "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.16.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/body-parser/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/body-parser/node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/boolean": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", + "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", + "dev": true, + "license": "ISC" + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-alloc": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz", + "integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==", + "license": "MIT", + "dependencies": { + "buffer-alloc-unsafe": "^1.1.0", + "buffer-fill": "^1.0.0" + } + }, + "node_modules/buffer-alloc-unsafe": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz", + "integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==", + "license": "MIT" + }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/buffer-fill": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz", + "integrity": "sha512-T7zexNBwiiaCOGDg9xNX9PBmjrubblRkENuptryuI64URkXDFum9il/JGL8Lm8wYfAXpredVXXZz7eMHilimiQ==", + "license": "MIT" + }, + "node_modules/buffer-indexof-polyfill": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", + "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/buffers": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", + "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==", + "dev": true, + "engines": { + "node": ">=0.2.0" + } + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/bytesish": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/bytesish/-/bytesish-0.4.4.tgz", + "integrity": "sha512-i4uu6M4zuMUiyfZN4RU2+i9+peJh//pXhd9x1oSe1LBkZ3LEbCoygu8W0bXTukU1Jme2txKuotpCZRaC3FLxcQ==", + "dev": true, + "license": "(Apache-2.0 AND MIT)" + }, + "node_modules/cacheable-lookup": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", + "integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.6.0" + } + }, + "node_modules/cacheable-request": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz", + "integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==", + "dev": true, + "license": "MIT", + "dependencies": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^4.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^6.0.1", + "responselike": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable-request/node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/chai": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.5.0.tgz", + "integrity": "sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chainsaw": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", + "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==", + "dev": true, + "license": "MIT/X11", + "dependencies": { + "traverse": ">=0.3.0 <0.4" + }, + "engines": { + "node": "*" + } + }, + "node_modules/chalk": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.0.0.tgz", + "integrity": "sha512-N9oWFcegS0sFr9oh1oz2d7Npos6vNoWW9HvtCg5N1KRFpUhaAhvTv5Y58g880fZaEYSNm3qDz8SU1UrGvp+n7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/chromium-bidi": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-16.0.1.tgz", + "integrity": "sha512-J63PGu/9PpeCwLIcKYyzWP6yaVL5pxuBc0shlYCYM8BaAkmlwiQboXO1iNbOgSDbVklEyYFfNEcHD8oOAWacUA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "mitt": "^3.0.1", + "zod": "^3.24.1" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, + "node_modules/chromium-bidi/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/ci-info": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", + "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/clone-response": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz", + "integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/comlink": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/comlink/-/comlink-4.4.2.tgz", + "integrity": "sha512-OxGdvBmJuNKSCMO4NTl1L47VRp6xn2wG4F/2hYzB6tiCb709otOxtEYCSvK80PtjODfXXZu8ds+Nw5kVCjqd2g==", + "license": "Apache-2.0" + }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "license": "MIT" + }, + "node_modules/confbox": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.1.tgz", + "integrity": "sha512-cKUSoKa8YxFZZSmraVi7onONx3amu77ngK3kGpsYHDH7drPwCRkQE1RYMPlLRrMtnciRj274XNRxcHxnKmDSnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", + "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/decompress": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/decompress/-/decompress-4.2.1.tgz", + "integrity": "sha512-e48kc2IjU+2Zw8cTb6VZcJQ3lgVbS4uuB1TfCHbiZIP/haNXm+SVyhu+87jts5/3ROpd82GSVCoNs/z8l4ZOaQ==", + "license": "MIT", + "dependencies": { + "decompress-tar": "^4.0.0", + "decompress-tarbz2": "^4.0.0", + "decompress-targz": "^4.0.0", + "decompress-unzip": "^4.0.1", + "graceful-fs": "^4.1.10", + "make-dir": "^1.0.0", + "pify": "^2.3.0", + "strip-dirs": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/decompress-response/node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/decompress-tar": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/decompress-tar/-/decompress-tar-4.1.1.tgz", + "integrity": "sha512-JdJMaCrGpB5fESVyxwpCx4Jdj2AagLmv3y58Qy4GE6HMVjWz1FeVQk1Ct4Kye7PftcdOo/7U7UKzYBJgqnGeUQ==", + "license": "MIT", + "dependencies": { + "file-type": "^5.2.0", + "is-stream": "^1.1.0", + "tar-stream": "^1.5.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/decompress-tar/node_modules/is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decompress-tar/node_modules/tar-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-1.6.2.tgz", + "integrity": "sha512-rzS0heiNf8Xn7/mpdSVVSMAWAoy9bfb1WOTYC78Z0UQKeKa/CWS8FOq0lKGNa8DWKAn9gxjCvMLYc5PGXYlK2A==", + "license": "MIT", + "dependencies": { + "bl": "^1.0.0", + "buffer-alloc": "^1.2.0", + "end-of-stream": "^1.0.0", + "fs-constants": "^1.0.0", + "readable-stream": "^2.3.0", + "to-buffer": "^1.1.1", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/decompress-tarbz2": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/decompress-tarbz2/-/decompress-tarbz2-4.1.1.tgz", + "integrity": "sha512-s88xLzf1r81ICXLAVQVzaN6ZmX4A6U4z2nMbOwobxkLoIIfjVMBg7TeguTUXkKeXni795B6y5rnvDw7rxhAq9A==", + "license": "MIT", + "dependencies": { + "decompress-tar": "^4.1.0", + "file-type": "^6.1.0", + "is-stream": "^1.1.0", + "seek-bzip": "^1.0.5", + "unbzip2-stream": "^1.0.9" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/decompress-tarbz2/node_modules/file-type": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-6.2.0.tgz", + "integrity": "sha512-YPcTBDV+2Tm0VqjybVd32MHdlEGAtuxS3VAYsumFokDSMG+ROT5wawGlnHDoz7bfMcMDt9hxuXvXwoKUx2fkOg==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/decompress-tarbz2/node_modules/is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decompress-targz": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/decompress-targz/-/decompress-targz-4.1.1.tgz", + "integrity": "sha512-4z81Znfr6chWnRDNfFNqLwPvm4db3WuZkqV+UgXQzSngG3CEKdBkw5jrv3axjjL96glyiiKjsxJG3X6WBZwX3w==", + "license": "MIT", + "dependencies": { + "decompress-tar": "^4.1.1", + "file-type": "^5.2.0", + "is-stream": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/decompress-targz/node_modules/is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha512-uQPm8kcs47jx38atAcWTVxyltQYoPT68y9aWYdV6yWXSyW8mzSat0TL6CiWdZeCdF3KrAvpVtnHbTv4RN+rqdQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decompress-unzip": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/decompress-unzip/-/decompress-unzip-4.0.1.tgz", + "integrity": "sha512-1fqeluvxgnn86MOh66u8FjbtJpAFv5wgCT9Iw8rcBqQcCo5tO8eiJw7NNTrvt9n4CRBVq7CstiS922oPgyGLrw==", + "license": "MIT", + "dependencies": { + "file-type": "^3.8.0", + "get-stream": "^2.2.0", + "pify": "^2.3.0", + "yauzl": "^2.4.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/decompress-unzip/node_modules/file-type": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-3.9.0.tgz", + "integrity": "sha512-RLoqTXE8/vPmMuTI88DAzhMYC99I8BWv7zYP4A1puo5HIjEJ5EX48ighy4ZyKMG9EDXxBgW6e++cn7d1xuFghA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/deep-eql": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.4.tgz", + "integrity": "sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/defer-to-connect": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz", + "integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-indent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-5.0.0.tgz", + "integrity": "sha512-rlpvsxUtM0PQvy9iZe640/IWwWYyBsTApREbA1pHOpmOUIl9MkP/U4z7vTtg4Oaojvqhxt7sdufnT0EzGaR31g==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/devtools-protocol": { + "version": "0.0.1624250", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1624250.tgz", + "integrity": "sha512-YFAat/lOiIk0ARmBweG+ygrEcbZrq5B9urRyUoeQKp53MlidHXE2TmTbxKcaXoQj7u/aX+jebDO4BW55rs0WwA==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/diff": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.2.2.tgz", + "integrity": "sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/dompurify": { + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", + "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/drivelist": { + "version": "12.0.2", + "resolved": "https://registry.npmjs.org/drivelist/-/drivelist-12.0.2.tgz", + "integrity": "sha512-Nps4pc1ukIqDj7v00wGgBkS7P3VVEZZKcaTPVcE1Yl+dLojXuEv76BuSg6HgmhjeOFIIMz8q7Y+2tux6gYqCvg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "bindings": "^1.5.0", + "debug": "^4.3.4", + "node-addon-api": "^8.0.0", + "prebuild-install": "^7.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/drivelist/node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/engine.io": { + "version": "6.6.11", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.11.tgz", + "integrity": "sha512-z34mGpLoY/82ZbkX1LqGMIaf3wjVMPL6gVC681QDqnmzJ26synI8qAE32P+a7UazmpJZ8UGrFIeAavgRfXzYrg==", + "license": "MIT", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "@types/ws": "^8.5.12", + "accepts": "~1.3.4", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.21.0" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-client": { + "version": "6.6.7", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.7.tgz", + "integrity": "sha512-GyAvmPA7gnRCpDQbYACAy79Lg4ewevrmaPzySZz0OVvgyZc3gEfLLqPTYk8wVBScjOEpM9ZO4KryyFpVItjGEA==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.21.0", + "xmlhttprequest-ssl": "~2.1.1" + } + }, + "node_modules/engine.io-client/node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/engine.io/node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/es-abstract": { + "version": "1.24.2", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", + "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-abstract-get": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-abstract-get/-/es-abstract-get-1.0.0.tgz", + "integrity": "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.2", + "is-callable": "^1.2.7", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.4.tgz", + "integrity": "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-abstract-get": "^1.0.0", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "is-callable": "^1.2.7", + "is-date-object": "^1.1.0", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/esbuild-plugin-copy": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/esbuild-plugin-copy/-/esbuild-plugin-copy-2.1.1.tgz", + "integrity": "sha512-Bk66jpevTcV8KMFzZI1P7MZKZ+uDcrZm2G2egZ2jNIvVnivDpodZI+/KnpL3Jnap0PBdIHU7HwFGB8r+vV5CVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.2", + "chokidar": "^3.5.3", + "fs-extra": "^10.0.1", + "globby": "^11.0.3" + }, + "peerDependencies": { + "esbuild": ">= 0.14.0" + } + }, + "node_modules/esbuild-plugin-copy/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/esbuild-plugin-copy/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/esbuild-plugin-copy/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/esbuild-plugin-copy/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/esbuild-plugins-node-modules-polyfill": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/esbuild-plugins-node-modules-polyfill/-/esbuild-plugins-node-modules-polyfill-1.8.3.tgz", + "integrity": "sha512-DSWWgkQUkavjuyvuaTSd7FpOOZgMpsgmzANoNCCDtOt6NeK5k5bxrn/kSGxnEyiRfSvfIlwgYfOL7s6RRLaxKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jspm/core": "^2.1.0", + "local-pkg": "^1.2.1", + "resolve.exports": "^2.0.3" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.14.0 <=0.28.x" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "dev": true, + "license": "MIT" + }, + "node_modules/events-universal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz", + "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==", + "license": "Apache-2.0", + "dependencies": { + "bare-events": "^2.7.0" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/execa": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-2.1.0.tgz", + "integrity": "sha512-Y/URAVapfbYy2Xp/gb6A0E7iR8xeqOCXsuuaoMn7A5PzrXUK84E1gyiEfq0wQd/GHA6GsoHWwhNq8anb0mleIw==", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.0", + "get-stream": "^5.0.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^3.0.0", + "onetime": "^5.1.0", + "p-finally": "^2.0.0", + "signal-exit": "^3.0.2", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": "^8.12.0 || >=9.7.0" + } + }, + "node_modules/execa/node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/exponential-backoff": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", + "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/express": { + "version": "4.22.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz", + "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.13", + "proxy-addr": "~2.0.7", + "qs": "~6.16.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.7.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.1.tgz", + "integrity": "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/exsolve": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.1.3.tgz", + "integrity": "sha512-kuzL9zherLQoqDeQaS55AiiIg1kb4KYXaSusTtgZTPlvKP2gGCI82LNmBNh5RjDVUXIcmgx+/Mx7vPwRzBbhJA==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-fifo": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", + "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "license": "MIT" + }, + "node_modules/fast-plist": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/fast-plist/-/fast-plist-0.1.3.tgz", + "integrity": "sha512-d9cEfo/WcOezgPLAC/8t8wGb6YOD6JTCPMw2QcG2nAdFmyY+9rTUizCTaGjIZAloWENTEUMAPpkUAIJJJ0i96A==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, + "node_modules/file-icons-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/file-icons-js/-/file-icons-js-1.0.3.tgz", + "integrity": "sha512-n4zoKEpMaAxBTUB7wtgrFBa4dM3b7mBLLA1VI/Q5Cdk/k2UA8S8oaxvnECp3QOzg0Dn+KKRzfIHF7qSdRkA65Q==", + "license": "MIT" + }, + "node_modules/file-type": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-5.2.0.tgz", + "integrity": "sha512-Iq1nJ6D2+yIO4c8HHg4fyVb8mAJieo1Oloy1mLLaB2PvezNedhBVm+QU7g0qM42aiMbRXTxKKwGD17rjKNJYVQ==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/filename-reserved-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/filename-reserved-regex/-/filename-reserved-regex-2.0.0.tgz", + "integrity": "sha512-lc1bnsSr4L4Bdif8Xb/qrtokGbq5zlsms/CYH8PP+WtCkGNF65DPiQY8vG3SakEdRn8Dlnm+gW/qWKKjS5sZzQ==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/filenamify": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/filenamify/-/filenamify-4.3.0.tgz", + "integrity": "sha512-hcFKyUG57yWGAzu1CMt/dPzYZuv+jAJUT85bL8mrXvNe6hWj6yEHEc4EdcgiA6Z3oi1/9wXJdZPXF2dZNgwgOg==", + "license": "MIT", + "dependencies": { + "filename-reserved-regex": "^2.0.0", + "strip-outer": "^1.0.1", + "trim-repeated": "^1.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/find-yarn-workspace-root": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", + "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "micromatch": "^4.0.2" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", + "dev": true, + "license": "BSD-3-Clause", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz", + "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/font-awesome": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/font-awesome/-/font-awesome-4.7.0.tgz", + "integrity": "sha512-U6kGnykA/6bFmg1M/oT9EkFeIYv7JlX3bozwQJWiiLz6L0w3F5vBVPxHlwyX/vtNq1ckcpRKOB9f2Qal/VtFpg==", + "license": "(OFL-1.1 AND MIT)", + "engines": { + "node": ">=0.10.3" + } + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/fs-extra": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-4.0.3.tgz", + "integrity": "sha512-q6rbdDd1o2mAnQreO7YADIxf/Whx4AHBiRf6d+/cVT8h44ss+lHgxf1FemcqDnQt9X3ct4McHr+JMGlYSsK7Cg==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/fstream": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", + "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", + "deprecated": "This package is no longer supported.", + "dev": true, + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/fstream/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fstream/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/fstream/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "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 i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fstream/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/fstream/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/fstream/node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.2.0.tgz", + "integrity": "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2", + "hasown": "^2.0.4", + "is-callable": "^1.2.7", + "is-document.all": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fuzzy": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/fuzzy/-/fuzzy-0.1.3.tgz", + "integrity": "sha512-/gZffu4ykarLrCiP3Ygsa86UAo1E5vEVlvTrpkKywXSbP9Xhln3oSp9QSV57gEq3JFFpGJ4GZ+5zdEp3FcUh4w==", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-2.3.1.tgz", + "integrity": "sha512-AUGhbbemXxrZJRD5cDvKtQxLuYaIbNtDTK8YqupCI393Q2KSTreEsLUN3ZxAWFGiKTzL6nKuzfcIvieflUX9qA==", + "license": "MIT", + "dependencies": { + "object-assign": "^4.0.1", + "pinkie-promise": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/glob": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", + "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", + "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 i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/glob/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/global-agent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz", + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "boolean": "^3.0.1", + "es6-error": "^4.1.1", + "matcher": "^3.0.0", + "roarr": "^2.15.3", + "semver": "^7.3.2", + "serialize-error": "^7.0.1" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globby/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/got": { + "version": "11.8.6", + "resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz", + "integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/is": "^4.0.0", + "@szmarczak/http-timer": "^4.0.5", + "@types/cacheable-request": "^6.0.1", + "@types/responselike": "^1.0.0", + "cacheable-lookup": "^5.0.3", + "cacheable-request": "^7.0.2", + "decompress-response": "^6.0.0", + "http2-wrapper": "^1.0.0-beta.5.2", + "lowercase-keys": "^2.0.0", + "p-cancelable": "^2.0.0", + "responselike": "^2.0.0" + }, + "engines": { + "node": ">=10.19.0" + }, + "funding": { + "url": "https://github.com/sindresorhus/got?sponsor=1" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "license": "ISC" + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true, + "license": "MIT", + "bin": { + "he": "bin/he" + } + }, + "node_modules/hono": { + "version": "4.13.13", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz", + "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", + "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz", + "integrity": "sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/http-proxy": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", + "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "license": "MIT", + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/http-proxy-agent/node_modules/@tootallnate/once": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.1.tgz", + "integrity": "sha512-HqmEUIGRJ5fSXchkVgR5F7qn48bDBzv0kWj/Kfu5e6uci4UlEeng4331LnBkWffb++Ei3FOVLxo8JJWMFBDMeQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/http-server": { + "version": "14.1.1", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-14.1.1.tgz", + "integrity": "sha512-+cbxadF40UXd9T01zUHgA+rlo2Bg1Srer4+B4NwIHdaGxAGGv59nYRnGGDJ9LBk7alpS0US+J+bLLdQOOkJq4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "basic-auth": "^2.0.1", + "chalk": "^4.1.2", + "corser": "^2.0.1", + "he": "^1.2.0", + "html-encoding-sniffer": "^3.0.0", + "http-proxy": "^1.18.1", + "mime": "^1.6.0", + "minimist": "^1.2.6", + "opener": "^1.5.1", + "portfinder": "^1.0.28", + "secure-compare": "3.0.1", + "union": "~0.5.0", + "url-join": "^4.0.1" + }, + "bin": { + "http-server": "bin/http-server" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/http-server/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/http-server/node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/http-status-codes": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/http-status-codes/-/http-status-codes-1.4.0.tgz", + "integrity": "sha512-JrT3ua+WgH8zBD3HEJYbeEgnuQaAnUeRRko/YojPAJjGmIfGD3KPU/asLdsLwKjfxOmQe5nXMQ0pt/7MyapVbQ==", + "license": "MIT" + }, + "node_modules/http2-wrapper": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz", + "integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "quick-lru": "^5.1.1", + "resolve-alpn": "^1.0.0" + }, + "engines": { + "node": ">=10.19.0" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/idb": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/idb/-/idb-4.0.5.tgz", + "integrity": "sha512-P+Fk9HT2h1DhXoE1YNK183SY+CRh2GHNh28de94sGwhe0bUA75JJeVJWt3SenE5p0BXK7maflIq29dl6UZHrFw==", + "license": "ISC" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-6.0.2.tgz", + "integrity": "sha512-InwqeHHN2XpumIkMvpl/DCJVrAHgCsG5+cn1XlnLWGwtZBm8QJfSusItfrwx81CTp5agNZqpKU2J/ccC5nGT4A==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/inversify": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/inversify/-/inversify-6.2.2.tgz", + "integrity": "sha512-KB836KHbZ9WrUnB8ax5MtadOwnqQYa+ZJO3KWbPFgcr4RIEnHM621VaqFZzOZd9+U7ln6upt9n0wJei7x2BNqw==", + "license": "MIT", + "dependencies": { + "@inversifyjs/common": "1.4.0", + "@inversifyjs/core": "1.3.5" + }, + "peerDependencies": { + "reflect-metadata": "~0.2.2" + } + }, + "node_modules/ip-address": { + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-document.all": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz", + "integrity": "sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-electron": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/is-electron/-/is-electron-2.2.2.tgz", + "integrity": "sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg==", + "license": "MIT" + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-natural-number": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-natural-number/-/is-natural-number-4.0.1.tgz", + "integrity": "sha512-Y4LTamMe0DDQIIAlaer9eKebAlDSV6huy+TWhJVPlzZh2o4tRP5SQWFlLn5N0To4mDD22/qdOq+veo1cSISLgQ==", + "license": "MIT" + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-plain-obj": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-1.1.0.tgz", + "integrity": "sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/isomorphic.js": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz", + "integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==", + "license": "MIT", + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jschardet": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/jschardet/-/jschardet-2.3.0.tgz", + "integrity": "sha512-6I6xT7XN/7sBB7q8ObzKbmv5vN+blzLcboDE1BNEsEfmRXJValMxO6OIRT69ylPBRemS3rw6US+CMCar0OBc9g==", + "license": "LGPL-2.1+", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/json-stable-stringify": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz", + "integrity": "sha512-qtYiSSFlwot9XHtF9bD9c7rwKjr+RecWT//ZnPvSmEjpV5mmPOCN4j8UjY5hbjNkOwZ/jQv3J6R1/pL7RwgMsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "isarray": "^2.0.5", + "jsonify": "^0.0.1", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/jsonc-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", + "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", + "license": "MIT" + }, + "node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "license": "MIT", + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonify": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.1.tgz", + "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==", + "dev": true, + "license": "Public Domain", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/just-performance": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/just-performance/-/just-performance-4.3.0.tgz", + "integrity": "sha512-L7RjvtJsL0QO8xFs5wEoDDzzJwoiowRw6Rn/GnvldlchS2JQr9wFYPiwZcDfrbbujEKqKN0tvENdbjXdYhDp5Q==", + "license": "MIT" + }, + "node_modules/keytar": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/keytar/-/keytar-7.9.0.tgz", + "integrity": "sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^4.3.0", + "prebuild-install": "^7.0.1" + } + }, + "node_modules/keytar/node_modules/node-addon-api": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", + "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==", + "license": "MIT" + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, + "node_modules/lib0": { + "version": "0.2.119", + "resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.119.tgz", + "integrity": "sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==", + "license": "MIT", + "dependencies": { + "isomorphic.js": "^0.2.4" + }, + "bin": { + "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js", + "0gentesthtml": "bin/gentesthtml.js", + "0serve": "bin/0serve.js" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/limiter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/limiter/-/limiter-2.1.0.tgz", + "integrity": "sha512-361TYz6iay6n+9KvUUImqdLuFigK+K79qrUtBsXhJTLdH4rIt/r1y8r1iozwh8KbZNpujbFTSh74mJ7bwbAMOw==", + "license": "MIT", + "dependencies": { + "just-performance": "4.3.0" + } + }, + "node_modules/linkify-it": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz", + "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^2.0.0" + } + }, + "node_modules/listenercount": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", + "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/local-pkg": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.2.1.tgz", + "integrity": "sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.3.0", + "quansync": "^0.2.11" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.clonedeep": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz", + "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", + "license": "MIT" + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", + "license": "MIT" + }, + "node_modules/lodash.throttle": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz", + "integrity": "sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ==", + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/log-update": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz", + "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^4.3.0", + "cli-cursor": "^3.1.0", + "slice-ansi": "^4.0.0", + "wrap-ansi": "^6.2.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "license": "ISC" + }, + "node_modules/luxon": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-2.5.2.tgz", + "integrity": "sha512-Yg7/RDp4nedqmLgyH0LwgGRvMEKVzKbUdkBYyCosbHgJ+kaOUx0qzSiSatVc3DFygnirTPYnMM2P5dg2uH1WvA==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/macaddress": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/macaddress/-/macaddress-0.5.4.tgz", + "integrity": "sha512-i8xVWoUjj2woYU8kbpQby86Kq7uF7xl2brtKREXUBWpfgqx1fKXEeYzDiVMVxA/IufC1d3xxwJRHtFCX+9IspA==", + "license": "MIT" + }, + "node_modules/make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "license": "MIT", + "dependencies": { + "pify": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/make-dir/node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/markdown-it": { + "version": "14.3.2", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.2.tgz", + "integrity": "sha512-sHHjZ5fJKlgrG4qns2YwVcdNep35h5fERrfkD2YNsb9UFk0UIHarbiTaHKVMlPuWAoiilyK8Fv/jAm11slsY7Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.5.0", + "linkify-it": "^5.0.2", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it-anchor": { + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-9.2.1.tgz", + "integrity": "sha512-p6APiLJDFAW2GEvaavDvhIBn7jrX2jLv77NkBGgNacFTurbORYc4pyYySg/mI6mpR6cHQuAtzKtmqgQr4K8dsQ==", + "license": "Unlicense", + "peerDependencies": { + "@types/markdown-it": "*", + "markdown-it": "*" + } + }, + "node_modules/markdown-it-emoji": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/markdown-it-emoji/-/markdown-it-emoji-3.1.0.tgz", + "integrity": "sha512-NhmMEH2ywduD4Nty1E8uB5NqfLhAT1VR0dyvoJyStKOqCzbZmVdn/+8wj7zpDsb/fLBikpCPsWwxqKlvMmbz4g==", + "license": "MIT" + }, + "node_modules/marked": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz", + "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==", + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/matcher": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", + "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mdurl": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", + "integrity": "sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==", + "license": "MIT" + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mitt": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", + "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", + "dev": true, + "license": "MIT" + }, + "node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true, + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/mocha": { + "version": "11.8.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-11.8.0.tgz", + "integrity": "sha512-VyCeUdGN3A9lmCTTgG4yuvY9ixxaDk+xt2R/7/+1AP6EqNG+G9OKkzBwhVtVYoNX8YsxNSgAl8mOv3IAeOpFbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "browser-stdout": "^1.3.1", + "chokidar": "^4.0.1", + "debug": "^4.3.5", + "diff": "^7.0.0", + "escape-string-regexp": "^4.0.0", + "find-up": "^5.0.0", + "glob": "^10.4.5", + "he": "^1.2.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", + "log-symbols": "^4.1.0", + "minimatch": "^9.0.5", + "ms": "^2.1.3", + "picocolors": "^1.1.1", + "serialize-javascript": "^6.0.2", + "strip-json-comments": "^3.1.1", + "supports-color": "^8.1.1", + "workerpool": "^9.2.0", + "yargs": "^17.7.2", + "yargs-parser": "^21.1.1", + "yargs-unparser": "^2.0.0" + }, + "bin": { + "_mocha": "bin/_mocha", + "mocha": "bin/mocha.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/mocha/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/mocha/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/mocha/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/mocha/node_modules/diff": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", + "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/mocha/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "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 i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mocha/node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mocha/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/mocha/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/modern-tar": { + "version": "0.7.7", + "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.7.7.tgz", + "integrity": "sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/mount-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mount-point/-/mount-point-3.0.0.tgz", + "integrity": "sha512-jAhfD7ZCG+dbESZjcY1SdFVFqSJkh/yGbdsifHcPkvuLRO5ugK0Ssmd9jdATu29BTd4JiN+vkpMzVvsUgP3SZA==", + "license": "MIT", + "dependencies": { + "@sindresorhus/df": "^1.0.1", + "pify": "^2.3.0", + "pinkie-promise": "^2.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mount-point/node_modules/@sindresorhus/df": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@sindresorhus/df/-/df-1.0.1.tgz", + "integrity": "sha512-1Hyp7NQnD/u4DSxR2DGW78TF9k7R0wZ8ev0BpMAIzA6yTQSHqNb5wTuvtcPYf4FWbVse2rW7RgDsyL8ua2vXHw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/move-file": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/move-file/-/move-file-2.1.0.tgz", + "integrity": "sha512-i9qLW6gqboJ5Ht8bauZi7KlTnQ3QFpBCvMvFfEcHADKgHGeJ9BZMO7SFCTwHPV9Qa0du9DYY1Yx3oqlGt30nXA==", + "license": "MIT", + "dependencies": { + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10.17" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/msgpackr": { + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.12.1.tgz", + "integrity": "sha512-4EUH9tQHnMmEgzW/MdAP0KIfa1T9AF+htl0ffe2n5vb2EKn9y2co8ccpgWko6S52Jy1PQZKwRnx5/KkYjtd9MQ==", + "license": "MIT", + "optionalDependencies": { + "msgpackr-extract": "^3.0.2" + } + }, + "node_modules/msgpackr-extract": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.4.tgz", + "integrity": "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "node-gyp-build-optional-packages": "5.2.2" + }, + "bin": { + "download-msgpackr-prebuilds": "bin/download-prebuilds.js" + }, + "optionalDependencies": { + "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" + } + }, + "node_modules/multer": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.4.0.tgz", + "integrity": "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/nano": { + "version": "10.1.4", + "resolved": "https://registry.npmjs.org/nano/-/nano-10.1.4.tgz", + "integrity": "sha512-bJOFIPLExIbF6mljnfExXX9Cub4W0puhDjVMp+qV40xl/DBvgKao7St4+6/GB6EoHZap7eFnrnx4mnp5KYgwJA==", + "deprecated": "nano@10 is now deprecated. Please visit https://www.npmjs.com/package/nano for the latest version", + "license": "Apache-2.0", + "dependencies": { + "axios": "^1.7.4", + "node-abort-controller": "^3.1.1", + "qs": "^6.13.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "4.37.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.37.0.tgz", + "integrity": "sha512-O9XXMXLeRHQtvh43NCah3y9N1K69tecOmu8Y5p2ay4iXvtpbQr0VaroJF9EmRVp3vkdoj3qn4IFfX+ZYtC94fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.6.3" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/node-abort-controller": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz", + "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==", + "license": "MIT" + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "license": "MIT" + }, + "node_modules/node-api-version": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/node-api-version/-/node-api-version-0.2.1.tgz", + "integrity": "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + } + }, + "node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/node-gyp-build-optional-packages": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz", + "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==", + "license": "MIT", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.1" + }, + "bin": { + "node-gyp-build-optional-packages": "bin.js", + "node-gyp-build-optional-packages-optional": "optional.js", + "node-gyp-build-optional-packages-test": "build-test.js" + } + }, + "node_modules/node-gyp/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "node_modules/node-gyp/node_modules/undici": { + "version": "6.29.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.0.tgz", + "integrity": "sha512-R+RODBqp6i2pPflGdq+xIOUkl+RNfGgHwoinecKu/JCuf2uO06cOKoDbI2P7Dn6KcswdKwrczbU6IYJ6K8X+wg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/node-gyp/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/node-pty": { + "version": "1.2.0-beta.12", + "resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.2.0-beta.12.tgz", + "integrity": "sha512-uExTCG/4VmSJa4+TjxFwPXv8BfacmfFEBL6JpxCMDghcwqzvD0yTcGmZ1fKOK6HY33tp0CelLblqTECJizc+Yw==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^7.1.0" + } + }, + "node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", + "dev": true, + "license": "ISC", + "dependencies": { + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-url": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", + "integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-3.1.0.tgz", + "integrity": "sha512-Dbl4A/VfiVGLgQv29URL9xshU8XDY1GeLy+fsaZ1AA8JDSfjvr5P5+pzRbWqRSBxk6/DW7MIh8lTM/PaGnP2kg==", + "license": "MIT", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/open": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-7.4.2.tgz", + "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/open-collaboration-protocol": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/open-collaboration-protocol/-/open-collaboration-protocol-0.3.0.tgz", + "integrity": "sha512-zvas595nQCGgrV4EDooFG0eGCd4sFyc+wuGqovTdyHD6DsZCYdol3SeHQgy3PZxxvPf18i1QXkPSzRc8RUmgiw==", + "license": "MIT", + "dependencies": { + "base64-js": "~1.5.1", + "fflate": "~0.8.2", + "msgpackr": "~1.11.2", + "semver": "~7.7.1", + "socket.io-client": "~4.8.1" + }, + "engines": { + "node": ">=20.10.0", + "npm": ">=10.2.3" + } + }, + "node_modules/open-collaboration-protocol/node_modules/msgpackr": { + "version": "1.11.14", + "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.11.14.tgz", + "integrity": "sha512-suPZQcjFtPGp0cksn70ICfLuxsO9F2/sRrbJzeNepojZ+OPwGzA0lNdLyU4SJUKAd5ZgvUWWPojzzdlVuOYcrQ==", + "license": "MIT", + "optionalDependencies": { + "msgpackr-extract": "^3.0.2" + } + }, + "node_modules/open-collaboration-protocol/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/open-collaboration-yjs": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/open-collaboration-yjs/-/open-collaboration-yjs-0.3.0.tgz", + "integrity": "sha512-XQk8ywZO5JiQo1QlRWcqR3C9RvEUuWi5FSDooIVqe/jZy9RMwQZs5ywz0a5cP8XQ7sTDhh6WjPwtG67laUP6uw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.103", + "open-collaboration-protocol": "~0.3.0", + "vscode-languageserver-textdocument": "~1.0.12", + "y-protocols": "~1.0.6" + }, + "engines": { + "node": ">=20.10.0", + "npm": ">=10.2.3" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/opener": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz", + "integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==", + "dev": true, + "license": "(WTFPL OR MIT)", + "bin": { + "opener": "bin/opener-bin.js" + } + }, + "node_modules/opfs-worker": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/opfs-worker/-/opfs-worker-1.3.1.tgz", + "integrity": "sha512-bQwEhkXm8ODfhoVflyKgd3exbUXfnA9kZ5wxb/o9M83y725SXawjrTaAwzJ3DKcYkEosiOkTeOphBwd/8br34w==", + "license": "MIT", + "dependencies": { + "comlink": "^4.4.2", + "minimatch": "^10.0.3" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/os-homedir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "integrity": "sha512-B5JU3cabzk8c67mRRd3ECmROafjYMXbuzlwtqdM8IbS8ktlTix8aFGb2bAGKrSRIlnfKwovGUUr72JUPyOb6kQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/own-keys": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz", + "integrity": "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-cancelable": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", + "integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/p-debounce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-debounce/-/p-debounce-2.1.0.tgz", + "integrity": "sha512-M9bMt62TTnozdZhqFgs+V7XD2MnuKCaz+7fZdlu2/T7xruI3uIE5CicQ0vx1hV7HIUYF0jF+4/R1AgfOkl74Qw==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/p-finally": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-2.0.1.tgz", + "integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-map": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", + "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", + "license": "MIT", + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-8.1.1.tgz", + "integrity": "sha512-aNZ+VfjobsWryoiPnEApGGmf5WmNsCo9xu8dfaYamG5qaLP7ClhLN6NgsFe6SwJ2UbLEBK5dv9x8Mn5+RVhMWQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.1", + "p-timeout": "^6.1.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue/node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/p-timeout": { + "version": "6.1.4", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-6.1.4.tgz", + "integrity": "sha512-MyIV3ZA/PmyBN/ud8vV9XzwTrNtR4jFrObymZYnZqMmW0zA8Z17vnT0rBgFE/TlohB+YCHqXMgZzb3Csp49vqg==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/patch-package": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz", + "integrity": "sha512-VsKRIA8f5uqHQ7NGhwIna6Bx6D9s/1iXlA1hthBVBEbkq+t4kXD0HHt+rJhf/Z+Ci0F/HCB2hvn0qLdLG+Qxlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^10.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.2.4", + "yaml": "^2.2.2" + }, + "bin": { + "patch-package": "index.js" + }, + "engines": { + "node": ">=14", + "npm": ">5" + } + }, + "node_modules/patch-package/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/patch-package/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/patch-package/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/patch-package/node_modules/slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/patch-package/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-root": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/path-root/-/path-root-0.1.1.tgz", + "integrity": "sha512-QLcPegTHF11axjfojBIoDygmS2E3Lf+8+jI6wOVmNVenrKSo3mFdSGiIgdSHenczw3wPtlVMQaFVwGmM7BJdtg==", + "license": "MIT", + "dependencies": { + "path-root-regex": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-root-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-root-regex/-/path-root-regex-0.1.2.tgz", + "integrity": "sha512-4GlJ6rZDhQZFE0DPVKh0e9jmZ5egZfxTkp7bcRDuPlJXbAwhxcl2dINPUAsjLdejqaLsCeg8axcLjIbvBjN4pQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/pdfobject": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/pdfobject/-/pdfobject-2.3.1.tgz", + "integrity": "sha512-vluuGiSDmMGpOvWFGiUY4trNB8aGKLDVxIXuuGHjX0kK3bMxCANUVtLivctE7uejLBScWCnbVarKatFVvdwXaQ==", + "license": "MIT" + }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, + "node_modules/perfect-scrollbar": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/perfect-scrollbar/-/perfect-scrollbar-1.5.5.tgz", + "integrity": "sha512-dzalfutyP3e/FOpdlhVryN4AJ5XDVauVWxybSkLZmakFE2sS3y3pc4JnSprw8tGmHvkaG5Edr5T7LBTZ+WWU2g==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pinkie": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz", + "integrity": "sha512-MnUuEycAemtSaeFSjXKW/aroV7akBbY+Sv+RkyqFjgAe73F+MR0TBWKBRDkmfWq/HiFmdavfZ1G7h4SPZXaCSg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pinkie-promise": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz", + "integrity": "sha512-0Gni6D4UcLTbv9c57DfxDGdr41XfgUjqWZu492f0cIGr16zDU06BWP/RAEvOuo7CQ0CNjHaLlM59YJJFm3NWlw==", + "license": "MIT", + "dependencies": { + "pinkie": "^2.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/pkg-types": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.3.tgz", + "integrity": "sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.1", + "pathe": "^2.0.3" + } + }, + "node_modules/portfinder": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.38.tgz", + "integrity": "sha512-rEwq/ZHlJIKw++XtLAO8PPuOQA/zaPJOZJ37BVuN97nLpMJeuDVLVGRwbFoBgLudgdTMP2hdRJP++H+8QOA3vg==", + "dev": true, + "license": "MIT", + "dependencies": { + "async": "^3.2.6", + "debug": "^4.3.6" + }, + "engines": { + "node": ">= 10.12" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/prebuild-install/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/prebuild-install/node_modules/node-abi": { + "version": "3.98.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.98.0.tgz", + "integrity": "sha512-Llh8noNw7s15m+rmIrZnZQbe4gLyasL9loT74rC92PkmwWKeEedKvc7o6pjp8B3MhrYT/Cl846NOYZbz1wmddw==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/prebuild-install/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prebuild-install/node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/prebuild-install/node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/puppeteer": { + "version": "25.1.0", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-25.1.0.tgz", + "integrity": "sha512-7L6/0JM7XStK99lIL4xQySyNEXNfII6pk0BxkI5kKBTOhR7AsoQiv067YTsE/rIXxQiq9ajlO4WcqBjS/FWK1A==", + "dev": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@puppeteer/browsers": "3.0.4", + "chromium-bidi": "16.0.1", + "devtools-protocol": "0.0.1624250", + "lilconfig": "^3.1.3", + "puppeteer-core": "25.1.0", + "typed-query-selector": "^2.12.2" + }, + "bin": { + "puppeteer": "lib/puppeteer/node/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/puppeteer-core": { + "version": "25.1.0", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.1.0.tgz", + "integrity": "sha512-jKzy5y4WG6uNuFbTWgW1D7mqoT9o0nllc/6a1DGF775T1mPmgw3scdFEtEq67yVFikavQmbYq6NLfbTfxHSlqQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@puppeteer/browsers": "3.0.4", + "chromium-bidi": "16.0.1", + "devtools-protocol": "0.0.1624250", + "typed-query-selector": "^2.12.2", + "webdriver-bidi-protocol": "0.4.2", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/puppeteer-to-istanbul": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/puppeteer-to-istanbul/-/puppeteer-to-istanbul-1.4.0.tgz", + "integrity": "sha512-dzW8u/PMqMZppvoXCFod8IkCTI2JL0yP2YUBbaALnX+iJJ6gqjk77fIoK9MqnMqRZAcoa81GLFfZExakWg/Q4Q==", + "dev": true, + "license": "ISC", + "dependencies": { + "clone": "^2.1.2", + "mkdirp": "^1.0.4", + "v8-to-istanbul": "^1.2.1", + "yargs": "^15.3.1" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/puppeteer-to-istanbul/node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/puppeteer-to-istanbul/node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.16.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.1.tgz", + "integrity": "sha512-5Px6J7rfHBAGUhNQ3es4YzcOdBBw0SDcVtThJml4RdnKw4tKs2epA0kPZ+K8X+WiHktT93RHVcQ/3ym5aTCgtg==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/quansync": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", + "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/rc/node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, + "node_modules/react-perfect-scrollbar": { + "version": "1.5.8", + "resolved": "https://registry.npmjs.org/react-perfect-scrollbar/-/react-perfect-scrollbar-1.5.8.tgz", + "integrity": "sha512-bQ46m70gp/HJtiBOF3gRzBISSZn8FFGNxznTdmTG8AAwpxG1bJCyn7shrgjEvGSQ5FJEafVEiosY+ccER11OSA==", + "license": "MIT", + "dependencies": { + "perfect-scrollbar": "^1.5.0", + "prop-types": "^15.6.1" + }, + "peerDependencies": { + "react": ">=16.3.3", + "react-dom": ">=16.3.3" + } + }, + "node_modules/react-textarea-autosize": { + "version": "8.5.9", + "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.5.9.tgz", + "integrity": "sha512-U1DGlIQN5AwgjTyOEnI1oCcMuEr1pv1qOtklB2l4nyMGbHzWrI0eFsYK0zos2YWqAolJyG0IWJaqWmWj5ETh0A==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.20.13", + "use-composed-ref": "^1.3.0", + "use-latest": "^1.2.1" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/react-tooltip": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-4.5.1.tgz", + "integrity": "sha512-Zo+CSFUGXar1uV+bgXFFDe7VeS2iByeIp5rTgTcc2HqtuOS5D76QapejNNfx320MCY91TlhTQat36KGFTqgcvw==", + "license": "MIT", + "dependencies": { + "prop-types": "^15.8.1", + "uuid": "^7.0.3" + }, + "engines": { + "npm": ">=6.13" + }, + "peerDependencies": { + "react": ">=16.0.0", + "react-dom": ">=16.0.0" + } + }, + "node_modules/react-tooltip/node_modules/uuid": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-7.0.3.tgz", + "integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/react-virtuoso": { + "version": "2.19.1", + "resolved": "https://registry.npmjs.org/react-virtuoso/-/react-virtuoso-2.19.1.tgz", + "integrity": "sha512-zF6MAwujNGy2nJWCx/Df92ay/RnV2Kj4glUZfdyadI4suAn0kAZHB1BeI7yPFVp2iSccLzFlszhakWyr+fJ4Dw==", + "license": "MIT", + "dependencies": { + "@virtuoso.dev/react-urx": "^0.2.12", + "@virtuoso.dev/urx": "^0.2.12" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": ">=16 || >=17 || >= 18", + "react-dom": ">=16 || >=17 || >= 18" + } + }, + "node_modules/read-binary-file-arch": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", + "integrity": "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "bin": { + "read-binary-file-arch": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0" + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "dev": true, + "license": "ISC" + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/resolve-alpn": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz", + "integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/resolve-package-path": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/resolve-package-path/-/resolve-package-path-4.0.3.tgz", + "integrity": "sha512-SRpNAPW4kewOaNUt8VPqhJ0UMxawMwzJD8V7m1cJfdSTK9ieZwS6K7Dabsm4bmLFM96Z5Y/UznrpG5kt1im8yA==", + "license": "MIT", + "dependencies": { + "path-root": "^0.1.1" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/resolve.exports": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.4.tgz", + "integrity": "sha512-zepuGL0ulf+nt+XaFrlKeaiTJeyPFPLLY62+ncq1/VTHBdt3HsfXOH60priZ6tnXQozdGcDeIF5JVTanvIcYWQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/responselike": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz", + "integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lowercase-keys": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rimraf": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-5.0.10.tgz", + "integrity": "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==", + "license": "ISC", + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/rimraf/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/rimraf/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "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 i@izs.me", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/rimraf/node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/roarr": { + "version": "2.15.4", + "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "boolean": "^3.0.1", + "detect-node": "^2.0.4", + "globalthis": "^1.0.1", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/route-parser": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/route-parser/-/route-parser-0.0.5.tgz", + "integrity": "sha512-nsii+MXoNb7NyF05LP9kaktx6AoBVT/7zUgDnzIb5IoYAvYkbZOAuoLJjVdsyEVxWv0swCxWkKDK4cMva+WDBA==", + "license": "MIT", + "engines": { + "node": ">= 0.9" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/router/node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", + "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "get-intrinsic": "^1.3.0", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT", + "peer": true + }, + "node_modules/secure-compare": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz", + "integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==", + "dev": true, + "license": "MIT" + }, + "node_modules/seek-bzip": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/seek-bzip/-/seek-bzip-1.0.6.tgz", + "integrity": "sha512-e1QtP3YL5tWww8uKaOCQ18UxIT2laNBXHjV/S2WYCiK4udiv8lkG89KRIoCjUagnAmCBurjF4zEVX2ByBbnCjQ==", + "license": "MIT", + "dependencies": { + "commander": "^2.8.1" + }, + "bin": { + "seek-bunzip": "bin/seek-bunzip", + "seek-table": "bin/seek-bzip-table" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/serialize-error": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", + "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "type-fest": "^0.13.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/serialize-error/node_modules/type-fest": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", + "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/serialize-javascript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz", + "integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "dev": true, + "license": "ISC" + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "dev": true, + "license": "MIT" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socket.io": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.4.tgz", + "integrity": "sha512-9ZV9zg8vN8hO3Y25DhR7nUkJ1VDnBhq5O/JrXhFT9s6+F0gqytSASTHVfCFc2mJXaTfARroErplXlzFWwETZqQ==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.5.8", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.8.tgz", + "integrity": "sha512-6Oy52pbg+kvdCVvjcN+FnY7BvxZ7cIHNScbvztT/It5d0vbwoJoVZmF2gjJmnV0/4WlXRfG15zc45ySk9Ah8bw==", + "license": "MIT", + "dependencies": { + "debug": "~4.4.1", + "ws": "~8.21.0" + } + }, + "node_modules/socket.io-adapter/node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/socket.io-client": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.4.tgz", + "integrity": "sha512-7wjKAvVXYOJsbmUgkWbnhPD4bFpkqrUR0++XOjpGFmqDqsqV1CI93VTraeExLxpjxEqrWgFoSRZu1ihjLWfkAA==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1", + "engine.io-client": "~6.6.1", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz", + "integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.10", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz", + "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-5.0.1.tgz", + "integrity": "sha512-vZdmnjb9a2Tz6WEQVIurybSwElwPxMZaIc7PzqbJTrezcKNznv6giT7J7tZDZ1BojVaa1jvO/UiUdhDVB0ACoQ==", + "license": "MIT", + "dependencies": { + "agent-base": "^6.0.2", + "debug": "4", + "socks": "^2.3.3" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/sort-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/sort-keys/-/sort-keys-2.0.0.tgz", + "integrity": "sha512-/dPCrG1s3ePpWm6yBbxZq5Be1dXGLyLn9Z791chDC3NFrpkVbWGzkBwPN1knaciexFXgRJ7hzdnwZ4stHSDmjg==", + "license": "MIT", + "dependencies": { + "is-plain-obj": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "dev": true, + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/stat-mode": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-1.0.0.tgz", + "integrity": "sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/streamx": { + "version": "2.28.1", + "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz", + "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==", + "license": "MIT", + "dependencies": { + "events-universal": "^1.0.0", + "fast-fifo": "^1.3.2", + "text-decoder": "^1.1.0" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/string-argv": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.1.2.tgz", + "integrity": "sha512-mBqPGEOMNJKXRo7z0keX0wlAhbBAjilUdPW13nN0PecVryZxdHIeM7TqbsSUA7VYuS00HGC6mojP7DlQzfa9ZA==", + "license": "MIT", + "engines": { + "node": ">=0.6.19" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.11.tgz", + "integrity": "sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-object-atoms": "^1.1.2", + "has-property-descriptors": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.10.tgz", + "integrity": "sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-dirs": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/strip-dirs/-/strip-dirs-2.1.0.tgz", + "integrity": "sha512-JOCxOeKLm2CAS73y/U4ZeZPTkE+gNVCzKt7Eox84Iej1LT/2pTWYpZKJuxwQpvX1LiZb1xokNR7RLfuBAa7T3g==", + "license": "MIT", + "dependencies": { + "is-natural-number": "^4.0.1" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-outer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/strip-outer/-/strip-outer-1.0.1.tgz", + "integrity": "sha512-k55yxKHwaXnpYGsOzg4Vl8+tDrWylxDEpknGjhTiZB8dFRU5rTo9CAzeycivxV3s+zlTKwrs6WxMxR95n26kwg==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-outer/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/sumchecker": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", + "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.1.0" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tar": { + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tar-fs": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz", + "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0", + "tar-stream": "^3.1.5" + }, + "optionalDependencies": { + "bare-fs": "^4.0.1", + "bare-path": "^3.0.0" + } + }, + "node_modules/tar-stream": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.2.tgz", + "integrity": "sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==", + "license": "MIT", + "dependencies": { + "b4a": "^1.9.0", + "bare-fs": "^4.8.2", + "fast-fifo": "^1.3.2", + "streamx": "^2.28.1" + } + }, + "node_modules/teex": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", + "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==", + "license": "MIT", + "dependencies": { + "streamx": "^2.12.5" + } + }, + "node_modules/temp": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz", + "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mkdirp": "^0.5.1", + "rimraf": "~2.6.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/temp/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/temp/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/temp/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "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 i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/temp/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/temp/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/temp/node_modules/rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/text-decoder": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz", + "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==", + "license": "Apache-2.0", + "dependencies": { + "b4a": "^1.6.4" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, + "node_modules/to-buffer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.2.2.tgz", + "integrity": "sha512-db0E3UJjcFhpDhAF4tLo03oli3pwl3dbnzXOUIlRKrp+ldk/VUxzpWYZENsw2SZiuBjHAk7DfB0VU7NKdpb6sw==", + "license": "MIT", + "dependencies": { + "isarray": "^2.0.5", + "safe-buffer": "^5.2.1", + "typed-array-buffer": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/trash": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/trash/-/trash-7.2.0.tgz", + "integrity": "sha512-3bR8Z5aWO8b9qybS6skBoaavH/hX9Onb1RrdIIhJxv9VpH3aBtpbKuAX4rIh/0xpDZ7K4ga36wONk/okbhjTlA==", + "license": "MIT", + "dependencies": { + "@stroncium/procfs": "^1.2.1", + "globby": "^7.1.1", + "is-path-inside": "^3.0.2", + "make-dir": "^3.1.0", + "move-file": "^2.0.0", + "p-map": "^4.0.0", + "uuid": "^8.3.2", + "xdg-trashdir": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/trash/node_modules/array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha512-Dxr6QJj/RdU/hCaBjOfxW+q6lyuVE6JFWIrAUpuOOhoJJoQ99cUn3igRaHVB5P9WrgFVN0FfArM3x0cueOU8ng==", + "license": "MIT", + "dependencies": { + "array-uniq": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/trash/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/trash/node_modules/brace-expansion": { + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/trash/node_modules/dir-glob": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-2.2.2.tgz", + "integrity": "sha512-f9LBi5QWzIW3I6e//uxZoLBlUt9kcp66qo0sSCxL6YZKc75R1c4MFCoe/LaZiBGmgujvQdxc5Bn3QhfyvK5Hsw==", + "license": "MIT", + "dependencies": { + "path-type": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/trash/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "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 i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/trash/node_modules/globby": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/globby/-/globby-7.1.1.tgz", + "integrity": "sha512-yANWAN2DUcBtuus5Cpd+SKROzXHs2iVXFZt/Ykrfz6SAXqacLX25NZpltE+39ceMexYF4TtEadjuSTw8+3wX4g==", + "license": "MIT", + "dependencies": { + "array-union": "^1.0.1", + "dir-glob": "^2.0.0", + "glob": "^7.1.2", + "ignore": "^3.3.5", + "pify": "^3.0.0", + "slash": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/trash/node_modules/ignore": { + "version": "3.3.10", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", + "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==", + "license": "MIT" + }, + "node_modules/trash/node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/trash/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/trash/node_modules/path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "license": "MIT", + "dependencies": { + "pify": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/trash/node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/trash/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/trash/node_modules/slash": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz", + "integrity": "sha512-3TYDR7xWt4dIqV2JauJr+EJeW356RXijHeUlO+8djJ+uBXPn8/2dpzBc8yQhh583sVvc9CvFAeQVgijsH+PNNg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/trash/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/traverse": { + "version": "0.3.10", + "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.10.tgz", + "integrity": "sha512-pd6fq5qmiFuPA3TpdqBCqJXlOrSdCSt0l9IZDg83Vbf4x3m/X18prEwMMVM5LXp9vGL9NxjeiDGBrTasqyngXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-to-primitive": "^1.3.4", + "gopd": "^1.2.0", + "typedarray.prototype.slice": "^1.0.6", + "which-typed-array": "^1.1.24" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/trim-repeated": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/trim-repeated/-/trim-repeated-1.0.0.tgz", + "integrity": "sha512-pkonvlKk8/ZuR0D5tLW8ljt5I8kmxp2XKymhepUeOdCEfKpZaktSArkLHZt76OB1ZvO9bssUsDty4SWhLvZpLg==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/trim-repeated/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/ts-md5": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/ts-md5/-/ts-md5-1.3.1.tgz", + "integrity": "sha512-DiwiXfwvcTeZ5wCE0z+2A9EseZsztaiZtGrtSaY5JOD7ekPnR/GoIVD5gXZAlK9Na9Kvpo9Waz5rW64WKAWApg==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-detect": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.1.0.tgz", + "integrity": "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.5.tgz", + "integrity": "sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.8.tgz", + "integrity": "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "for-each": "^0.3.5", + "gopd": "^1.2.0", + "is-typed-array": "^1.1.15", + "possible-typed-array-names": "^1.1.0", + "reflect.getprototypeof": "^1.0.10" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-query-selector": { + "version": "2.12.3", + "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz", + "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==", + "dev": true, + "license": "MIT" + }, + "node_modules/typedarray.prototype.slice": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/typedarray.prototype.slice/-/typedarray.prototype.slice-1.0.6.tgz", + "integrity": "sha512-r+7YvGfM5TkTiDQ5EqWi/Z4L4KP3jUI+YCmTtWg1tmTHUw6xladLJqzR2heMaHBIM0TTFLZmn/EkIaEHYs/bIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "math-intrinsics": "^1.1.0", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-offset": "^1.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/uc.micro": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "license": "MIT" + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/unbzip2-stream": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", + "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==", + "license": "MIT", + "dependencies": { + "buffer": "^5.2.1", + "through": "^2.3.8" + } + }, + "node_modules/undici": { + "version": "7.30.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz", + "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, + "node_modules/union": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz", + "integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==", + "dev": true, + "dependencies": { + "qs": "^6.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/unzipper": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.9.15.tgz", + "integrity": "sha512-2aaUvO4RAeHDvOCuEtth7jrHFaCKTSXPqUkXwADaLBzGbgZGzUDccoEdJ5lW+3RmfpOZYNx0Rw6F6PUzM6caIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "^1.0.12", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/url-join": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", + "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/use-composed-ref": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/use-composed-ref/-/use-composed-ref-1.4.0.tgz", + "integrity": "sha512-djviaxuOOh7wkj0paeO1Q/4wMZ8Zrnag5H6yBvzN7AKKe8beOaED9SF5/ByLqsku8NP4zQqsvM2u3ew/tJK8/w==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-isomorphic-layout-effect": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.2.1.tgz", + "integrity": "sha512-tpZZ+EX0gaghDAiFR37hj5MgY6ZN55kLiPkJsKxBMZ6GZdOSPJXiOzPM984oPYZ5AnehYx5WQp1+ME8I/P/pRA==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/use-latest": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/use-latest/-/use-latest-1.3.0.tgz", + "integrity": "sha512-mhg3xdm9NaM8q+gLT8KryJPnRFOz1/5XPBhmDEVZK1webPzDjrPk7f/mbpeLqTgB9msytYWANxgALOCJKnLvcQ==", + "license": "MIT", + "dependencies": { + "use-isomorphic-layout-effect": "^1.1.1" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/user-home": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/user-home/-/user-home-2.0.0.tgz", + "integrity": "sha512-KMWqdlOcjCYdtIJpicDSFBQ8nFwS2i9sslAd6f4+CBGcU4gist2REnr2fxj2YocvJFxSF3ZOHLYLVZnUxv4BZQ==", + "license": "MIT", + "dependencies": { + "os-homedir": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", + "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/v8-to-istanbul": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-1.2.1.tgz", + "integrity": "sha512-NglPycIwSQeSJj7VJ6L8vTsPKC9MG5Lcx4n3SvYqNHzklbMI4dGcLJnkLPEPJ3uB8UyTdWviMhM0Ptq+xD5UFQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10.10.0" + } + }, + "node_modules/valid-filename": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/valid-filename/-/valid-filename-2.0.1.tgz", + "integrity": "sha512-7eF/iUZ5SPd3FighoKgatSjXDJ25Vopo/6yvEKGyX4FIeZVHcLjHmyvbQ1WdFD9RQZ9PoBA7nrSxxAz/oC64SQ==", + "license": "MIT", + "dependencies": { + "filename-reserved-regex": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vhost": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/vhost/-/vhost-3.0.2.tgz", + "integrity": "sha512-S3pJdWrpFWrKMboRU4dLYgMrTgoPALsmYwOvyebK2M6X95b9kQrjZy5rwl3uzzpfpENe/XrNYu/2U+e7/bmT5g==", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/vscode-jsonrpc": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", + "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", + "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "8.2.0", + "vscode-languageserver-types": "3.17.5" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.15", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.15.tgz", + "integrity": "sha512-Gsfr9S8LU3S6885cS+NaleasJ0n3V5y/SOTqHCifQiXWFw3G9w9/YItDfwHrlCz+dSZWWZ8ilYVMcJe7Sz7Sxw==", + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.17.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", + "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", + "license": "MIT" + }, + "node_modules/vscode-oniguruma": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/vscode-oniguruma/-/vscode-oniguruma-2.0.1.tgz", + "integrity": "sha512-poJU8iHIWnC3vgphJnrLZyI3YdqRlR27xzqDmpPXYzA93R4Gk8z7T6oqDzDoHjoikA2aS82crdXFkjELCdJsjQ==", + "license": "MIT" + }, + "node_modules/vscode-textmate": { + "version": "9.3.2", + "resolved": "https://registry.npmjs.org/vscode-textmate/-/vscode-textmate-9.3.2.tgz", + "integrity": "sha512-n2uGbUcrjhUEBH16uGA0TvUfhWwliFZ1e3+pTjrkim1Mt7ydB41lV08aUvsi70OlzDWp6X7Bx3w/x3fAXIsN0Q==", + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.0.8.tgz", + "integrity": "sha512-AyFQ0EVmsOZOlAnxoFOGOq1SQDWAB7C6aqMGS23svWAllfOaxbuFvcT8D1i8z3Gyn8fraVeZNNmN6e9bxxXkKw==", + "license": "MIT" + }, + "node_modules/webdriver-bidi-protocol": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.2.tgz", + "integrity": "sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/whatwg-encoding": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", + "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/which-typed-array": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", + "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/workerpool": { + "version": "9.3.4", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-9.3.4.tgz", + "integrity": "sha512-TmPRQYYSAnnDiEB0P/Ytip7bFGvqnSU6I2BcuSw7Hx+JSg/DsUi5ebYfc8GYaSdpuvOcEs6dXxPurOYpe9QFwg==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/write-file-atomic": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.3.tgz", + "integrity": "sha512-GaETH5wwsX+GcnzhPgKcKjJ6M2Cq3/iZp1WyY/X1CSqrW+jVNM9Y7D8EC2sM4ZG/V8wZlSniJnCKWPmBYAucRQ==", + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "node_modules/write-json-file": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/write-json-file/-/write-json-file-2.3.0.tgz", + "integrity": "sha512-84+F0igFp2dPD6UpAQjOUX3CdKUOqUzn6oE9sDBNzUXINR5VceJ1rauZltqQB/bcYsx3EpKys4C7/PivKUAiWQ==", + "license": "MIT", + "dependencies": { + "detect-indent": "^5.0.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "pify": "^3.0.0", + "sort-keys": "^2.0.0", + "write-file-atomic": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/write-json-file/node_modules/pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xdg-basedir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", + "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/xdg-trashdir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/xdg-trashdir/-/xdg-trashdir-3.1.0.tgz", + "integrity": "sha512-N1XQngeqMBoj9wM4ZFadVV2MymImeiFfYD+fJrNlcVcOHsJFFQe7n3b+aBoTPwARuq2HQxukfzVpQmAk1gN4sQ==", + "license": "MIT", + "dependencies": { + "@sindresorhus/df": "^3.1.1", + "mount-point": "^3.0.0", + "user-home": "^2.0.0", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz", + "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/xterm": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/xterm/-/xterm-5.3.0.tgz", + "integrity": "sha512-8QqjlekLUFTrU6x7xck1MsPzPA571K5zNqWm0M0oroYEWVOptZ0+ubQSkQ3uxIEhcIHRujJy6emDWX4A7qyFzg==", + "deprecated": "This package is now deprecated. Move to @xterm/xterm instead.", + "license": "MIT" + }, + "node_modules/xterm-addon-fit": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/xterm-addon-fit/-/xterm-addon-fit-0.8.0.tgz", + "integrity": "sha512-yj3Np7XlvxxhYF/EJ7p3KHaMt6OdwQ+HDu573Vx1lRXsVxOcnVJs51RgjZOouIZOczTsskaS+CpXspK81/DLqw==", + "deprecated": "This package is now deprecated. Move to @xterm/addon-fit instead.", + "license": "MIT", + "peerDependencies": { + "xterm": "^5.0.0" + } + }, + "node_modules/xterm-addon-search": { + "version": "0.13.0", + "resolved": "https://registry.npmjs.org/xterm-addon-search/-/xterm-addon-search-0.13.0.tgz", + "integrity": "sha512-sDUwG4CnqxUjSEFh676DlS3gsh3XYCzAvBPSvJ5OPgF3MRL3iHLPfsb06doRicLC2xXNpeG2cWk8x1qpESWJMA==", + "deprecated": "This package is now deprecated. Move to @xterm/addon-search instead.", + "license": "MIT", + "peerDependencies": { + "xterm": "^5.0.0" + } + }, + "node_modules/xterm-addon-webgl": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/xterm-addon-webgl/-/xterm-addon-webgl-0.16.0.tgz", + "integrity": "sha512-E8cq1AiqNOv0M/FghPT+zPAEnvIQRDbAbkb04rRYSxUym69elPWVJ4sv22FCLBqM/3LcrmBLl/pELnBebVFKgA==", + "deprecated": "This package is now deprecated. Move to @xterm/addon-webgl instead.", + "license": "MIT", + "peerDependencies": { + "xterm": "^5.0.0" + } + }, + "node_modules/y-protocols": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/y-protocols/-/y-protocols-1.0.7.tgz", + "integrity": "sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.85" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + }, + "peerDependencies": { + "yjs": "^13.0.0" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-unparser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", + "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "camelcase": "^6.0.0", + "decamelize": "^4.0.0", + "flat": "^5.0.2", + "is-plain-obj": "^2.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-unparser/node_modules/is-plain-obj": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", + "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, + "node_modules/yjs": { + "version": "13.6.33", + "resolved": "https://registry.npmjs.org/yjs/-/yjs-13.6.33.tgz", + "integrity": "sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==", + "license": "MIT", + "dependencies": { + "lib0": "^0.2.99" + }, + "engines": { + "node": ">=16.0.0", + "npm": ">=8.0.0" + }, + "funding": { + "type": "GitHub Sponsors ❤", + "url": "https://github.com/sponsors/dmonad" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + }, + "policy": { + "name": "@wishforge/ide-policy", + "version": "0.1.0", + "peerDependencies": { + "@theia/collaboration": "1.76.0", + "@theia/core": "1.76.0" + } + } + } +} diff --git a/apps/ide/package.json b/apps/ide/package.json new file mode 100644 index 0000000..ab966ac --- /dev/null +++ b/apps/ide/package.json @@ -0,0 +1,69 @@ +{ + "name": "@wishforge/ide", + "version": "0.1.0", + "private": true, + "engines": { + "node": ">=22.14.0 <27" + }, + "scripts": { + "build": "theia build --mode development", + "build:production": "theia build --mode production", + "start": "node scripts/start.mjs", + "test": "node --test gateway/test/*.test.mjs provisioner/test/*.test.mjs coordination/test/*.test.cjs security/test/*.test.cjs policy/test/*.test.cjs collaboration/test/client-factory.test.cjs", + "plugins:download": "theia download:plugins && node scripts/download-python-debugger.mjs && node scripts/verify-managed-plugins.mjs", + "plugins:download:python": "node scripts/download-python-debugger.mjs", + "plugins:verify": "node scripts/verify-managed-plugins.mjs" + }, + "dependencies": { + "@theia/core": "1.76.0", + "@theia/editor": "1.76.0", + "@theia/filesystem": "1.76.0", + "@theia/workspace": "1.76.0", + "@theia/navigator": "1.76.0", + "@theia/preferences": "1.76.0", + "@theia/messages": "1.76.0", + "@theia/terminal": "1.76.0", + "@theia/process": "1.76.0", + "@theia/monaco": "1.76.0", + "@theia/scm": "1.76.0", + "@theia/debug": "1.76.0", + "@theia/markers": "1.76.0", + "@theia/search-in-workspace": "1.76.0", + "@theia/outline-view": "1.76.0", + "@theia/callhierarchy": "1.76.0", + "@theia/typehierarchy": "1.76.0", + "@theia/file-search": "1.76.0", + "@theia/mini-browser": "1.76.0", + "@theia/plugin-ext": "1.76.0", + "@theia/plugin-ext-vscode": "1.76.0", + "@theia/vsx-registry": "1.76.0", + "@theia/collaboration": "1.76.0", + "@theia/editor-preview": "1.76.0", + "@wishforge/ide-policy": "file:./policy" + }, + "devDependencies": { + "@theia/cli": "1.76.0" + }, + "theia": { + "target": "browser", + "frontend": { + "config": { + "applicationName": "WishForge IDE", + "defaultTheme": "dark", + "defaultIconTheme": "theia-file-icons", + "applicationVersion": "0.1.0", + "preferences": { + "telemetry.telemetryLevel": "off" + } + } + }, + "backend": { + "config": { + "frontendConnectionTimeout": 0 + } + } + }, + "theiaPlugins": { + "vscode-builtin-extensions": "https://github.com/eclipse-theia/vscode-builtin-extensions/releases/download/1.108.2/vscode-builtin-extensions-1.108.2.tar.gz" + } +} diff --git a/apps/ide/policy/README.md b/apps/ide/policy/README.md new file mode 100644 index 0000000..63ae5b7 --- /dev/null +++ b/apps/ide/policy/README.md @@ -0,0 +1,95 @@ +# WishForge IDE policy integration + +This is a real Theia 1.76 frontend/backend extension, loaded by the independent +IDE build. It implements collaboration routing, editor coordination and backend +DAP gates. It does not replace operating-system process isolation. + +## Commands and editor lifecycle + +Use the command palette (`Cmd/Ctrl+Shift+P`): + +- **WishForge: Create Verified Workspace Snapshot** asks every registered client + to freeze its text editors, run `ApplicationShell.saveAll`, return the complete + document version vector, and confirm that vector again. The backend freezes the + participant set and disk digest, requires each acknowledgement, and commits an + immutable-content snapshot with a monotonically increasing saved revision. +- A dirty/unsavable buffer, changed version, new/disconnected participant, expired + acknowledgement or changed disk refuses the snapshot. Frozen editors are + released on success, failure or connection closure. The saved revision is + independent from a requirement's `WishRevision` and from a Git commit SHA. +- **WishForge: Recover Unsaved Draft** reads workspace/actor-scoped IndexedDB + records. Dirty content plus its original baseline survives page reload. Recovery + opens a comparison against the current saved file and an unsaved recovery copy; + it never automatically writes the original. Changed saved contents are explicitly + reported. Saving the current buffer removes its current recovery record, not + unrelated older unconfirmed drafts. Text plus baseline is limited to 2 MiB UTF-8. +- **Acquire Debug Control**, **Transfer Debug Control**, and **Release Debug + Control** manage a 30-second renewable backend lease. A same-actor second tab + does not obtain another tab's token. Tokens remain backend-only; transfer rotates + them and notifies the target client. Connection closure releases its ownership. + +The snapshot orchestration is exposed over the actual Theia service path +`/services/wishforge-coordination`. It is connected to editor/command lifecycle, +not an unattached sample API. Automated Git integration/build must explicitly use +an accepted workspace snapshot if it depends on live human workspace contents; +this RPC does not by itself wire that gate into every platform workflow. + +## Backend identity and DAP enforcement + +The gateway strips caller-supplied `x-wishforge-*` headers and signs the API-granted +actor/role/tenant/workspace with Ed25519. Theia verifies the signature, audience, +scope and expiry. Only the gateway has the private key; the workspace receives +only a pinned public key. Unsigned/forged actor strings cannot acquire the normal +coordination or debug API. Viewer access is denied before the IDE session starts. + +Two actual backend paths are guarded: + +1. Native `/services/debug-adapter/:id` wraps `ForwardingDebugChannel` and checks + the live lease before passing each DAP message to the adapter callback. +2. Bundled VS Code/js-debug adapters travel through `HostedPluginProcess.onMessage`. + The policy validates Theia's nested MessagePack batch and intercepts + `DebugExt.$createDebugSession` / `$terminateDebugSession` and + `ConnectionExt.$sendMessage` / `$deleteConnection`. Unauthorized requests are + never forwarded. A blocked DAP request receives both its RPC failure and a + matching DAP failure notification so the client is not left waiting forever. + +Unrelated plugin RPC bytes are preserved. Tests use real Theia encoders, +RPCProtocol, ConnectionImpl and ForwardingDebugChannel rather than a made-up wire +shape. Real UI acceptance also exercised the bundled js-debug: F5 was denied +without a lease; after acquisition, Node paused, showed stack/variables, and +stepped to a state with `count: 1`. + +## Runtime configuration + +Gateway only: `WF_IDE_GATEWAY_PRIVATE_KEY_FILE`. + +Theia: `WF_IDE_GATEWAY_PUBLIC_KEY_FILE`, `WF_TENANT_ID`, `WF_WORKSPACE_ID`, +`WISHFORGE_WORKSPACE_PATH`, `WF_COORDINATION_STATE_DIR` outside the source tree. +Use `node apps/ide/security/create-local-keys.cjs` for an isolated local fixture +key pair. It prints paths only and never replaces an existing key pair silently. +Missing coordination identity/configuration fails closed for snapshots/debug while +ordinary IDE startup remains possible. Provisioned production instances must use +reviewed public-key configuration and durable state storage. + +## Threat and acceptance boundary + +**A separate directory or PVC is not an OS privilege boundary.** The current +Theia backend and human terminal run under the same UID. A malicious terminal can +modify same-UID writable state or stop/replace that backend. Mode `0700`, read-only +snapshot files and signed gateway assertions do not prevent that threat. These +are authenticated cooperative-client controls and local integrity/recovery checks, +not hard isolation between malicious editors sharing a workspace. + +Do not promote these workspace snapshots into independently trusted release +proof. Final Git verification/build evidence still belongs to the separately +isolated verifier. Strong same-workspace isolation needs direct gateway-to- +coordination-sidecar routing and independently controlled debugger/target processes, +with state inaccessible to the terminal UID; merely moving the state volume is +insufficient. The tenant/workspace Kata boundary remains a separate requirement. + +The lease can transfer between clients, but attaching another user's UI to an +already-running plugin-host-owned debugger session is not implemented by the +lease itself. Room state remains in-memory OCT state: draft comparison recovery +is implemented, not lossless room reconstruction. Python debugger acceptance, +production OIDC identity variants, HA coordination and hostile-terminal containment +remain separate checks. diff --git a/apps/ide/policy/backend.cjs b/apps/ide/policy/backend.cjs new file mode 100644 index 0000000..e2e6e2a --- /dev/null +++ b/apps/ide/policy/backend.cjs @@ -0,0 +1,87 @@ +const { ContainerModule, injectable, inject } = require('@theia/core/shared/inversify'); +const { ConnectionContainerModule } = require('@theia/core/lib/node/messaging/connection-container-module'); +const { MainChannel, DefaultMessagingService } = require('@theia/core/lib/node/messaging/default-messaging-service'); +const { DebugService } = require('@theia/debug/lib/common/debug-service'); +const { DebugServiceImpl } = require('@theia/debug/lib/node/debug-service-impl'); +const { DebugAdapterSessionManager } = require('@theia/debug/lib/node/debug-adapter-session-manager'); +const { ForwardingDebugChannel } = require('@theia/debug/lib/common/debug-service'); +const { HostedPluginProcess } = require('@theia/plugin-ext/lib/hosted/node/hosted-plugin-process'); +const {ProcessManager}=require('@theia/process/lib/node/process-manager'); +const {sleepReceipt}=require('./lifecycle-safety.cjs'); +const { BackendApplicationContribution } = require('@theia/core/lib/node/backend-application'); +const {filterPluginRpc,guardDebugChannel}=require('./plugin-dap-guard.cjs'); +const fs = require('node:fs');const path = require('node:path');const {randomUUID,createHash}=require('node:crypto');const {pathToFileURL}=require('node:url'); +const {verifyAssertion}=require('../security/assertions.cjs'); +const {Coordinator}=require('../coordination/index.cjs'); +const Context=Symbol('WishForgeConnectionContext'),Service=Symbol('WishForgeCoordinatorService'); +const connections=new Map();let engine;let snapshotPending=false;let hostedDebugTouched=false; +function coordinator(){if(!engine){for(const name of ['WISHFORGE_WORKSPACE_PATH','WF_COORDINATION_STATE_DIR','WF_WORKSPACE_ID','WF_TENANT_ID','WF_IDE_GATEWAY_PUBLIC_KEY_FILE'])if(!process.env[name])throw new Error(`COORDINATION_UNCONFIGURED: ${name}`);engine=new Coordinator({workspaceRoot:process.env.WISHFORGE_WORKSPACE_PATH,stateDirectory:process.env.WF_COORDINATION_STATE_DIR});}return engine;} +function actor(channel){coordinator();return verifyAssertion(fs.readFileSync(process.env.WF_IDE_GATEWAY_PUBLIC_KEY_FILE,'utf8'),channel.socket?.request?.headers?.['x-wishforge-actor-assertion'],{tenantId:process.env.WF_TENANT_ID,workspaceId:process.env.WF_WORKSPACE_ID});} +function checkControl(context){const who=actor(context.channel);coordinator().assertDebugController(who.actorId,context.debugToken);return who;} +const timeout=(promise)=>Promise.race([promise,new Promise((_,reject)=>setTimeout(()=>reject(new Error('EDITOR_ACK_TIMEOUT')),10000))]); +class CoordinationService { + constructor(context){this.context=context;} + register(documents){const who=actor(this.context.channel);this.context.actorId=who.actorId;coordinator().register(who.actorId,this.context.id,{documents});return{actorId:who.actorId,clientId:this.context.id,workspaceId:who.workspaceId,workspaceRoot:process.env.WISHFORGE_WORKSPACE_PATH,state:coordinator().state()};} + status(){actor(this.context.channel);return coordinator().state();} + async snapshot(){ + const who=actor(this.context.channel);const participants=[...connections.values()]; + if(snapshotPending)throw new Error('BARRIER_BUSY');snapshotPending=true; + const requestClient=`snapshot-request-${randomUUID()}`; + const prepared=[]; + try{ + for(const entry of participants){const identity=actor(entry.channel);const documents=await timeout(entry.frontend.prepareSnapshot());coordinator().register(identity.actorId,entry.id,{documents});prepared.push({entry,identity,documents});} + coordinator().register(who.actorId,requestClient,{documents:[]}); + const barrier=coordinator().beginBarrier(who.actorId); + coordinator().acknowledge(who.actorId,barrier.id,requestClient,{documents:[]}); + for(const {entry,identity,documents} of prepared){const confirmed=await timeout(entry.frontend.confirmSnapshot(documents));coordinator().acknowledge(identity.actorId,barrier.id,entry.id,{documents:confirmed});} + return await coordinator().commitBarrier(who.actorId,barrier.id); + } finally {coordinator().unregister(who.actorId,requestClient);await Promise.allSettled(participants.map(entry=>timeout(entry.frontend.releaseSnapshot())));snapshotPending=false;} + } + readSaved(relative){actor(this.context.channel);const root=fs.realpathSync(process.env.WISHFORGE_WORKSPACE_PATH);if(typeof relative!=='string'||!relative||path.isAbsolute(relative))throw new Error('INVALID_DOCUMENT_PATH');const file=fs.realpathSync(path.resolve(root,relative));if(!file.startsWith(root+path.sep)||fs.statSync(file).size>4*1024*1024)throw new Error('DOCUMENT_SCOPE');const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);let content;try{const info=fs.fstatSync(fd);if(!info.isFile()||info.size>4*1024*1024)throw new Error('DOCUMENT_SCOPE');content=fs.readFileSync(fd,'utf8');}finally{fs.closeSync(fd);}return{content,digest:createHash('sha256').update(content).digest('hex'),uri:pathToFileURL(file).href};} + acquireDebug(){const who=actor(this.context.channel);this.context.actorId=who.actorId;const lease=coordinator().debugAcquire(who.actorId,this.context.debugToken);this.context.debugToken=lease.token;return{actorId:lease.actorId,expiresAt:lease.expiresAt};} + releaseDebug(){const who=actor(this.context.channel);if(this.context.debugToken)coordinator().debugRelease(who.actorId,this.context.debugToken);this.context.debugToken=undefined;return true;} + async transferDebug(targetClientId){const who=actor(this.context.channel);const target=connections.get(targetClientId);if(!target)throw new Error('TARGET_NOT_CONNECTED');const identity=actor(target.channel);const lease=coordinator().debugTransfer(who.actorId,this.context.debugToken,identity.actorId);target.debugToken=lease.token;this.context.debugToken=undefined;target.frontend.debugGranted().catch(()=>{});return{actorId:identity.actorId,clientId:target.id};} + peers(){actor(this.context.channel);return[...connections.values()].map(entry=>({clientId:entry.id,actorId:actor(entry.channel).actorId}));} +} +class IntegrationHttp { + configure(app){ + const identity=(req,purpose)=>verifyAssertion(fs.readFileSync(process.env.WF_IDE_GATEWAY_PUBLIC_KEY_FILE,'utf8'),req.headers['x-wishforge-actor-assertion'],{tenantId:process.env.WF_TENANT_ID,workspaceId:process.env.WF_WORKSPACE_ID,purpose}); + app.get('/_wishforge/lifecycle/state',(req,res)=>{try{identity(req,'workspace-lifecycle');res.set('Cache-Control','no-store').json({workspaceId:process.env.WF_WORKSPACE_ID,...sleepReceipt({coordinator:coordinator(),processManager:this.processManager,debugManager:this.debugManager,snapshotPending,hostedDebugTouched})});}catch{res.status(409).json({error:'WORKSPACE_ACTIVITY_UNKNOWN'});}}); + app.get('/_wishforge/integration/state',(req,res)=>{try{identity(req,'integration-state');res.set('Cache-Control','no-store').json({workspaceId:process.env.WF_WORKSPACE_ID,...coordinator().inputState()});}catch{res.status(409).json({error:'WORKSPACE_INPUT_UNAVAILABLE'});}}); + app.post('/_wishforge/integration/snapshot',async(req,res)=>{try{identity(req,'interactive');const service=new CoordinationService({channel:{socket:{request:req}}});await service.snapshot();res.set('Cache-Control','no-store').json({workspaceId:process.env.WF_WORKSPACE_ID,...coordinator().inputState()});}catch(error){res.status(409).json({error:'WORKSPACE_SAVE_BARRIER_REQUIRED',message:error.message});}}); + } +} +injectable()(IntegrationHttp);inject(ProcessManager)(IntegrationHttp.prototype,'processManager');inject(DebugAdapterSessionManager)(IntegrationHttp.prototype,'debugManager'); + +// Native debug adapters: no command reaches the adapter without the server lease. +class ScopedMessagingService extends DefaultMessagingService { + getConnectionChannelHandlers(channel){const handlers=super.getConnectionChannelHandlers(channel); + handlers.push('/services/debug-adapter/:id',({id},wsChannel)=>{try{const context=channel.wishforgeContext;const session=this.container.get(DebugAdapterSessionManager).find(id);if(!session||!context){wsChannel.close();return;}session.start(guardDebugChannel(new ForwardingDebugChannel(wsChannel),()=>checkControl(context)));}catch{wsChannel.close();}});return handlers;} +} +injectable()(ScopedMessagingService); +class ScopedDebugService extends DebugServiceImpl { + async createDebugSession(...args){checkControl(this.context);return super.createDebugSession(...args);} + async terminateDebugSession(...args){checkControl(this.context);return super.terminateDebugSession(...args);} + dispose(){super.terminateDebugSession().catch(()=>{});} +} +injectable()(ScopedDebugService);inject(Context)(ScopedDebugService.prototype,'context'); + +// VS Code/js-debug adapters use a different channel inside hosted-plugin RPC. +// Gate those requests on the backend before any payload reaches the plugin host. +class ScopedHostedPluginProcess extends HostedPluginProcess { + onMessage(hostId,payload){try{const result=filterPluginRpc(payload,()=>{checkControl(this.context);hostedDebugTouched=true;});if(result.denied)this.logger.warn('WishForge debug control denied',result.denied);if(result.replies)this.client?.postMessage(hostId,result.replies);if(result.forwarded)super.onMessage(hostId,result.forwarded);}catch(error){this.logger.error('WishForge rejected malformed plugin RPC',error.message);}} +} +injectable()(ScopedHostedPluginProcess);inject(Context)(ScopedHostedPluginProcess.prototype,'context'); +Object.defineProperty(exports,'__esModule',{value:true}); +exports.default=new ContainerModule((bind,_unbind,_isBound,rebind)=>{ + require('./plugin-install-policy.cjs').bindManagedPlugins(rebind); + bind(IntegrationHttp).toSelf().inSingletonScope();bind(BackendApplicationContribution).toService(IntegrationHttp); + rebind(DefaultMessagingService).to(ScopedMessagingService).inSingletonScope(); + bind(ConnectionContainerModule).toConstantValue(ConnectionContainerModule.create(({bind,rebind,bindBackendService})=>{ + bind(Context).toDynamicValue(ctx=>{const channel=ctx.container.get(MainChannel);const context={id:randomUUID(),channel};channel.wishforgeContext=context;channel.onClose(()=>{connections.delete(context.id);try{if(context.actorId){coordinator().unregister(context.actorId,context.id);if(context.debugToken)coordinator().debugRelease(context.actorId,context.debugToken);}}catch{}});return context;}).inSingletonScope(); + bind(Service).toDynamicValue(ctx=>new CoordinationService(ctx.container.get(Context))).inSingletonScope(); + bindBackendService('/services/wishforge-coordination',Service,(service,frontend)=>{service.context.frontend=frontend;connections.set(service.context.id,service.context);return service;}); + rebind(DebugService).to(ScopedDebugService).inSingletonScope(); + rebind(HostedPluginProcess).to(ScopedHostedPluginProcess).inSingletonScope(); + })); +}); diff --git a/apps/ide/policy/coordination-frontend.cjs b/apps/ide/policy/coordination-frontend.cjs new file mode 100644 index 0000000..e975c91 --- /dev/null +++ b/apps/ide/policy/coordination-frontend.cjs @@ -0,0 +1,42 @@ +const { FrontendApplicationContribution, ApplicationShell, OpenerService, open }=require('@theia/core/lib/browser'); +const { CommandContribution, MessageService, QuickInputService, UntitledResourceResolver, URI }=require('@theia/core'); +const { EditorManager }=require('@theia/editor/lib/browser'); +const { WorkspaceService }=require('@theia/workspace/lib/browser'); +const { WebSocketConnectionProvider }=require('@theia/core/lib/browser/messaging/ws-connection-provider'); +const { StatusBar, StatusBarAlignment }=require('@theia/core/lib/browser/status-bar/status-bar'); +const { DiffUris }=require('@theia/core/lib/browser/diff-uris'); +const { DraftStore }=require('./drafts.cjs'); +const Service=Symbol('WishForgeFrontendCoordination'); +const vector=documents=>JSON.stringify(documents.map(d=>({uri:d.uri,version:d.version,dirty:d.dirty})).sort((a,b)=>a.uri.localeCompare(b.uri))); + +class FrontendCoordination { + constructor(services){Object.assign(this,services);this.drafts=new DraftStore(window.indexedDB);this.tracked=new Map();this.frozen=new Map();this.controller=false;this.busy=false;this.draftWarning=false;} + documents(){const documents=new Map();for(const widget of this.editors.all){const doc={uri:widget.editor.uri.toString(),version:widget.editor.document.version,dirty:widget.editor.document.dirty};const previous=documents.get(doc.uri);if(previous&&previous.version!==doc.version)throw new Error('Conflicting editor versions for one document');documents.set(doc.uri,{...doc,dirty:doc.dirty||previous?.dirty===true});}return [...documents.values()];} + async onStart(){ + this.rpc=this.connection.createProxy('/services/wishforge-coordination',{prepareSnapshot:()=>this.prepareSnapshot(),confirmSnapshot:docs=>this.confirmSnapshot(docs),releaseSnapshot:()=>this.releaseSnapshot(),debugGranted:()=>{this.controller=true;return this.heartbeat();}}); + this.rpc.onDidCloseConnection?.(()=>{this.releaseSnapshot();this.controller=false;}); + this.editors.onCreated(widget=>this.track(widget));for(const widget of this.editors.all)this.track(widget); + await this.heartbeat();this.timer=setInterval(()=>this.heartbeat(),5000); + window.addEventListener('pagehide',()=>{for(const widget of this.editors.all)this.persistDraft(widget);}); + } + async heartbeat(){try{this.identity=await this.rpc.register(this.documents());this.scope=`${this.identity.workspaceId}/${this.identity.actorId}`;if(this.controller)await this.rpc.acquireDebug();const state=await this.rpc.status();this.status.setElement('wishforge-coordination',{text:`$(cloud-upload) Saved r${state.revision}${this.controller?' · Debug control':''}`,alignment:StatusBarAlignment.RIGHT,priority:5,tooltip:'WishForge coordinated snapshot and draft recovery',command:'wishforge.snapshot'});if(!this.recoveryNotified){this.recoveryNotified=true;const saved=await this.drafts.list(this.scope);if(saved.length)this.messages.info(`${saved.length} unconfirmed draft(s) are available. Use WishForge: Recover Unsaved Draft to compare them with saved files.`);}}catch{this.controller=false;this.status.setElement('wishforge-coordination',{text:'$(warning) Coordination unavailable',alignment:StatusBarAlignment.RIGHT,priority:5,tooltip:'Snapshots and debug control require authenticated workspace coordination.'});}} + pathFor(widget){const current=widget.editor.uri;for(const root of this.workspace.tryGetRoots()){const prefix=root.resource.path.toString().replace(/\/$/,'')+'/';if(current.scheme===root.resource.scheme&¤t.path.toString().startsWith(prefix))return current.path.toString().slice(prefix.length);}return undefined;} + track(widget){if(this.tracked.has(widget))return;const state={id:window.crypto.randomUUID(),baseText:widget.editor.document.getText(),wasDirty:widget.editor.document.dirty};this.tracked.set(widget,state);const change=()=>{if(!state.timer)state.timer=setTimeout(()=>{state.timer=undefined;this.persistDraft(widget);},120);this.rpc?.register(this.documents()).catch(()=>{});};widget.editor.document.onContentChanged(change);widget.editor.document.onDirtyChanged(change);if(this.busy)this.freeze(widget);} + async persistDraft(widget){const state=this.tracked.get(widget);if(!state||!this.scope)return;const doc=widget.editor.document;const relative=this.pathFor(widget);if(!relative)return; + try{if(doc.dirty){state.wasDirty=true;await this.drafts.put({id:state.id,scope:this.scope,path:relative,uri:widget.editor.uri.toString(),text:doc.getText(),baseText:state.baseText,version:doc.version,updatedAt:Date.now()});}else if(state.wasDirty){await this.drafts.remove(state.id);state.baseText=doc.getText();state.wasDirty=false;}}catch(error){if(!this.draftWarning){this.draftWarning=true;this.messages.warn(`Draft recovery storage unavailable: ${error.message}`);}} + } + freeze(widget){if(this.frozen.has(widget))return;const control=widget.editor.getControl?.();if(!control?.updateOptions)throw new Error('This editor cannot be frozen for a coordinated snapshot');const previous=control.getRawOptions?.().readOnly??widget.editor.readOnly??false;this.frozen.set(widget,{control,previous});control.updateOptions({readOnly:true});} + async prepareSnapshot(){if(this.busy)throw new Error('Editor is already participating in a save barrier');this.busy=true;for(const w of this.editors.all)this.freeze(w);try{await this.shell.saveAll();const docs=this.documents();if(docs.some(doc=>doc.dirty))throw new Error('Unconfirmed or unsaved documents prevent the snapshot');return docs;}catch(error){this.releaseSnapshot();throw error;}} + confirmSnapshot(expected){const docs=this.documents();if(!this.busy||vector(docs)!==vector(expected)||docs.some(doc=>doc.dirty))throw new Error('Document versions changed during the save barrier');return docs;} + releaseSnapshot(){for(const {control,previous}of this.frozen.values())control.updateOptions({readOnly:previous});this.frozen.clear();this.busy=false;return true;} + registerCommands(commands){ + commands.registerCommand({id:'wishforge.snapshot',label:'Create Verified Workspace Snapshot',category:'WishForge'},{execute:async()=>{try{const snapshot=await this.rpc.snapshot();await this.heartbeat();this.messages.info(`Saved workspace revision ${snapshot.revision} (${snapshot.digest.slice(0,12)}).`);}catch(error){this.messages.error(`Snapshot refused: ${error.message}`);}}}); + commands.registerCommand({id:'wishforge.recover-draft',label:'Recover Unsaved Draft',category:'WishForge'},{execute:()=>this.recover()}); + commands.registerCommand({id:'wishforge.debug-acquire',label:'Acquire Debug Control',category:'WishForge'},{execute:async()=>{try{await this.rpc.acquireDebug();this.controller=true;await this.heartbeat();this.messages.info('Debug control acquired for this client.');}catch(error){this.messages.error(error.message);}}}); + commands.registerCommand({id:'wishforge.debug-release',label:'Release Debug Control',category:'WishForge'},{execute:async()=>{await this.rpc.releaseDebug();this.controller=false;await this.heartbeat();}}); + commands.registerCommand({id:'wishforge.debug-transfer',label:'Transfer Debug Control',category:'WishForge'},{execute:async()=>{try{const peers=(await this.rpc.peers()).filter(p=>p.clientId!==this.identity?.clientId);const picked=await this.quick.pick(peers.map(p=>({label:p.actorId,description:p.clientId,value:p.clientId})),{title:'Transfer control to a connected workspace client'});if(picked){await this.rpc.transferDebug(picked.value);this.controller=false;await this.heartbeat();}}catch(error){this.messages.error(error.message);}}}); + } + async recover(){try{if(!this.scope)throw new Error('Authenticated workspace identity unavailable');const records=await this.drafts.list(this.scope);const picked=await this.quick.pick(records.map(record=>({label:record.path,description:new Date(record.updatedAt).toLocaleString(),record})),{title:'Compare an unconfirmed draft with the saved file'});if(!picked)return;const draft=picked.record;const saved=await this.rpc.readSaved(draft.path);const resource=await this.untitled.createUntitledResource(draft.text,draft.path.split('.').at(-1));const left=new URI('mem-txt-readonly:/Saved-file').withQuery(saved.content);await open(this.opener,DiffUris.encode(left,resource.uri,`Saved ↔ recovered ${draft.path}`));this.messages.info(saved.content===draft.baseText?'Draft opened as an unsaved recovery copy. Review and Save As to apply it.':'The saved file changed after this draft. Review the comparison before applying the recovery copy.');}catch(error){this.messages.error(`Draft recovery: ${error.message}`);}} +} +function bindCoordination(bind){bind(Service).toDynamicValue(ctx=>new FrontendCoordination({editors:ctx.container.get(EditorManager),workspace:ctx.container.get(WorkspaceService),shell:ctx.container.get(ApplicationShell),messages:ctx.container.get(MessageService),quick:ctx.container.get(QuickInputService),untitled:ctx.container.get(UntitledResourceResolver),opener:ctx.container.get(OpenerService),connection:ctx.container.get(WebSocketConnectionProvider),status:ctx.container.get(StatusBar)})).inSingletonScope();bind(FrontendApplicationContribution).toService(Service);bind(CommandContribution).toService(Service);} +module.exports={bindCoordination,FrontendCoordination}; diff --git a/apps/ide/policy/drafts.cjs b/apps/ide/policy/drafts.cjs new file mode 100644 index 0000000..4be0101 --- /dev/null +++ b/apps/ide/policy/drafts.cjs @@ -0,0 +1,9 @@ +class DraftStore { + constructor(indexedDB){this.indexedDB=indexedDB;} + async database(){if(!this.pending)this.pending=new Promise((resolve,reject)=>{const request=this.indexedDB.open('wishforge-unconfirmed-drafts',1);request.onupgradeneeded=()=>request.result.createObjectStore('drafts',{keyPath:'id'});request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);});return this.pending;} + async operation(mode, action){const db=await this.database();return new Promise((resolve,reject)=>{const tx=db.transaction('drafts',mode);const request=action(tx.objectStore('drafts'));let value;request.onsuccess=()=>{value=request.result;};tx.oncomplete=()=>resolve(value);tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error);});} + put(record){if(record.text.length+record.baseText.length>2*1024*1024||new TextEncoder().encode(record.text+record.baseText).byteLength>2*1024*1024)throw new Error('Draft exceeds the 2 MiB local recovery limit');return this.operation('readwrite',store=>store.put(record));} + remove(id){return this.operation('readwrite',store=>store.delete(id));} + async list(scope){return(await this.operation('readonly',store=>store.getAll())).filter(record=>record.scope===scope).sort((a,b)=>b.updatedAt-a.updatedAt);} +} +module.exports={DraftStore}; diff --git a/apps/ide/policy/frontend.cjs b/apps/ide/policy/frontend.cjs new file mode 100644 index 0000000..6759afe --- /dev/null +++ b/apps/ide/policy/frontend.cjs @@ -0,0 +1,46 @@ +const { ContainerModule, injectable } = require('@theia/core/shared/inversify'); +const { CollaborationFrontendContribution } = require('@theia/collaboration/lib/browser/collaboration-frontend-contribution'); +const { CollaborationWorkspaceService } = require('@theia/collaboration/lib/browser/collaboration-workspace-service'); +const { FrontendApplicationConfigProvider } = require('@theia/core/lib/browser/frontend-application-config-provider'); +const { ConnectionProvider, SocketIoTransport } = require('open-collaboration-protocol'); +const { io } = require('socket.io-client'); +const { collaborationBase, createPrefixConnectionProvider } = require('../collaboration/client-factory.cjs'); +Object.defineProperty(exports, '__esModule', { value: true }); + +// Register room commands only for this workspace's authenticated gateway route. +// An absent/mismatched URL keeps collaboration disabled with no public fallback. +class ScopedCollaborationContribution extends CollaborationFrontendContribution { + async scopedUrl() { + const url = await this.getCollaborationServerUrl(); + return collaborationBase(url, window.location.href).href; + } + init() { this.scopedUrl().then(() => this.setStatusBarEntryDefault()).catch(() => {}); } + registerCommands(commands) { + this.scopedUrl().then(() => super.registerCommands(commands)).catch(() => {}); + } + async createConnectionProvider() { + const url = await this.scopedUrl(); + return createPrefixConnectionProvider({ ConnectionProvider, SocketIoTransport, io }, { + url, browserLocation: window.location.href, + client: FrontendApplicationConfigProvider.get().applicationName, + fetch: window.fetch.bind(window), + authenticationHandler: (token, metadata) => this.handleAuth(url, token, metadata), + // OCT tokens are instance-local; never reuse a different workspace token + // from the upstream global localStorage key. + userToken: undefined, + }); + } +} +injectable()(ScopedCollaborationContribution); +// Every backend already belongs to one provisioned project. A guest's virtual +// collaboration URI must not overwrite the backend-wide default for other tabs. +class DedicatedWorkspaceService extends CollaborationWorkspaceService { + isRemoteSession() { return true; } +} +injectable()(DedicatedWorkspaceService); +module.exports.default = new ContainerModule((_bind, _unbind, _isBound, rebind) => { + require('./plugin-install-frontend.cjs').bindManagedExtensionNotice(_bind); + require('./coordination-frontend.cjs').bindCoordination(_bind); + rebind(CollaborationWorkspaceService).to(DedicatedWorkspaceService).inSingletonScope(); + rebind(CollaborationFrontendContribution).to(ScopedCollaborationContribution).inSingletonScope(); +}); diff --git a/apps/ide/policy/lifecycle-safety.cjs b/apps/ide/policy/lifecycle-safety.cjs new file mode 100644 index 0000000..7304809 --- /dev/null +++ b/apps/ide/policy/lifecycle-safety.cjs @@ -0,0 +1,13 @@ +'use strict'; +/** Pinned Theia 1.76 seam. Unknown process/debug inventory is never idle evidence. */ +function sleepReceipt({coordinator,processManager,debugManager,snapshotPending,hostedDebugTouched}){ + try{ + if(!(processManager?.processes instanceof Map)||typeof debugManager?.getAll!=='function')return{known:false}; + const input=coordinator.inputState();const state=coordinator.state(); + // Hosted plugin debug sessions are not enumerated by the native DAP manager. + // Once used, require explicit pause until backend restart instead of guessing termination. + const known=!snapshotPending&&!hostedDebugTouched; + return{known,activeClients:input.activeClients,terminals:processManager.processes.size,debugSessions:[...debugManager.getAll()].length+(state.debugController?1:0),dirty:input.dirty,snapshotComplete:!!input.latestSnapshot&&input.latestSnapshot.digest===input.currentDiskDigest,snapshotRevision:input.latestSnapshot?.revision??0,diskDigest:input.currentDiskDigest}; + }catch{return{known:false};} +} +module.exports={sleepReceipt}; diff --git a/apps/ide/policy/managed-plugins.cjs b/apps/ide/policy/managed-plugins.cjs new file mode 100644 index 0000000..394dc08 --- /dev/null +++ b/apps/ide/policy/managed-plugins.cjs @@ -0,0 +1,79 @@ +'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const { createHash } = require('node:crypto'); +const { execFileSync } = require('node:child_process'); +const sha256 = value => createHash('sha256').update(value).digest('hex'); +const managedError = () => new Error('EXTENSIONS_MANAGED_BY_ADMIN: Extensions are installed and updated only through the operator image build.'); +function treeDigest(root) { + const files = []; + function visit(directory, prefix = '') { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const relative = prefix ? `${prefix}/${entry.name}` : entry.name; + const name = path.join(directory, entry.name); + if (entry.isSymbolicLink()) throw new Error('EXTENSION_SYMLINK_REJECTED'); + if (entry.isDirectory()) visit(name, relative); + else if (entry.isFile()) files.push([relative, sha256(fs.readFileSync(name))]); + else throw new Error('EXTENSION_SPECIAL_FILE_REJECTED'); + } + } + visit(root); + files.sort((left, right) => left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0); + return sha256(files.map(([name, digest]) => `${name}\0${digest}\n`).join('')); +} +function assertIdentity(directory, expected) { + if (fs.lstatSync(directory).isSymbolicLink()) throw new Error('EXTENSION_SYMLINK_REJECTED'); + const manifest = JSON.parse(fs.readFileSync(path.join(directory, 'extension/package.json'), 'utf8')); + if (`${manifest.publisher}.${manifest.name}` !== expected.id || manifest.version !== expected.version) throw new Error('EXTENSION_ID_VERSION_REJECTED'); +} +function validateManagedPlugins(root, { + catalog = require('./managed-plugins.lock.json'), + pythonLock = require('../scripts/python-debugger.lock.json'), + platform = `${process.platform}-${process.arch}`, +} = {}) { + if (fs.lstatSync(root).isSymbolicLink()) throw new Error('EXTENSION_SYMLINK_REJECTED'); + const extensions = [...catalog.plugins]; + if (pythonLock) extensions.push( + { directory: pythonLock.id, id: pythonLock.id, version: pythonLock.version }, + { directory: pythonLock.pythonDependency.id, id: pythonLock.pythonDependency.id, version: pythonLock.pythonDependency.version }, + { directory: pythonLock.languageServer.id, id: pythonLock.languageServer.id, version: pythonLock.languageServer.version }, + ); + const allowed = new Set(extensions.map(extension => extension.directory)); + const found = fs.readdirSync(root).filter(name => !name.startsWith('.')); + if (found.length !== allowed.size || found.some(name => !allowed.has(name))) throw new Error('EXTENSION_ALLOWLIST_MISMATCH'); + for (const extension of extensions) { + const directory = path.join(root, extension.directory); + assertIdentity(directory, extension); + if (extension.sha256 && treeDigest(directory) !== extension.sha256) throw new Error(`EXTENSION_DIGEST_REJECTED: ${extension.id}`); + } + if (pythonLock) { + const expected = pythonLock.platforms[platform]; + if (!expected) throw new Error('EXTENSION_PLATFORM_NOT_PINNED'); + const dependency = pythonLock.pythonDependency; + const packages = [ + { id: pythonLock.id, file: `${pythonLock.id}-${pythonLock.version}@${platform}.vsix`, sha256: expected }, + { id: dependency.id, file: `${dependency.id}-${dependency.version}.vsix`, sha256: dependency.sha256 }, + { id: pythonLock.languageServer.id, file: `${pythonLock.languageServer.id}-${pythonLock.languageServer.version}.vsix`, sha256: pythonLock.languageServer.sha256 }, + ]; + // Compare the unpacked bytes against the checksum-pinned official VSIX files, + // never against a manifest self-generated from the current runtime directory. + execFileSync('python3', ['-c', ` +import hashlib,json,pathlib,stat,sys,zipfile +root=pathlib.Path(sys.argv[1]) +for package in json.loads(sys.argv[2]): + archive=root/'.downloads'/package['file'] + if archive.is_symlink() or archive.stat().st_size>67108864: raise ValueError('EXTENSION_ARCHIVE_REJECTED') + if hashlib.sha256(archive.read_bytes()).hexdigest()!=package['sha256']: raise ValueError('EXTENSION_ARCHIVE_DIGEST_REJECTED') + target=root/package['id'] + with zipfile.ZipFile(archive) as z: + expected={i.filename:hashlib.sha256(z.read(i)).hexdigest() for i in z.infolist() if not i.is_dir()} + actual={} + for p in target.rglob('*'): + if p.is_symlink(): raise ValueError('EXTENSION_SYMLINK_REJECTED') + if p.is_file(): actual[p.relative_to(target).as_posix()]=hashlib.sha256(p.read_bytes()).hexdigest() + if actual!=expected: raise ValueError('EXTENSION_CONTENT_DIGEST_REJECTED: '+package['id']) +`, root, JSON.stringify(packages)], { timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] }); + } + return extensions; +} +module.exports = { treeDigest, assertIdentity, validateManagedPlugins, managedError }; diff --git a/apps/ide/policy/managed-plugins.lock.json b/apps/ide/policy/managed-plugins.lock.json new file mode 100644 index 0000000..a966285 --- /dev/null +++ b/apps/ide/policy/managed-plugins.lock.json @@ -0,0 +1,561 @@ +{ + "schemaVersion": 1, + "source": { + "url": "https://github.com/eclipse-theia/vscode-builtin-extensions/releases/download/1.108.2/vscode-builtin-extensions-1.108.2.tar.gz", + "sha256": "05a20cf3e671c8d328b04d9ce72b25688b0e762e4a3f5592f31a21ee38280367" + }, + "plugins": [ + { + "directory": "ms-vscode.js-debug", + "id": "ms-vscode.js-debug", + "version": "1.105.0", + "sha256": "47b974a9cf4f2d030efbbd00d21ad7c4c8b406dade21652aa95686427fd96a76" + }, + { + "directory": "ms-vscode.js-debug-companion", + "id": "ms-vscode.js-debug-companion", + "version": "1.1.3", + "sha256": "3d567809ed536ad5ead4732f83b4433113f6bba0d56ee57ba80cdb7fc90e87b6" + }, + { + "directory": "ms-vscode.vscode-js-profile-table", + "id": "ms-vscode.vscode-js-profile-table", + "version": "1.0.10", + "sha256": "6db1bdc953c0c055480eca4a867059ea36a71b2f28eb22631abe5d807d9d992a" + }, + { + "directory": "vscode.bat", + "id": "vscode.bat", + "version": "1.108.2", + "sha256": "049a52d9bd4934464eabe1318ccc164f734d0e080e39df9c02f54c32d6a1480a" + }, + { + "directory": "vscode.builtin-notebook-renderers", + "id": "vscode.builtin-notebook-renderers", + "version": "1.108.2", + "sha256": "28198f48d05ba683c4a1ce490377543f4c89fd65e44c18da0a1b9f3faa010f2b" + }, + { + "directory": "vscode.clojure", + "id": "vscode.clojure", + "version": "1.108.2", + "sha256": "5ba5793cf1797861aa58410079cc1a542784053bc9b038afd758db5336319dd5" + }, + { + "directory": "vscode.coffeescript", + "id": "vscode.coffeescript", + "version": "1.108.2", + "sha256": "ef1d7e0149349a73550c7359c5d9186c406c941dba3771230ce82f9e8cd709cf" + }, + { + "directory": "vscode.configuration-editing", + "id": "vscode.configuration-editing", + "version": "1.108.2", + "sha256": "d5c82fa70a7ac06e53d55dd0ad943be42b7206da918887582701b63dd318ced9" + }, + { + "directory": "vscode.cpp", + "id": "vscode.cpp", + "version": "1.108.2", + "sha256": "e890a89907e8bed3718962f7f56fea93cd639eb8d3f87078b24c4fc26767d30a" + }, + { + "directory": "vscode.csharp", + "id": "vscode.csharp", + "version": "1.108.2", + "sha256": "f70330001f788a62592b5d5d9639fdabddbffa616ece32fb3deed47edd15d926" + }, + { + "directory": "vscode.css", + "id": "vscode.css", + "version": "1.108.2", + "sha256": "e16cc9e6ba83af3b8b2dac7a58326d8d49dccf11d0ce4ddc450c3a529bc43b12" + }, + { + "directory": "vscode.css-language-features", + "id": "vscode.css-language-features", + "version": "1.108.2", + "sha256": "9c61d13d105e4fa35b6d430e3afde416e47e5691ca72cff84226a54a8a7a2925" + }, + { + "directory": "vscode.dart", + "id": "vscode.dart", + "version": "1.108.2", + "sha256": "65594c659e862f0eaebbcc1b68652ebe70e6c9d1a90340d078eb1697c1166913" + }, + { + "directory": "vscode.debug-auto-launch", + "id": "vscode.debug-auto-launch", + "version": "1.108.2", + "sha256": "408b192f4c5913b6fc3294ad661dabddea56d7c57ea8bbe10919bc06a9239660" + }, + { + "directory": "vscode.debug-server-ready", + "id": "vscode.debug-server-ready", + "version": "1.108.2", + "sha256": "8deb733ffbf4198cef3cbb73d6b5307de9ba6c18d8a4249432d71ba47d06b864" + }, + { + "directory": "vscode.diff", + "id": "vscode.diff", + "version": "1.108.2", + "sha256": "ecbdda82e1072bce5d375a4b6d267da041a936c3cabfda3011dddb21e5a48e98" + }, + { + "directory": "vscode.docker", + "id": "vscode.docker", + "version": "1.108.2", + "sha256": "2a957acd235c9a5d3580e46389f16cb840a34d3a70f9d66df8c0691bcede878d" + }, + { + "directory": "vscode.dotenv", + "id": "vscode.dotenv", + "version": "1.108.2", + "sha256": "eb84848cc43176288f815c554ab03636a5d5472c6314e956041d95b2d7b0bf8f" + }, + { + "directory": "vscode.emmet", + "id": "vscode.emmet", + "version": "1.108.2", + "sha256": "b6b5dc5df353e4ecbca48aca599bfe51cdcba7f63b9fb0ef79b8022ac9a4ddf1" + }, + { + "directory": "vscode.extension-editing", + "id": "vscode.extension-editing", + "version": "1.108.2", + "sha256": "2885dabf8b502f45a402f500a4bd43b338cc9b64764d758ef250c8b1aad0bcf6" + }, + { + "directory": "vscode.fsharp", + "id": "vscode.fsharp", + "version": "1.108.2", + "sha256": "1167d5c4c0bf022aeacf859803d5552071d42cec848684546a68a4ebb99628a1" + }, + { + "directory": "vscode.git", + "id": "vscode.git", + "version": "1.108.2", + "sha256": "882cbb7556376f513629ed3fba1711c77b80890cb284646b6391518276609075" + }, + { + "directory": "vscode.git-base", + "id": "vscode.git-base", + "version": "1.108.2", + "sha256": "26d3c189c0890b8bff9ec56391cea74f378b815c5aedbd5ec583ca297ae23f55" + }, + { + "directory": "vscode.github", + "id": "vscode.github", + "version": "1.108.2", + "sha256": "616a6f2b139be59b00725aa28111512e11f8354d3433f84681a9dee54956f422" + }, + { + "directory": "vscode.github-authentication", + "id": "vscode.github-authentication", + "version": "1.108.2", + "sha256": "7f772b6f9241509efba786f4ff9184374740516084b2e3b1c231163f143da208" + }, + { + "directory": "vscode.go", + "id": "vscode.go", + "version": "1.108.2", + "sha256": "c848c972ae6d559fbfb10702e3dcf95ad94d16cd0edb2dde45dcc72054efa1e3" + }, + { + "directory": "vscode.groovy", + "id": "vscode.groovy", + "version": "1.108.2", + "sha256": "00ca5455163d0ec0dbc5d50fade93f94e2b93f1dc5bce3d22395508e256ec619" + }, + { + "directory": "vscode.grunt", + "id": "vscode.grunt", + "version": "1.108.2", + "sha256": "68bc5e71189089032abc187ff97666cc873b1cf6bfecd37a93721e8710633f86" + }, + { + "directory": "vscode.gulp", + "id": "vscode.gulp", + "version": "1.108.2", + "sha256": "fd073848831e8d3c148e4daf085e7f54fdc48bfc91a3136f6491df99f99f9c01" + }, + { + "directory": "vscode.handlebars", + "id": "vscode.handlebars", + "version": "1.108.2", + "sha256": "c9446c5192f64cb8cd70300577a69961ef83fab430898db36421d07b62660fdf" + }, + { + "directory": "vscode.hlsl", + "id": "vscode.hlsl", + "version": "1.108.2", + "sha256": "482db38e94f8505f12458b051793bb3d937c3e2e560e6adeaa31e41609396441" + }, + { + "directory": "vscode.html", + "id": "vscode.html", + "version": "1.108.2", + "sha256": "3420b09f3f1fd441dacf842041db14045584dea25b2d3f675453a9ba6fd9b599" + }, + { + "directory": "vscode.html-language-features", + "id": "vscode.html-language-features", + "version": "1.108.2", + "sha256": "ccc11f2b9c7ba04f6f9f31c49e16587a165fd4f71a5d8345314d2509393b01bb" + }, + { + "directory": "vscode.ini", + "id": "vscode.ini", + "version": "1.108.2", + "sha256": "00f9170d7311b1a75484e63c2ac0abe374934bb38dff5a0c342153f93fc69164" + }, + { + "directory": "vscode.ipynb", + "id": "vscode.ipynb", + "version": "1.108.2", + "sha256": "d5be113eeaf2d9735044c5db42983a3f7c9f81b5fc0ce6c7864ff69f15ac5e27" + }, + { + "directory": "vscode.jake", + "id": "vscode.jake", + "version": "1.108.2", + "sha256": "9ff40dd4dcbb130f52b4a39cbf630fab468d9d5f1ef91d6b1ac4433ffda55a9c" + }, + { + "directory": "vscode.java", + "id": "vscode.java", + "version": "1.108.2", + "sha256": "af9b242d4bfcd33683013f3af4ceddae96324f6a242e9055718a431a157dca75" + }, + { + "directory": "vscode.javascript", + "id": "vscode.javascript", + "version": "1.108.2", + "sha256": "9936e0f60e9f6130edb3cc5c1a8727582519c29cb882ea53f8ab2728193695e5" + }, + { + "directory": "vscode.json", + "id": "vscode.json", + "version": "1.108.2", + "sha256": "0047b7b7e590fed1fd5a30c7d06d167c9fb23f9d6155a65e9b57a3b9703da68d" + }, + { + "directory": "vscode.json-language-features", + "id": "vscode.json-language-features", + "version": "1.108.2", + "sha256": "51971aef66c5af444e04042b6a3d6cebc7e20422d0c2cee4219b775caf567446" + }, + { + "directory": "vscode.julia", + "id": "vscode.julia", + "version": "1.108.2", + "sha256": "109bf99c4cbe2e02082d952d72da97984bf90bbfe1c5a53683040a1b98e18c82" + }, + { + "directory": "vscode.latex", + "id": "vscode.latex", + "version": "1.108.2", + "sha256": "8e664d4c99645338f2d85d7013270e072a494df4db61be027cfccafab3a1dcb4" + }, + { + "directory": "vscode.less", + "id": "vscode.less", + "version": "1.108.2", + "sha256": "10027163ff231ab5ad5b964f87538793dd4f0430ea71a0575ec66514c63dbe6e" + }, + { + "directory": "vscode.log", + "id": "vscode.log", + "version": "1.108.2", + "sha256": "f48bcc16c41b1789496341d883141dc1105d458529390299ddd924909c5e31c8" + }, + { + "directory": "vscode.lua", + "id": "vscode.lua", + "version": "1.108.2", + "sha256": "2de7c36f55c75a9167f9a58ad17012c6567a87928a5bfdc0a42ea8839c8069c5" + }, + { + "directory": "vscode.make", + "id": "vscode.make", + "version": "1.108.2", + "sha256": "a4f6189f96df05bf08e2c6d8fa0e0d5eabe2e1d61056654fc5f8e5581f279937" + }, + { + "directory": "vscode.markdown", + "id": "vscode.markdown", + "version": "1.108.2", + "sha256": "d4b364c6e2edad2b1ae50ece5cee20b130aa94efc5f8f8eb1b696b0eda563ba9" + }, + { + "directory": "vscode.markdown-language-features", + "id": "vscode.markdown-language-features", + "version": "1.108.2", + "sha256": "ced48a41ed75021d1a4ea5afd7f51c08631f70f04e323d351d7260824083a7a6" + }, + { + "directory": "vscode.markdown-math", + "id": "vscode.markdown-math", + "version": "1.108.2", + "sha256": "b58711f19ecca7df14e13979ec675c1bdaa9f3968a6e756ff5c7105105dbb86e" + }, + { + "directory": "vscode.media-preview", + "id": "vscode.media-preview", + "version": "1.108.2", + "sha256": "179e0778ac606e254f59018fde83ea9caf5f90e0f99ac0ecc347d5ad66af330c" + }, + { + "directory": "vscode.merge-conflict", + "id": "vscode.merge-conflict", + "version": "1.108.2", + "sha256": "a1b347a40c96cccf73a102808b768140bf5d3c1dfeddbfa1dca1da2b7f7f477b" + }, + { + "directory": "vscode.mermaid-chat-features", + "id": "vscode.mermaid-chat-features", + "version": "1.108.2", + "sha256": "b6d18d40c0b1e0b2585b99a0488b984d1b30a2a1140206ca34c9557165b78455" + }, + { + "directory": "vscode.npm", + "id": "vscode.npm", + "version": "1.108.2", + "sha256": "0f11c99fe30648d7c444361298749d0b8d5ff60472b5a0eabc3904d07397876e" + }, + { + "directory": "vscode.objective-c", + "id": "vscode.objective-c", + "version": "1.108.2", + "sha256": "8319b21c30bb8fcb897687991165909e359ec0c075c1d014602f38da9865864a" + }, + { + "directory": "vscode.perl", + "id": "vscode.perl", + "version": "1.108.2", + "sha256": "5727730f86da49921388ea8276a1c11bb1438796c02815f980fd5239ebd2e430" + }, + { + "directory": "vscode.php", + "id": "vscode.php", + "version": "1.108.2", + "sha256": "70c19b21bc32837872145a0a1e76ee216b51d012321087f4ef7380e289d77715" + }, + { + "directory": "vscode.php-language-features", + "id": "vscode.php-language-features", + "version": "1.108.2", + "sha256": "01159d120c597f2663367277c1e9d4f8e9866a88c3c30776d48485d061bbd8ad" + }, + { + "directory": "vscode.powershell", + "id": "vscode.powershell", + "version": "1.108.2", + "sha256": "83d8cbf4801aaddee86ddd3c3f61a9fcfde74a1049497c8db4e890598beeffe6" + }, + { + "directory": "vscode.prompt", + "id": "vscode.prompt", + "version": "1.108.2", + "sha256": "a0d70ebb1f4189419dbb963e1024e0b3a5e7d977697b32b1d9686a9f315c8fa9" + }, + { + "directory": "vscode.pug", + "id": "vscode.pug", + "version": "1.108.2", + "sha256": "288d461d6a7ec29b7ec2f4d11a3065690e9315c719e64cf1baa1dea542d1b57a" + }, + { + "directory": "vscode.python", + "id": "vscode.python", + "version": "1.108.2", + "sha256": "8683bf05b9c8ab797d2a75ddf23eee1f979d4272fbbcb5b0b963f62e16ea8f2f" + }, + { + "directory": "vscode.r", + "id": "vscode.r", + "version": "1.108.2", + "sha256": "a2f642e8905e67bb73737e457fa079bf76aad644fdaa2f1cdf0fd0ecdcfc73f5" + }, + { + "directory": "vscode.razor", + "id": "vscode.razor", + "version": "1.108.2", + "sha256": "6d24d115419c70dd22329d82d5a06b965c8f4c4890543edb11ff0bf4f71fa7bb" + }, + { + "directory": "vscode.references-view", + "id": "vscode.references-view", + "version": "1.108.2", + "sha256": "d2bdc0161a107eaa844c6bb2f4c287bb8a1319f7107370ee9f60a3621859e42c" + }, + { + "directory": "vscode.restructuredtext", + "id": "vscode.restructuredtext", + "version": "1.108.2", + "sha256": "19a9dbcd2fc1f7ac087dd3f056e4d69ea50aaac43195cb7762513245f39dd089" + }, + { + "directory": "vscode.ruby", + "id": "vscode.ruby", + "version": "1.108.2", + "sha256": "958e0bbe7c1cd09da68e7794abd85a99ed8fb0f588d7a3d73bf36b118a842caa" + }, + { + "directory": "vscode.rust", + "id": "vscode.rust", + "version": "1.108.2", + "sha256": "bb29d84d161754274f80f605b627cc11de67458b826fa13e0eebf30e12ab979e" + }, + { + "directory": "vscode.scss", + "id": "vscode.scss", + "version": "1.108.2", + "sha256": "a66ee14fedc6225c672ddc73fd457034baf90f9fac23b2987d6404c8a937b737" + }, + { + "directory": "vscode.search-result", + "id": "vscode.search-result", + "version": "1.108.2", + "sha256": "4f579e97277485d9861554bdedb9cbecf761b37e70be74d5144c66affdc00d7e" + }, + { + "directory": "vscode.shaderlab", + "id": "vscode.shaderlab", + "version": "1.108.2", + "sha256": "ce9c866d5f4fff9d3c2e3fd4f5f5a2e0c789be7daf0db88387d74e884d0b29e8" + }, + { + "directory": "vscode.shellscript", + "id": "vscode.shellscript", + "version": "1.108.2", + "sha256": "ac6048f34e998b969fda2698583983627b5a957db35270d3d056df7946f7b0f6" + }, + { + "directory": "vscode.simple-browser", + "id": "vscode.simple-browser", + "version": "1.108.2", + "sha256": "64a0ad33a16501227125ac2c994b668ba8772b213bb246fa60281b4aaba9a9f9" + }, + { + "directory": "vscode.sql", + "id": "vscode.sql", + "version": "1.108.2", + "sha256": "fb9285cd41cff6e70da9a6f7017307be12cbf49abe06627854ea8eb254db1013" + }, + { + "directory": "vscode.swift", + "id": "vscode.swift", + "version": "1.108.2", + "sha256": "fc74ef0b507b235e07dd905b82e8efc69824f7f7dfdbbd12d6a5cd7b23bbece1" + }, + { + "directory": "vscode.terminal-suggest", + "id": "vscode.terminal-suggest", + "version": "1.108.2", + "sha256": "12b7713afd5028bc3978c652d555ec4737bc4d29d2c236318a60b20c5c7e2d80" + }, + { + "directory": "vscode.theme-abyss", + "id": "vscode.theme-abyss", + "version": "1.108.2", + "sha256": "f4f5256d0a95c11442f8b758cae95c22240cc209e45f284ac9afe70b242cf4fa" + }, + { + "directory": "vscode.theme-defaults", + "id": "vscode.theme-defaults", + "version": "1.108.2", + "sha256": "220a90a481dd4ffb0587d727ca02122f03d7befc26a6649d709f13e3a50c29f0" + }, + { + "directory": "vscode.theme-kimbie-dark", + "id": "vscode.theme-kimbie-dark", + "version": "1.108.2", + "sha256": "eb1cf1a0362f82b6e23f5383cc3b691afb6a0d60d79955aa858263ecfbd797ec" + }, + { + "directory": "vscode.theme-monokai", + "id": "vscode.theme-monokai", + "version": "1.108.2", + "sha256": "ba7abbb9ab04ece745aced2269003d65316ee487638308fc0f1a08476a91de83" + }, + { + "directory": "vscode.theme-monokai-dimmed", + "id": "vscode.theme-monokai-dimmed", + "version": "1.108.2", + "sha256": "00d5d056d6f3773c5314feaae1adae3c061a8188ba3231961f4a5707176f62e0" + }, + { + "directory": "vscode.theme-quietlight", + "id": "vscode.theme-quietlight", + "version": "1.108.2", + "sha256": "f0f018f4de1a3f93de5a9ed40069dc8614d981339273f8bfc244c1f5cad8d2aa" + }, + { + "directory": "vscode.theme-red", + "id": "vscode.theme-red", + "version": "1.108.2", + "sha256": "3065330894fdb026a9b6278108be00e5dbc71bfa218575b7b0db6f29f2d3d7be" + }, + { + "directory": "vscode.theme-solarized-dark", + "id": "vscode.theme-solarized-dark", + "version": "1.108.2", + "sha256": "ff0b771b8ac188e5025c9d2f79aff66dbb9092cee54fdad5c5ef55493e741576" + }, + { + "directory": "vscode.theme-solarized-light", + "id": "vscode.theme-solarized-light", + "version": "1.108.2", + "sha256": "90d275f62c97c6db813f4b8328dfbb6a2416d3ffbe3086f5b6b0c336e0b129d9" + }, + { + "directory": "vscode.theme-tomorrow-night-blue", + "id": "vscode.theme-tomorrow-night-blue", + "version": "1.108.2", + "sha256": "ec253677124f41a815d63dfa970f0a25a98bf805d9172c9e539b4ed037320c7e" + }, + { + "directory": "vscode.tunnel-forwarding", + "id": "vscode.tunnel-forwarding", + "version": "1.108.2", + "sha256": "dc6f8419f6544455b42afd1b729b50d07705be1ce001007ddc208e2594397fb9" + }, + { + "directory": "vscode.typescript", + "id": "vscode.typescript", + "version": "1.108.2", + "sha256": "879b9686a08845f43c2d9f89334f3bf747aaf9de9ea12fb3c3b161bc19e4ea48" + }, + { + "directory": "vscode.typescript-language-features", + "id": "vscode.typescript-language-features", + "version": "1.108.2", + "sha256": "819e93858b013f24a6e102a71e8e1922515b310071d11ccbb98a82be6ab99dd9" + }, + { + "directory": "vscode.vb", + "id": "vscode.vb", + "version": "1.108.2", + "sha256": "49b14b8e8668434f86fa997e1168a86168f92c237662af6d8b6c0d25790caf30" + }, + { + "directory": "vscode.vscode-theme-seti", + "id": "vscode.vscode-theme-seti", + "version": "1.108.2", + "sha256": "e0383c41fedc343b6b2e02ef6ba77e5edac78ce72c06ae45d84fd940f2b8975e" + }, + { + "directory": "vscode.xml", + "id": "vscode.xml", + "version": "1.108.2", + "sha256": "4656d86b85078ba1673a36050439013339aa58e855e7695a6ef201e9333d6e6c" + }, + { + "directory": "vscode.yaml", + "id": "vscode.yaml", + "version": "1.108.2", + "sha256": "b03408b1cc8cb82c2c1961ea480e6b04d9a054ebc034af71f4d91cb29408aca6" + } + ] +} diff --git a/apps/ide/policy/package.json b/apps/ide/policy/package.json new file mode 100644 index 0000000..2232e7a --- /dev/null +++ b/apps/ide/policy/package.json @@ -0,0 +1,7 @@ +{ + "name": "@wishforge/ide-policy", + "version": "0.1.0", + "private": true, + "theiaExtensions": [{ "frontend": "frontend.cjs", "backend": "backend.cjs" }], + "peerDependencies": { "@theia/core": "1.76.0", "@theia/collaboration": "1.76.0" } +} diff --git a/apps/ide/policy/plugin-dap-guard.cjs b/apps/ide/policy/plugin-dap-guard.cjs new file mode 100644 index 0000000..87e139f --- /dev/null +++ b/apps/ide/policy/plugin-dap-guard.cjs @@ -0,0 +1,158 @@ +'use strict'; + +const { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } = require('@theia/core/lib/common/message-rpc/uint8-array-message-buffer'); +const { MsgPackMessageDecoder, MsgPackMessageEncoder } = require('@theia/core/lib/common/message-rpc/rpc-message-encoder'); + +const MAX_BATCH_MESSAGES = 10_000; +const MAX_BATCH_BYTES = 64 * 1024 * 1024; +const MAX_MESSAGE_BYTES = 16 * 1024 * 1024; +// filterPluginRpc is invoked once per batch. Keep synthetic DAP response sequence +// numbers increasing across batches for the lifetime of this backend process. +let pluginDapResponseSequence = 0; + +function rejected(code) { return Object.assign(new Error(code), { code }); } + +// Theia's ReadBuffer intentionally trusts frame lengths. Validate every boundary +// first: a Uint8Array may be a view into a larger websocket backing buffer. +function readLength(bytes, cursor, maximum) { + let value = 0; + for (let shift = 0; shift <= 28; shift += 7) { + if (cursor.offset >= bytes.byteLength) throw rejected('MALFORMED_PLUGIN_RPC'); + const byte = bytes[cursor.offset++]; + value += (byte & 127) * 2 ** shift; + if (value > maximum) throw rejected('RPC_BATCH_LIMIT'); + if (byte < 128) return value; + } + throw rejected('MALFORMED_PLUGIN_RPC'); +} + +function decodeBatch(payload) { + if (!(payload instanceof Uint8Array)) throw rejected('MALFORMED_PLUGIN_RPC'); + if (payload.byteLength > MAX_BATCH_BYTES) throw rejected('RPC_BATCH_LIMIT'); + const cursor = { offset: 0 }; + const count = readLength(payload, cursor, MAX_BATCH_MESSAGES); + const messages = []; + const decoder = new MsgPackMessageDecoder(); + for (let index = 0; index < count; index++) { + const length = readLength(payload, cursor, MAX_MESSAGE_BYTES); + if (length === 0 || length > payload.byteLength - cursor.offset) throw rejected('MALFORMED_PLUGIN_RPC'); + const bytes = payload.slice(cursor.offset, cursor.offset + length); + cursor.offset += length; + const inner = { offset: 0 }; + const encodedLength = readLength(bytes, inner, MAX_MESSAGE_BYTES); + if (encodedLength !== bytes.byteLength - inner.offset) throw rejected('MALFORMED_PLUGIN_RPC'); + let message; + try { message = decoder.parse(new Uint8ArrayReadBuffer(bytes)); } + catch { throw rejected('UNDECODABLE_PLUGIN_RPC'); } + if (!message || ![1, 2, 3, 4, 5].includes(message.type)) throw rejected('MALFORMED_PLUGIN_RPC'); + if ((message.type !== 2 || message.id !== undefined) && (!Number.isSafeInteger(message.id) || message.id < 0)) throw rejected('MALFORMED_PLUGIN_RPC'); + if ((message.type === 1 || message.type === 2) && (typeof message.method !== 'string' || !Array.isArray(message.args))) throw rejected('MALFORMED_PLUGIN_RPC'); + messages.push({ bytes, message }); + } + if (cursor.offset !== payload.byteLength) throw rejected('MALFORMED_PLUGIN_RPC'); + return messages; +} + +function encodeBatch(messages) { + if (messages.length === 0) return null; + const writer = new Uint8ArrayWriteBuffer(); + writer.writeLength(messages.length); + for (const message of messages) writer.writeBytes(message); + const encoded = writer.getCurrentContents(); + writer.dispose(); + return encoded; +} + +function gated(message) { + if (message.type !== 1 && message.type !== 2) return false; + return (message.args[0] === 'DebugExt' && ['$createDebugSession', '$terminateDebugSession'].includes(message.method)) || + (message.args[0] === 'ConnectionExt' && ['$sendMessage', '$deleteConnection'].includes(message.method)); +} + +function assertSynchronously(assertControl) { + const result = assertControl(); + // The backend guard must make its authorization decision before forwarding. + if (result === false || (result && typeof result.then === 'function')) throw rejected('DEBUG_CONTROL_REQUIRED'); +} + +function dapRequest(value) { + if (typeof value !== 'string') return null; + let request; + try { request = JSON.parse(value); } catch { return null; } + if (!request || Array.isArray(request) || request.type !== 'request' || !Number.isSafeInteger(request.seq) || request.seq < 0 || typeof request.command !== 'string' || !request.command) return null; + return request; +} + +function pluginDapDenial(message, encoder) { + if (message.args[0] !== 'ConnectionExt' || message.method !== '$sendMessage') return null; + const sessionId = message.args[1]; + if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 1024) return null; + const request = dapRequest(message.args[2]); + if (!request) return null; + const response = { + seq: ++pluginDapResponseSequence, type: 'response', request_seq: request.seq, + command: request.command, success: false, message: 'WishForge debug controller lease required', + }; + const writer = new Uint8ArrayWriteBuffer(); + // PluginChannel.send discards its RPC promise. ReplyErr alone leaves the DAP + // request pending, so deliver a real DAP failure through the frontend channel. + encoder.notification(writer, '$sendMessage', ['ConnectionMain', sessionId, JSON.stringify(response)]); + const bytes = writer.getCurrentContents(); + writer.dispose(); + return bytes; +} + +/** Filter a real Theia BatchingChannel frame without forwarding any undecoded bytes. */ +function filterPluginRpc(payload, assertControl) { + if (typeof assertControl !== 'function') throw rejected('DEBUG_GUARD_REQUIRED'); + const messages = decodeBatch(payload); + const forwarded = []; + const replies = []; + const encoder = new MsgPackMessageEncoder(); + let denied = 0; + for (const { bytes, message } of messages) { + if (gated(message)) { + try { assertSynchronously(assertControl); } + catch { + denied++; + if (message.type === 1) { + const writer = new Uint8ArrayWriteBuffer(); + encoder.replyErr(writer, message.id, rejected('DEBUG_CONTROL_REQUIRED')); + replies.push(writer.getCurrentContents()); + writer.dispose(); + } + const dapReply = pluginDapDenial(message, encoder); + if (dapReply) replies.push(dapReply); + continue; + } + } + forwarded.push(bytes); + } + return { forwarded: encodeBatch(forwarded), replies: encodeBatch(replies), denied }; +} + +/** Wrap the native ForwardingDebugChannel; authorization is checked per incoming DAP message. */ +function guardDebugChannel(raw, assertControl) { + if (typeof assertControl !== 'function') throw rejected('DEBUG_GUARD_REQUIRED'); + let responseSequence = 0; + return { + send: message => raw.send(message), + onClose: callback => raw.onClose(callback), + onError: callback => raw.onError(callback), + close: () => raw.close(), + onMessage: callback => raw.onMessage(message => { + try { assertSynchronously(assertControl); } + catch { + let request; + try { request = JSON.parse(message); } catch { raw.close(); return; } + if (!request || request.type !== 'request' || !Number.isSafeInteger(request.seq) || request.seq < 0 || typeof request.command !== 'string' || !request.command) { raw.close(); return; } + raw.send(JSON.stringify({ seq: ++responseSequence, type: 'response', request_seq: request.seq, command: request.command, success: false, message: 'WishForge debug controller lease required' })); + return; + } + // Adapter callback errors are not authorization failures and must not be swallowed. + callback(message); + }), + }; +} + +module.exports = { filterPluginRpc, guardDebugChannel, MAX_BATCH_MESSAGES, MAX_BATCH_BYTES, MAX_MESSAGE_BYTES }; diff --git a/apps/ide/policy/plugin-install-frontend.cjs b/apps/ide/policy/plugin-install-frontend.cjs new file mode 100644 index 0000000..d3c52e5 --- /dev/null +++ b/apps/ide/policy/plugin-install-frontend.cjs @@ -0,0 +1,33 @@ +'use strict'; +const { injectable, inject } = require('@theia/core/shared/inversify'); +const { WidgetManager } = require('@theia/core/lib/browser/widget-manager'); +const { FrontendApplicationContribution } = require('@theia/core/lib/browser/frontend-application-contribution'); +const React = require('@theia/core/shared/react'); +class ManagedExtensionsNotice { + onStart() { + const label = widget => { + if (widget.id !== 'vsx-extensions-view-container') return; + widget.title.label = 'Extensions · 管理员管理'; + widget.title.caption = '扩展由管理员固定版本安装。可查看已安装扩展;安装、更新与移除须通过平台镜像发布。'; + // ViewContainer restores its title from saved layout/part titles. Put the + // durable notice in the extension search widget as well as the caption. + if (!widget.searchBar || widget.searchBar.wishforgeManagedNotice) return; + const search = widget.searchBar; + search.wishforgeManagedNotice = true; + const render = search.render.bind(search); + search.render = () => React.createElement('div', { style: { width: '100%' } }, + React.createElement('p', { style: { margin: '0 0 8px', fontSize: '12px', lineHeight: '1.6' } }, + '扩展由管理员管理。安装与更新须通过平台镜像发布。'), render()); + search.update(); + }; + this.widgets.getWidgets('vsx-extensions-view-container').forEach(label); + this.widgets.onDidCreateWidget(({ widget }) => label(widget)); + } +} +injectable()(ManagedExtensionsNotice); +inject(WidgetManager)(ManagedExtensionsNotice.prototype, 'widgets'); +function bindManagedExtensionNotice(bind) { + bind(ManagedExtensionsNotice).toSelf().inSingletonScope(); + bind(FrontendApplicationContribution).toService(ManagedExtensionsNotice); +} +module.exports = { bindManagedExtensionNotice }; diff --git a/apps/ide/policy/plugin-install-policy.cjs b/apps/ide/policy/plugin-install-policy.cjs new file mode 100644 index 0000000..5aaeaee --- /dev/null +++ b/apps/ide/policy/plugin-install-policy.cjs @@ -0,0 +1,45 @@ +'use strict'; +const path = require('node:path'); +const { injectable } = require('@theia/core/shared/inversify'); +const { PluginServer, PluginDeployer, PluginType } = require('@theia/plugin-ext/lib/common/plugin-protocol'); +const { PluginServerImpl } = require('@theia/plugin-ext/lib/main/node/plugin-server-impl'); +const { PluginDeployerImpl } = require('@theia/plugin-ext/lib/main/node/plugin-deployer-impl'); +const { validateManagedPlugins, managedError } = require('./managed-plugins.cjs'); + +class ManagedPluginServer extends PluginServerImpl { + async install() { throw managedError(); } + async doInstall() { throw managedError(); } + async uninstall() { throw managedError(); } + async enablePlugin() { throw managedError(); } + async disablePlugin() { throw managedError(); } +} +injectable()(ManagedPluginServer); +class ManagedPluginDeployer extends PluginDeployerImpl { + async doStart() { + if (!process.env.WF_IDE_MANAGED_PLUGINS_DIR) throw new Error('MANAGED_EXTENSIONS_UNCONFIGURED'); + const root = path.resolve(process.env.WF_IDE_MANAGED_PLUGINS_DIR); + const allowed = validateManagedPlugins(root); + await this.initResolvers(); + // Do not consult THEIA_PLUGINS, user directories, extension recommendations + // or resolver participants. All system content was verified before resolution. + const entries = await this.resolveAndHandle(`local-dir:${root}`, PluginType.System); + const paths = new Set(allowed.map(extension => path.join(root, extension.directory))); + if (entries.length !== paths.size || entries.some(entry => !paths.has(entry.originalPath()) || entry.type !== PluginType.System)) { + throw new Error('EXTENSION_DEPLOYMENT_SCOPE_REJECTED'); + } + return super.deployPlugins(entries); + } + async deploy() { throw managedError(); } + async deployMultipleEntries() { throw managedError(); } + async deployPlugins() { throw managedError(); } + async uninstall() { throw managedError(); } + async undeploy() { throw managedError(); } + async enablePlugin() { throw managedError(); } + async disablePlugin() { throw managedError(); } +} +injectable()(ManagedPluginDeployer); +function bindManagedPlugins(rebind) { + rebind(PluginServer).to(ManagedPluginServer).inSingletonScope(); + rebind(PluginDeployer).to(ManagedPluginDeployer).inSingletonScope(); +} +module.exports = { ManagedPluginServer, ManagedPluginDeployer, bindManagedPlugins }; diff --git a/apps/ide/policy/test/backend-guard.test.cjs b/apps/ide/policy/test/backend-guard.test.cjs new file mode 100644 index 0000000..ba6181d --- /dev/null +++ b/apps/ide/policy/test/backend-guard.test.cjs @@ -0,0 +1,263 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { Uint8ArrayReadBuffer, Uint8ArrayWriteBuffer } = require('@theia/core/lib/common/message-rpc/uint8-array-message-buffer'); +const { MsgPackMessageDecoder, MsgPackMessageEncoder } = require('@theia/core/lib/common/message-rpc/rpc-message-encoder'); +const { BatchingChannel, RPCProtocolImpl, createProxyIdentifier } = require('@theia/plugin-ext/lib/common/rpc-protocol'); +const { ConnectionImpl } = require('@theia/plugin-ext/lib/common/connection'); +const { ForwardingDebugChannel } = require('@theia/debug/lib/common/debug-service'); +const { Emitter } = require('@theia/core/lib/common/event'); +const { filterPluginRpc, guardDebugChannel, MAX_BATCH_MESSAGES } = require('../plugin-dap-guard.cjs'); +const { Coordinator, DEBUG_LEASE_MS } = require('../../coordination/index.cjs'); + +const encoder = new MsgPackMessageEncoder(); +const decoder = new MsgPackMessageDecoder(); +const deny = () => { throw new Error('DEBUG_FORBIDDEN'); }; +function rpc(method, service, id = 1, type = 1, rest = []) { + const writer = new Uint8ArrayWriteBuffer(); + if (type === 2) encoder.notification(writer, method, [service, ...rest], id); + else encoder.request(writer, id, method, [service, ...rest]); + return writer.getCurrentContents(); +} +function batch(...messages) { + const writer = new Uint8ArrayWriteBuffer(); + writer.writeLength(messages.length); + for (const message of messages) writer.writeBytes(message); + return writer.getCurrentContents(); +} +function decode(payload) { + if (!payload) return []; + const reader = new Uint8ArrayReadBuffer(payload); + const count = reader.readLength(); + return Array.from({ length: count }, () => decoder.parse(new Uint8ArrayReadBuffer(reader.readBytes()))); +} +function memoryChannel() { + const messages = new Emitter(); + const errors = new Emitter(); + const closes = new Emitter(); + const sent = []; + let closed = false; + return { + sent, get closed() { return closed; }, + onMessage: messages.event, onError: errors.event, onClose: closes.event, + getWriteBuffer() { const writer = new Uint8ArrayWriteBuffer(); writer.onCommit(value => sent.push(value)); return writer; }, + close() { closed = true; closes.fire({ code: 1000, reason: 'closed' }); }, + receive(bytes) { messages.fire(() => new Uint8ArrayReadBuffer(bytes)); }, + }; +} + +test('real Theia RPCProtocol emits the DebugExt wire shape gated by the filter', async () => { + const wire = memoryChannel(); + const protocol = new RPCProtocolImpl(wire); + const pending = protocol.getProxy(createProxyIdentifier('DebugExt')).$createDebugSession({ type: 'pwa-node', name: 'test' }, 'file:///workspace'); + const rejected = assert.rejects(pending, /DEBUG_CONTROL_REQUIRED/); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(wire.sent.length, 1); + const actual = decode(wire.sent[0]); + assert.equal(actual[0].method, '$createDebugSession'); + assert.equal(actual[0].args[0], 'DebugExt'); + const result = filterPluginRpc(wire.sent[0], deny); + assert.equal(result.forwarded, null); + assert.equal(result.denied, 1); + wire.receive(result.replies); + await rejected; + protocol.dispose(); +}); + +test('unauthorized plugin create/terminate/send/delete requests never enter the forwarded host batch', () => { + const calls = [ + rpc('$createDebugSession', 'DebugExt', 10), rpc('$terminateDebugSession', 'DebugExt', 11), + rpc('$sendMessage', 'ConnectionExt', 12, 1, ['session', '{"command":"continue"}']), rpc('$deleteConnection', 'ConnectionExt', 13), + ]; + const result = filterPluginRpc(batch(...calls), deny); + assert.equal(result.forwarded, null); + assert.equal(result.denied, 4); + assert.deepEqual(decode(result.replies).map(message => ({ type: message.type, id: message.id, error: message.err.message })), [10, 11, 12, 13].map(id => ({ type: 4, id, error: 'DEBUG_CONTROL_REQUIRED' }))); +}); + +test('denied plugin DAP reaches real frontend RPCProtocol and ConnectionMain as a failed response', async () => { + const wire = memoryChannel(); + const protocol = new RPCProtocolImpl(wire); + const proxy = protocol.getProxy(createProxyIdentifier('ConnectionExt')); + const connectionMain = protocol.set(createProxyIdentifier('ConnectionMain'), new ConnectionImpl(proxy)); + const frontendChannel = await connectionMain.doEnsureConnection('session-real'); + const received = []; + frontendChannel.onMessage(message => received.push(JSON.parse(message))); + let previousSequence = 0; + try { + for (const [seq, command] of [[31, 'next'], [32, 'continue']]) { + const pending = proxy.$sendMessage('session-real', JSON.stringify({ type: 'request', seq, command, arguments: { threadId: 1 } })); + const rejected = assert.rejects(pending, /DEBUG_CONTROL_REQUIRED/); + await new Promise(resolve => setImmediate(resolve)); + const result = filterPluginRpc(wire.sent.at(-1), deny); + assert.equal(result.forwarded, null); + assert.equal(result.denied, 1); + const messages = decode(result.replies); + assert.equal(messages[0].type, 4); + assert.equal(messages[1].type, 2); + assert.equal(messages[1].method, '$sendMessage'); + assert.deepEqual(messages[1].args.slice(0, 2), ['ConnectionMain', 'session-real']); + wire.receive(result.replies); + await rejected; + const response = received.at(-1); + assert.ok(Number.isSafeInteger(response.seq) && response.seq > previousSequence); + previousSequence = response.seq; + assert.deepEqual({ ...response, seq: undefined }, { + seq: undefined, type: 'response', request_seq: seq, command, success: false, + message: 'WishForge debug controller lease required', + }); + } + assert.equal(received.length, 2); + } finally { protocol.dispose(); } +}); + +test('denied DAP carried as an RPC notification receives only a DAP failure notification', () => { + const request = JSON.stringify({ type: 'request', seq: 4, command: 'disconnect' }); + const result = filterPluginRpc(batch(rpc('$sendMessage', 'ConnectionExt', 42, 2, ['session-one', request])), deny); + assert.equal(result.forwarded, null); + assert.equal(result.denied, 1); + const replies = decode(result.replies); + assert.equal(replies.length, 1); + assert.equal(replies[0].type, 2); + assert.deepEqual(replies[0].args.slice(0, 2), ['ConnectionMain', 'session-one']); + assert.equal(JSON.parse(replies[0].args[2]).request_seq, 4); +}); + +test('malformed or nonrequest denied plugin DAP never fabricates a DAP response', () => { + const cases = [ + ['session', 'bad-json'], ['session', 'null'], ['session', '[]'], + ['session', '{"type":"event","seq":1,"command":"next"}'], + ['session', '{"type":"request","seq":"1","command":"next"}'], + ['session', '{"type":"request","seq":-1,"command":"next"}'], + ['session', '{"type":"request","seq":1}'], + ['session', '{"type":"request","seq":1,"command":""}'], + ['session', { type: 'request', seq: 1, command: 'next' }], + ['', '{"type":"request","seq":1,"command":"next"}'], + [5, '{"type":"request","seq":1,"command":"next"}'], + ]; + for (const args of cases) { + const result = filterPluginRpc(batch(rpc('$sendMessage', 'ConnectionExt', 42, 1, args)), deny); + assert.equal(result.forwarded, null); + assert.equal(result.denied, 1); + const replies = decode(result.replies); + assert.equal(replies.length, 1); + assert.equal(replies[0].type, 4); + assert.equal(replies[0].err.message, 'DEBUG_CONTROL_REQUIRED'); + } +}); + +test('ordinary RPC forwards byte-for-byte while denied notifications do not fabricate replies', () => { + const ordinary = rpc('$acceptModelChanged', 'EditorsAndDocumentsExt', 1, 2); + const reply = new Uint8ArrayWriteBuffer(); + encoder.replyOK(reply, 8, { success: true }); + const result = filterPluginRpc(batch(ordinary, rpc('$sendMessage', 'ConnectionExt', 2, 2), reply.getCurrentContents()), deny); + assert.deepEqual(result.forwarded, batch(ordinary, reply.getCurrentContents())); + assert.equal(result.replies, null); + assert.equal(result.denied, 1); +}); + +test('controller forwarding preserves actual BatchingChannel bytes and rechecks authorization for every command', () => { + const wire = memoryChannel(); + const batching = new BatchingChannel(wire); + const first = batching.getWriteBuffer(); encoder.request(first, 1, '$createDebugSession', ['DebugExt']); first.commit(); + const second = batching.getWriteBuffer(); encoder.request(second, 2, '$sendMessage', ['ConnectionExt', 'session', '{}']); second.commit(); + batching.sendAccumulated(); + const payload = wire.sent[0]; + let checks = 0; + const allowed = filterPluginRpc(payload, () => { checks++; }); + assert.deepEqual(allowed.forwarded, payload); + assert.equal(allowed.replies, null); + assert.equal(checks, 2); + checks = 0; + const revokedMidBatch = filterPluginRpc(payload, () => { if (++checks === 2) deny(); }); + assert.equal(decode(revokedMidBatch.forwarded).length, 1); + assert.equal(decode(revokedMidBatch.replies)[0].id, 2); + batching.close(); +}); + +test('malformed, truncated, oversized or trailing frames fail atomically before any forwarding', () => { + const good = batch(rpc('$createDebugSession', 'DebugExt')); + const excessive = new Uint8ArrayWriteBuffer(); excessive.writeLength(MAX_BATCH_MESSAGES + 1); + const invalidInner = new Uint8ArrayWriteBuffer(); invalidInner.writeLength(100); invalidInner.writeRaw(new Uint8Array([1])); + const wrongShape = new Uint8ArrayWriteBuffer(); encoder.encode(wrongShape, { type: 1, id: 3, method: '$sendMessage', args: { 0: 'ConnectionExt' } }); + for (const bytes of [new Uint8Array(), good.slice(0, -1), new Uint8Array([...good, 0]), excessive.getCurrentContents(), batch(invalidInner.getCurrentContents()), batch(wrongShape.getCurrentContents()), new Uint8Array([129, 129, 129, 129, 129, 0])]) { + let invoked = false; + assert.throws(() => filterPluginRpc(bytes, () => { invoked = true; }), /PLUGIN_RPC|RPC_BATCH_LIMIT/); + assert.equal(invoked, false); + } + // Prevent reading into extra bytes from a websocket buffer outside the actual view. + const backed = new Uint8Array([...good, ...good]); + assert.throws(() => filterPluginRpc(backed.subarray(0, good.length - 1), deny), /PLUGIN_RPC/); + assert.deepEqual(filterPluginRpc(batch(), deny), { forwarded: null, replies: null, denied: 0 }); +}); + +test('guard cannot accidentally authorize on a false or asynchronous decision', () => { + const payload = batch(rpc('$sendMessage', 'ConnectionExt')); + for (const callback of [() => false, () => Promise.resolve(true)]) assert.equal(filterPluginRpc(payload, callback).forwarded, null); + assert.throws(() => filterPluginRpc(payload), /DEBUG_GUARD_REQUIRED/); +}); + +test('real coordinator lease owner, renewal, expiry and revocation govern plugin forwarding', t => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-debug-guard-')); + const workspaceRoot = path.join(directory, 'source'); fs.mkdirSync(workspaceRoot); + let now = 1000; + const coordinator = new Coordinator({ workspaceRoot, stateDirectory: path.join(directory, 'state'), now: () => now }); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const alice = coordinator.debugAcquire('alice'); + const payload = batch(rpc('$sendMessage', 'ConnectionExt')); + assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('bob', alice.token)).forwarded, null); + assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('alice', 'another-tab-token')).forwarded, null); + const permitted = () => coordinator.assertDebugController('alice', alice.token); + assert.deepEqual(filterPluginRpc(payload, permitted).forwarded, payload); + now += 10_000; + coordinator.debugAcquire('alice', alice.token); + now += DEBUG_LEASE_MS - 10_000; + assert.deepEqual(filterPluginRpc(payload, permitted).forwarded, payload); + now += 10_000; + assert.equal(filterPluginRpc(payload, permitted).forwarded, null); + const next = coordinator.debugAcquire('alice'); + assert.deepEqual(filterPluginRpc(payload, () => coordinator.assertDebugController('alice', next.token)).forwarded, payload); + coordinator.revoke('alice'); + assert.equal(filterPluginRpc(payload, () => coordinator.assertDebugController('alice', next.token)).forwarded, null); +}); + +test('native DAP wrapper checks the live lease before adapter callback and sends decodable denials', () => { + const wire = memoryChannel(); + const raw = new ForwardingDebugChannel(wire); + let allowed = false; + const guarded = guardDebugChannel(raw, () => { if (!allowed) deny(); }); + const received = []; + guarded.onMessage(message => received.push(JSON.parse(message))); + const incoming = (seq, command) => { + const writer = new Uint8ArrayWriteBuffer(); writer.writeString(JSON.stringify({ type: 'request', seq, command })); wire.receive(writer.getCurrentContents()); + }; + incoming(1, 'launch'); incoming(2, 'continue'); + assert.deepEqual(received, []); + const errors = wire.sent.map(bytes => JSON.parse(new Uint8ArrayReadBuffer(bytes).readString())); + assert.deepEqual(errors.map(error => [error.seq, error.request_seq, error.command, error.success]), [[1, 1, 'launch', false], [2, 2, 'continue', false]]); + allowed = true; incoming(3, 'next'); + assert.equal(received[0].command, 'next'); + allowed = false; incoming(4, 'disconnect'); + assert.equal(received.length, 1); + guarded.send(JSON.stringify({ type: 'event', event: 'stopped' })); + assert.equal(JSON.parse(new Uint8ArrayReadBuffer(wire.sent.at(-1)).readString()).event, 'stopped'); + guarded.close(); + assert.equal(wire.closed, true); +}); + +test('unauthorized malformed native DAP closes channel without reaching adapter', () => { + for (const message of ['bad-json', 'null', '{"type":"event","event":"stopped"}', '{"type":"request","seq":1}']) { + const wire = memoryChannel(); + const guarded = guardDebugChannel(new ForwardingDebugChannel(wire), deny); + let reached = false; + guarded.onMessage(() => { reached = true; }); + const writer = new Uint8ArrayWriteBuffer(); writer.writeString(message); wire.receive(writer.getCurrentContents()); + assert.equal(reached, false); + assert.equal(wire.closed, true); + assert.equal(wire.sent.length, 0); + } +}); diff --git a/apps/ide/policy/test/drafts.test.cjs b/apps/ide/policy/test/drafts.test.cjs new file mode 100644 index 0000000..81d4aed --- /dev/null +++ b/apps/ide/policy/test/drafts.test.cjs @@ -0,0 +1,6 @@ +const test=require('node:test');const assert=require('node:assert/strict');const {DraftStore}=require('../drafts.cjs'); +test('draft quota rejects oversized ASCII and multibyte content before touching IndexedDB',()=>{ + const store=new DraftStore({open(){throw new Error('storage should not be opened');}}); + assert.throws(()=>store.put({text:'a'.repeat(2*1024*1024+1),baseText:''}),/2 MiB/); + assert.throws(()=>store.put({text:'中'.repeat(800000),baseText:''}),/2 MiB/); +}); diff --git a/apps/ide/policy/test/lifecycle-safety.test.cjs b/apps/ide/policy/test/lifecycle-safety.test.cjs new file mode 100644 index 0000000..1b8082c --- /dev/null +++ b/apps/ide/policy/test/lifecycle-safety.test.cjs @@ -0,0 +1,4 @@ +'use strict';const test=require('node:test');const assert=require('node:assert/strict');const {sleepReceipt}=require('../lifecycle-safety.cjs'); +const hash='a'.repeat(64);function fixture(){return{coordinator:{inputState:()=>({activeClients:0,dirty:false,currentDiskDigest:hash,latestSnapshot:{digest:hash,revision:1}}),state:()=>({debugController:null})},processManager:{processes:new Map()},debugManager:{getAll:()=>[].values()},snapshotPending:false,hostedDebugTouched:false};} +test('quiescent saved workspace reports complete snapshots and no active processes',()=>{assert.deepEqual(sleepReceipt(fixture()),{known:true,activeClients:0,terminals:0,debugSessions:0,dirty:false,snapshotComplete:true,snapshotRevision:1,diskDigest:hash});}); +test('unknown/debug/plugin activity, active terminals and incomplete snapshots never look quiescent',()=>{const f=fixture();f.processManager.processes.set(1,{});assert.equal(sleepReceipt(f).terminals,1);f.hostedDebugTouched=true;assert.equal(sleepReceipt(f).known,false);f.hostedDebugTouched=false;f.debugManager.getAll=()=>[{}].values();assert.equal(sleepReceipt(f).debugSessions,1);f.coordinator.inputState=()=>({activeClients:1,dirty:true,currentDiskDigest:hash,latestSnapshot:{digest:'b'.repeat(64),revision:1}});assert.equal(sleepReceipt(f).snapshotComplete,false);assert.equal(sleepReceipt(f).activeClients,1);assert.equal(sleepReceipt({...f,processManager:{}}).known,false);assert.equal(sleepReceipt({...f,snapshotPending:true}).known,false);}); diff --git a/apps/ide/policy/test/plugin-install-policy.test.cjs b/apps/ide/policy/test/plugin-install-policy.test.cjs new file mode 100644 index 0000000..df1bd25 --- /dev/null +++ b/apps/ide/policy/test/plugin-install-policy.test.cjs @@ -0,0 +1,59 @@ +'use strict'; +require('reflect-metadata'); +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { treeDigest, validateManagedPlugins } = require('../managed-plugins.cjs'); +const { ManagedPluginServer, ManagedPluginDeployer } = require('../plugin-install-policy.cjs'); + +function fixture(t) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wishforge-managed-plugins-')); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + const directory = path.join(root, 'test.approved'); + fs.mkdirSync(path.join(directory, 'extension'), { recursive: true }); + fs.writeFileSync(path.join(directory, 'extension/package.json'), JSON.stringify({ publisher: 'test', name: 'approved', version: '1.0.0' })); + fs.writeFileSync(path.join(directory, 'extension/main.js'), 'exports.activate = () => {};\n'); + const catalog = { plugins: [{ directory: 'test.approved', id: 'test.approved', version: '1.0.0', sha256: treeDigest(directory) }] }; + return { root, directory, options: { catalog, pythonLock: null } }; +} + +test('approved ID/version/content loads while unrelated hidden cache is ignored', t => { + const f = fixture(t); fs.mkdirSync(path.join(f.root, '.downloads')); + assert.equal(validateManagedPlugins(f.root, f.options).length, 1); +}); +test('same ID and version with changed implementation fails digest validation', t => { + const f = fixture(t); fs.appendFileSync(path.join(f.directory, 'extension/main.js'), 'malicious();'); + assert.throws(() => validateManagedPlugins(f.root, f.options), /DIGEST_REJECTED/); +}); +test('changed version and additional plugin are refused', t => { + const f = fixture(t); + fs.writeFileSync(path.join(f.directory, 'extension/package.json'), JSON.stringify({ publisher: 'test', name: 'approved', version: '2.0.0' })); + assert.throws(() => validateManagedPlugins(f.root, f.options), /ID_VERSION_REJECTED/); + fs.mkdirSync(path.join(f.root, 'unapproved.plugin')); + assert.throws(() => validateManagedPlugins(f.root, f.options), /ALLOWLIST_MISMATCH/); +}); +test('symlinks cannot substitute plugin code or plugin directories', t => { + const f = fixture(t); fs.symlinkSync('/tmp', path.join(f.directory, 'escape')); + assert.throws(() => validateManagedPlugins(f.root, f.options), /SYMLINK_REJECTED/); +}); +test('actual Theia PluginServer install routes reject registry, VSIX, update and forged system type before calling deployer', async () => { + const server = new ManagedPluginServer(); + server.pluginDeployer = new Proxy({}, { get() { throw new Error('Unsafe deployer reached'); } }); + for (const id of ['vscode:untrusted.extension', 'file:///tmp/plugin.vsix', 'https://example.invalid/plugin.vsix', 'vscode:ms-python.debugpy@2026.6.0']) { + await assert.rejects(server.install(id, 0, { ignoreDependencies: true }), /EXTENSIONS_MANAGED_BY_ADMIN/); + } + for (const method of ['doInstall', 'uninstall', 'enablePlugin', 'disablePlugin']) await assert.rejects(server[method]('test.approved'), /EXTENSIONS_MANAGED_BY_ADMIN/); +}); +test('direct deployer mutation paths and bulk/update paths are closed', async () => { + const deployer = new ManagedPluginDeployer(); + for (const method of ['deploy', 'deployMultipleEntries', 'deployPlugins', 'uninstall', 'undeploy', 'enablePlugin', 'disablePlugin']) { + await assert.rejects(deployer[method]({ id: 'local-dir:/tmp/evil', type: 0 }), /EXTENSIONS_MANAGED_BY_ADMIN/); + } +}); +test('installed plugin reads still reach the normal Theia implementation', async () => { + const server = new ManagedPluginServer(); + server.pluginDeployerHandler = { getDeployedPluginIds: () => ['test.approved@1.0.0'] }; + assert.deepEqual(await server.getInstalledPlugins(), ['test.approved@1.0.0']); +}); diff --git a/apps/ide/product.json b/apps/ide/product.json new file mode 100644 index 0000000..6970491 --- /dev/null +++ b/apps/ide/product.json @@ -0,0 +1,7 @@ +{ + "nameShort": "WishForge", + "nameLong": "WishForge IDE", + "applicationName": "wishforge-ide", + "version": "1.108.2", + "extensionEnabledApiProposals": {} +} diff --git a/apps/ide/provisioner/README.md b/apps/ide/provisioner/README.md new file mode 100644 index 0000000..93d0514 --- /dev/null +++ b/apps/ide/provisioner/README.md @@ -0,0 +1,80 @@ +# Run sandbox provisioner + +This service renders and applies real Kubernetes resources through an explicit +`kubectl --context ... --namespace ...` command. It has no local fallback and does +not start without a tenant, cluster context, namespace, digest-pinned worker image, +storage class, HTTPS control-plane URL and Temporal configuration. + +`POST /runs` requires `Authorization: Bearer ` and +`{tenantId, runId, generation, executorToken, verifierToken, resourceGrant}`. The authenticated control plane +issues the two short-lived run-scoped tokens. The provisioner checks their scope +and lifetime without holding the token-signing key. The API independently verifies +signatures when the workers use them. Returned status `provisioned` means Kubernetes +accepted the resources; it does not mean either pod is scheduled or ready. + +The independent HMAC resource grant binds the immutable runtime image and total +CPU/memory/persistent-volume allowance for both roles. Each role receives half, +rounded down. This grant does not include retained earlier-generation PVCs, IDE +resources or temporary disk (currently an 8 GiB ephemeral limit and 4 GiB `/tmp` +limit per role); it is not an aggregate tenant storage budget. +The provisioner verifies the signature, expiry and its static caps, then renders the +signed image only if listed in the current/previous runtime allowlist. Workers never +receive the grant-signing key. See [plans and admission](../../../docs/billing-entitlements.md). + +Each run receives deterministic, idempotent names for two independent RWO PVCs, one per role, two +separate capability Secrets, two unbound service accounts, two Kata Jobs and a +run-scoped NetworkPolicy. Policy/identities are applied before jobs. Jobs get only +their own role token and cannot mount a Kubernetes token, host path or Docker +socket. Provider homes are private memory volumes. Only DNS plus labeled API and +Temporal services are allowed by the generated network policy; provider/tool/build +network access requires separately reviewed egress-proxy configuration. + +Required environment: + +```text +WF_TENANT_ID= +WF_PROVISIONER_TOKEN= +WF_RESOURCE_GRANT_SECRET= +WF_KUBE_CONTEXT= +WF_KUBE_NAMESPACE= +WF_RUN_WORKER_IMAGE= +WF_RUN_PREVIOUS_IMAGES= +WF_RUN_STORAGE_CLASS= +WF_CONTROL_PLANE_URL=https://api.wishforge-control.svc:8443 +WF_CONTROL_NAMESPACE=wishforge-control +TEMPORAL_ADDRESS=temporal.wishforge-control.svc:7233 +TEMPORAL_NAMESPACE=wishforge +``` + +Optional `WF_VERIFIER_DOCKER_CONFIG_SECRET` references a separately provisioned +verifier-only Docker/BuildKit client configuration. There is no default daemon, +host socket or registry credential. An isolated builder plus its explicit egress +and authentication still need provisioning and acceptance; without them the +runtime must fail closed at build time. The worker image must include Node/runtime, +the configured coding adapters and `/usr/bin/bwrap`; Kata and nested unprivileged +bubblewrap support must be tested on the actual node pool. + +The executor cannot mount the verifier's PVC. The verifier restores an exact Git +bundle and validates its digest and source SHA in its own workspace. API leases +and generation-bound capabilities independently fence stale evidence. Before a +new generation starts, only this run's older managed Jobs are deleted with +foreground propagation; their PVCs remain for diagnosis. A terminal Job in the +same generation returns failed and requires an explicit new-generation resume. Tokens expire; jobs have a shorter hard +deadline. Existing terminal Jobs are not silently deleted/recreated by retries. +An operator-controlled retry/cleanup policy must reconcile expired jobs and +Secrets; PVC deletion requires the applicable retention policy. No endpoint grants +arbitrary namespace, image, command or cleanup control to callers. + +`POST /runs/release` accepts `{tenantId,runId,generation,resourceGrant}` with the same +service authentication. It checks owned generation labels, stops only matching Jobs, +and reports whether compute has stopped; it never deletes persistent volumes or +fabricates compute billing measurements. Provision/cleanup is serialized per run +within this process. Run a single active provisioner per tenant namespace; this queue +is not durable distributed fencing across a process restart. Unknown prior outcomes +remain reserved until API-side operator reconciliation after cleanup. + +Tests validate rendered resources and fake command invocation; **no real cluster +has been provisioned**. Production acceptance requires actual RuntimeClass VM +proof, Secret/role isolation, CNI denial, independent RWO storage, generation-bound queue routing, +bubblewrap execution and end-to-end token revocation. `WF_SANDBOX_ENFORCED=true` +records the intended runtime path; it is not independent evidence of isolation. diff --git a/apps/ide/provisioner/main.mjs b/apps/ide/provisioner/main.mjs new file mode 100644 index 0000000..3b49ddb --- /dev/null +++ b/apps/ide/provisioner/main.mjs @@ -0,0 +1,34 @@ +import http from 'node:http'; +import { timingSafeEqual } from 'node:crypto'; +import { readConfig, provisionRun } from './provisioner.mjs'; +import { provisionWorkspace } from './workspaces.mjs'; +import { releaseRun } from './run-release.mjs'; +import {observeWorkspaceLifecycle,reconcileWorkspaceLifecycle} from './workspace-lifecycle.mjs'; +import { createRunOperationQueue } from './run-operations.mjs'; + +const config = readConfig(); +const expected = process.env.WF_PROVISIONER_TOKEN; +const runOperation = createRunOperationQueue(); +if (!expected || expected.length < 32) throw new Error('unconfigured: scoped WF_PROVISIONER_TOKEN must be at least 32 characters'); +const server = http.createServer(async (req, res) => { + res.setHeader('content-type', 'application/json'); res.setHeader('cache-control', 'no-store'); + try { + const token = req.headers.authorization?.replace(/^Bearer /, '') ?? ''; + if (token.length !== expected.length || !timingSafeEqual(Buffer.from(token), Buffer.from(expected))) { res.writeHead(401); res.end(JSON.stringify({ error: 'UNAUTHORIZED' })); return; } + if (req.url === '/healthz' && req.method === 'GET') { res.end(JSON.stringify({ status: 'configured', tenantId: config.tenantId })); return; } + const target=new URL(req.url,'http://provisioner.local'); + const lifecycle=/^\/workspaces\/([a-zA-Z0-9_-]{1,128})\/lifecycle$/.exec(target.pathname); + if(lifecycle&&req.method==='GET'){const input={tenantId:target.searchParams.get('tenantId'),projectId:target.searchParams.get('projectId'),workspaceId:lifecycle[1]};res.end(JSON.stringify(await observeWorkspaceLifecycle(config,input)));return;} + if(lifecycle&&req.method==='PUT'){let body='';for await(const part of req){body+=part;if(body.length>4000)throw new Error('INVALID_REQUEST');}const input=JSON.parse(body);if(input.workspaceId!==lifecycle[1])throw new Error('INVALID_WORKSPACE_SCOPE');const state=await reconcileWorkspaceLifecycle(config,input);res.writeHead(202);res.end(JSON.stringify(state));return;} + if (!['/runs', '/runs/release', '/workspaces'].includes(req.url) || req.method !== 'POST') { res.writeHead(404); res.end(JSON.stringify({ error: 'NOT_FOUND' })); return; } + let body = ''; for await (const part of req) { body += part; if (body.length > 40000) throw new Error('INVALID_REQUEST'); } + const input = JSON.parse(body); + const result = req.url === '/workspaces' ? await provisionWorkspace(config, input) : await runOperation(input.tenantId, input.runId, () => req.url === '/runs/release' ? releaseRun(config, input) : provisionRun(config, input)); + res.writeHead(202); res.end(JSON.stringify(result)); + } catch (error) { + const infrastructure = error.message.startsWith('KUBERNETES_'); + res.writeHead(infrastructure ? 502 : 400); + res.end(JSON.stringify({ error: infrastructure || ['RESOURCE_GRANT_INVALID','RESOURCE_GRANT_EXPIRED','RESOURCE_LIMIT','RUNTIME_IMAGE_MIGRATION_REQUIRED'].includes(error.message) ? error.message : 'INVALID_RUN_REQUEST' })); + } +}); +server.listen(Number(process.env.WF_PROVISIONER_PORT ?? 4450), process.env.WF_PROVISIONER_HOST ?? '127.0.0.1', () => console.log('Run provisioner configured; no workloads are launched until an authenticated request arrives.')); diff --git a/apps/ide/provisioner/package.json b/apps/ide/provisioner/package.json new file mode 100644 index 0000000..5290573 --- /dev/null +++ b/apps/ide/provisioner/package.json @@ -0,0 +1,7 @@ +{ + "name": "@wishforge/run-provisioner", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { "start": "node main.mjs", "test": "node --test test/*.test.mjs" } +} diff --git a/apps/ide/provisioner/provisioner.mjs b/apps/ide/provisioner/provisioner.mjs new file mode 100644 index 0000000..205d6e3 --- /dev/null +++ b/apps/ide/provisioner/provisioner.mjs @@ -0,0 +1,174 @@ +import { createHash } from 'node:crypto'; +import { spawn } from 'node:child_process'; +import { verifyResourceGrant } from './resource-grants.mjs'; + +const safe = /^[a-zA-Z0-9_-]{1,128}$/; +const dns = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/; +function requireValue(value, name) { if (!value) throw new Error(`unconfigured: ${name} is required`); return value; } +export function readConfig(env = process.env) { + const config = { + tenantId: requireValue(env.WF_TENANT_ID, 'WF_TENANT_ID'), + context: requireValue(env.WF_KUBE_CONTEXT, 'WF_KUBE_CONTEXT'), + namespace: requireValue(env.WF_KUBE_NAMESPACE, 'WF_KUBE_NAMESPACE'), + image: requireValue(env.WF_RUN_WORKER_IMAGE, 'WF_RUN_WORKER_IMAGE'), + storageClass: requireValue(env.WF_RUN_STORAGE_CLASS, 'WF_RUN_STORAGE_CLASS'), + storageSize: env.WF_RUN_STORAGE_SIZE ?? '10Gi', + controlPlaneUrl: requireValue(env.WF_CONTROL_PLANE_URL, 'WF_CONTROL_PLANE_URL'), + controlNamespace: requireValue(env.WF_CONTROL_NAMESPACE, 'WF_CONTROL_NAMESPACE'), + temporalAddress: requireValue(env.TEMPORAL_ADDRESS, 'TEMPORAL_ADDRESS'), + temporalNamespace: requireValue(env.TEMPORAL_NAMESPACE, 'TEMPORAL_NAMESPACE'), + runtimeClass: env.WF_KATA_RUNTIME_CLASS ?? 'wishforge-kata', + activeDeadlineSeconds: Number(env.WF_RUN_MAX_SECONDS ?? 3600), + verifierDockerSecret: env.WF_VERIFIER_DOCKER_CONFIG_SECRET, + resourceGrantSecret: requireValue(env.WF_RESOURCE_GRANT_SECRET, 'WF_RESOURCE_GRANT_SECRET'), + cpuMilliCap: Number(env.WF_RUN_CPU_MILLI_CAP ?? 2000), memoryMiBCap: Number(env.WF_RUN_MEMORY_MIB_CAP ?? 4096), + previousImages: (env.WF_RUN_PREVIOUS_IMAGES ?? '').split(',').map(value=>value.trim()).filter(Boolean), + }; + if (!safe.test(config.tenantId) || [config.namespace, config.controlNamespace, config.runtimeClass, config.storageClass, ...(config.verifierDockerSecret ? [config.verifierDockerSecret] : [])].some(value => !dns.test(value) || value.length > 63)) throw new Error('Invalid configured tenant/namespace/runtime class/storage/secret'); + if (!/^[^\s]+@sha256:[a-f0-9]{64}$/.test(config.image)) throw new Error('WF_RUN_WORKER_IMAGE must be an immutable sha256 image digest'); + if (config.resourceGrantSecret.length < 32 || !Number.isSafeInteger(config.cpuMilliCap) || config.cpuMilliCap < 100 || !Number.isSafeInteger(config.memoryMiBCap) || config.memoryMiBCap < 512 || config.previousImages.length > 10 || config.previousImages.some(image=>!/^[^\s]+@sha256:[a-f0-9]{64}$/.test(image))) throw new Error('Invalid resource grant signing key, static caps or previous runtime image allowlist'); + if (!/^\d+Gi$/.test(config.storageSize)) throw new Error('Invalid run storage size'); + if (!Number.isInteger(config.activeDeadlineSeconds) || config.activeDeadlineSeconds < 60 || config.activeDeadlineSeconds > 10800) throw new Error('Run deadline must be 60..10800 seconds and shorter than the scoped token lifetime'); + const api = new URL(config.controlPlaneUrl); + if (api.protocol !== 'https:' || api.username || api.password || api.search || api.hash) throw new Error('Production control plane must use an HTTPS URL without embedded credentials'); + if (!/^[a-zA-Z0-9.-]+:\d+$/.test(config.temporalAddress)) throw new Error('TEMPORAL_ADDRESS must explicitly include host:port'); + if (Number(config.temporalAddress.split(':').at(-1)) < 1 || Number(config.temporalAddress.split(':').at(-1)) > 65535) throw new Error('Invalid Temporal port'); + return config; +} + +function assertToken(token, request, kind, deadline) { + try { + const parts = token.split('.'); + if (parts.length !== 3 || token.length > 16384) throw new Error(); + const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')); + if (claims.tenant_id !== request.tenantId || claims.run_id !== request.runId || claims.generation !== request.generation || claims.kind !== kind || claims.iss !== 'wishforge-control-plane' || claims.aud !== 'wishforge-internal' || !Number.isFinite(claims.exp) || claims.exp * 1000 <= Date.now() + deadline * 1000) throw new Error(); + } catch { throw new Error(`Invalid or insufficient-lifetime ${kind} run token`); } + // The authenticated control plane issues these tokens. This shape/scope check + // is defense-in-depth, not signature verification; the API verifies signatures. +} + +export function renderRunResources(config, request) { + if (!request || Object.keys(request).some(key => !['tenantId', 'runId', 'generation', 'executorToken', 'verifierToken', 'resourceGrant'].includes(key)) || request.tenantId !== config.tenantId || !safe.test(request.runId ?? '') || !safe.test(request.generation ?? '')) throw new Error('Run request is outside the configured tenant or has invalid fields'); + const resourceGrant = verifyResourceGrant(config, request); + // One reservation covers both isolated roles; aggregate requested limits must + // stay within the signed run grant, including their separate persistent PVCs. + const roleResources = { cpuMilli: Math.floor(resourceGrant.cpuMilli / 2), memoryMiB: Math.floor(resourceGrant.memoryMiB / 2), storageMiB: Math.floor(resourceGrant.storageMiB / 2) }; + assertToken(request.executorToken, request, 'worker', config.activeDeadlineSeconds); + assertToken(request.verifierToken, request, 'verifier', config.activeDeadlineSeconds); + if (request.executorToken === request.verifierToken) throw new Error('Executor and verifier credentials must differ'); + const runHash = createHash('sha256').update(`${request.tenantId}\0${request.runId}`).digest('hex').slice(0, 24); + const generationHash = createHash('sha256').update(request.generation).digest('hex').slice(0, 24); + const suffix = createHash('sha256').update(`${request.tenantId}\0${request.runId}\0${request.generation}`).digest('hex').slice(0, 24); + const prefix = `wf-${suffix}`; + const labels = { 'app.kubernetes.io/managed-by': 'wishforge-provisioner', 'wishforge.io/run': runHash, 'wishforge.io/generation': generationHash, 'wishforge.io/component': 'runner' }; + const metadata = name => ({ name, namespace: config.namespace, labels }); + const claims = Object.fromEntries(['executor', 'verifier'].map(role => [role, `${prefix}-${role}-workspace`])); + const resources = Object.values(claims).map(claim => ({ apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata: metadata(claim), spec: { storageClassName: config.storageClass, accessModes: ['ReadWriteOnce'], resources: { requests: { storage: `${roleResources.storageMiB}Mi` } } } })); + for (const role of ['executor', 'verifier']) { + const name = `${prefix}-${role}`; + const secretName = `${name}-capability`; + resources.push({ apiVersion: 'v1', kind: 'Secret', metadata: metadata(secretName), type: 'Opaque', stringData: { token: request[role === 'executor' ? 'executorToken' : 'verifierToken'] } }); + resources.push({ apiVersion: 'v1', kind: 'ServiceAccount', metadata: metadata(name), automountServiceAccountToken: false }); + const env = [ + { name: 'WF_WORKER_ROLE', value: role }, + { name: 'WF_SANDBOX_RUN_ID', value: request.runId }, + { name: 'WF_SANDBOX_TENANT_ID', value: request.tenantId }, + { name: 'WF_SANDBOX_GENERATION', value: request.generation }, + { name: role === 'executor' ? 'WF_WORKER_TOKEN' : 'WF_VERIFIER_TOKEN', valueFrom: { secretKeyRef: { name: secretName, key: 'token' } } }, + { name: 'WF_WORKER_ID', value: name }, + { name: 'WF_WORKSPACE_ROOT', value: '/workspaces' }, + { name: 'WF_PROVIDER_HOME_ROOT', value: '/provider-home' }, + { name: 'WF_CONTROL_PLANE_URL', value: config.controlPlaneUrl }, + { name: 'TEMPORAL_ADDRESS', value: config.temporalAddress }, + { name: 'TEMPORAL_NAMESPACE', value: config.temporalNamespace }, + { name: 'WF_SANDBOX_ENFORCED', value: 'true' }, + { name: 'WF_WORKER_CONCURRENCY', value: '1' }, + { name: 'WF_EXECUTION_CPU_MILLI_LIMIT', value: String(roleResources.cpuMilli) }, + { name: 'WF_EXECUTION_MEMORY_MIB_LIMIT', value: String(roleResources.memoryMiB) }, + { name: 'WF_EXECUTION_STORAGE_MIB_LIMIT', value: String(roleResources.storageMiB) }, + ]; + const mounts = [{ name: 'workspace', mountPath: '/workspaces' }, { name: 'provider-home', mountPath: '/provider-home' }, { name: 'temporary', mountPath: '/tmp' }]; + const volumes = [{ name: 'workspace', persistentVolumeClaim: { claimName: claims[role] } }, { name: 'provider-home', emptyDir: { medium: 'Memory', sizeLimit: '256Mi' } }, { name: 'temporary', emptyDir: { sizeLimit: '4Gi' } }]; + if (role === 'verifier') { + env.push({ name: 'WF_VERIFIER_BWRAP', value: '/usr/bin/bwrap' }); + if (config.verifierDockerSecret) { + env.push({ name: 'WF_DOCKER_CONFIG', value: '/run/docker' }); + mounts.push({ name: 'docker-config', mountPath: '/run/docker', readOnly: true }); + volumes.push({ name: 'docker-config', secret: { secretName: config.verifierDockerSecret, defaultMode: 256 } }); + } + } + resources.push({ apiVersion: 'batch/v1', kind: 'Job', metadata: metadata(name), spec: { + backoffLimit: 0, activeDeadlineSeconds: config.activeDeadlineSeconds, ttlSecondsAfterFinished: 86400, + template: { metadata: { labels: { ...labels, 'wishforge.io/worker-role': role } }, spec: { + runtimeClassName: config.runtimeClass, serviceAccountName: name, automountServiceAccountToken: false, restartPolicy: 'Never', + securityContext: { runAsNonRoot: true, runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000, seccompProfile: { type: 'RuntimeDefault' } }, + containers: [{ name: role, image: resourceGrant.image, imagePullPolicy: 'Always', command: ['npm', 'run', 'dev', '-w', '@wishforge/worker'], env, + securityContext: { allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: { drop: ['ALL'] } }, + resources: { requests: { cpu: `${Math.min(1000,roleResources.cpuMilli)}m`, memory: `${Math.min(2048,roleResources.memoryMiB)}Mi`, 'ephemeral-storage': '1Gi' }, limits: { cpu: `${roleResources.cpuMilli}m`, memory: `${roleResources.memoryMiB}Mi`, 'ephemeral-storage': '8Gi' } }, volumeMounts: mounts }], volumes, + } }, + } }); + } + const nsSelector = { namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': config.controlNamespace } } }; + const apiPort = Number(new URL(config.controlPlaneUrl).port || 443); + const temporalPort = Number(config.temporalAddress.split(':').at(-1)); + resources.push({ apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata: metadata(`${prefix}-isolation`), spec: { + podSelector: { matchLabels: { 'wishforge.io/run': runHash, 'wishforge.io/generation': generationHash } }, policyTypes: ['Ingress', 'Egress'], ingress: [], + egress: [ + { to: [{ namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': 'kube-system' } }, podSelector: { matchLabels: { 'k8s-app': 'kube-dns' } } }], ports: [{ protocol: 'UDP', port: 53 }, { protocol: 'TCP', port: 53 }] }, + { to: [{ ...nsSelector, podSelector: { matchLabels: { 'wishforge.io/component': 'api' } } }], ports: [{ protocol: 'TCP', port: apiPort }] }, + { to: [{ ...nsSelector, podSelector: { matchLabels: { 'wishforge.io/component': 'temporal' } } }], ports: [{ protocol: 'TCP', port: temporalPort }] }, + ], + } }); + return { resources, receipt: { tenantId: request.tenantId, runId: request.runId, generation: request.generation, namespace: config.namespace, executorJobName: `${prefix}-executor`, verifierJobName: `${prefix}-verifier`, workspaceClaim: claims.executor, verifierWorkspaceClaim: claims.verifier, status: 'provisioned' } }; +} + +export function runKubectl(config, document) { + return new Promise((resolve, reject) => { + const child = spawn('kubectl', ['--context', config.context, '--namespace', config.namespace, 'apply', '--server-side', '--field-manager=wishforge-provisioner', '-o', 'name', '-f', '-'], { stdio: ['pipe', 'pipe', 'pipe'] }); + let output = ''; + const timeout = setTimeout(() => { child.kill('SIGTERM'); reject(new Error('KUBERNETES_APPLY_TIMEOUT')); }, 30000); + child.stdout.on('data', chunk => { output += chunk; if (output.length > 65536) child.kill('SIGTERM'); }); + // Never expose kubectl diagnostics: API validation errors can contain Secret data. + child.stderr.resume(); + child.on('error', () => { clearTimeout(timeout); reject(new Error('KUBERNETES_COMMAND_UNAVAILABLE')); }); + child.on('close', code => { clearTimeout(timeout); code === 0 ? resolve(output) : reject(new Error('KUBERNETES_APPLY_FAILED')); }); + child.stdin.on('error', () => {}); child.stdin.end(JSON.stringify({ apiVersion: 'v1', kind: 'List', items: document })); + }); +} + +export async function lifecycleCommand(config, args) { + return new Promise((resolve, reject) => { + const child = spawn('kubectl', ['--context', config.context, '--namespace', config.namespace, ...args], { stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout=''; const timer=setTimeout(()=>{child.kill('SIGKILL');reject(new Error('KUBERNETES_RECONCILE_TIMEOUT'));},45000); + child.stdout.on('data', chunk=>{stdout+=chunk; if(stdout.length>1024*1024)child.kill('SIGKILL');});child.stderr.resume(); + child.on('error',()=>{clearTimeout(timer);reject(new Error('KUBERNETES_RECONCILE_FAILED'));}); + child.on('close',code=>{clearTimeout(timer);code===0?resolve(stdout):reject(new Error('KUBERNETES_RECONCILE_FAILED'));}); + }); +} + +export async function reconcileRunJobs(config, request, execute = lifecycleCommand) { + const { resources }=renderRunResources(config,request); + const labels=resources[0].metadata.labels; + const selector=`app.kubernetes.io/managed-by=wishforge-provisioner,wishforge.io/run=${labels['wishforge.io/run']},wishforge.io/component=runner`; + const listed=JSON.parse(await execute(config,['get','jobs','-l',selector,'-o','json'])); + if(!Array.isArray(listed.items))throw new Error('KUBERNETES_RECONCILE_FAILED'); + let terminal=false; + for(const job of listed.items){ + if(job.metadata?.namespace!==config.namespace || job.metadata?.labels?.['app.kubernetes.io/managed-by']!=='wishforge-provisioner' || job.metadata?.labels?.['wishforge.io/run']!==labels['wishforge.io/run'] || !/^wf-[a-f0-9]{24}-(executor|verifier)$/.test(job.metadata?.name??''))throw new Error('KUBERNETES_RECONCILE_SCOPE_MISMATCH'); + if(job.metadata.labels['wishforge.io/generation']===labels['wishforge.io/generation']){ + if(job.status?.failed>0 || job.status?.succeeded>0 || job.status?.conditions?.some(c=>['Failed','Complete'].includes(c.type)&&c.status==='True'))terminal=true; + } else await execute(config,['delete','job',job.metadata.name,'--cascade=foreground','--wait=true','--timeout=30s']); + } + return {terminal}; +} + +export async function provisionRun(config, request, apply = runKubectl, reconcile = reconcileRunJobs) { + const rendered = renderRunResources(config, request); + const state = await reconcile(config, request); + if(state.terminal) return { ...rendered.receipt, status:'failed', reason:'Run generation has terminal jobs; resume with a new generation' }; + // Provision policy and identities before Jobs. An interrupted call is retried + // with the same deterministic resource names, never with a second workload. + await apply(config, rendered.resources.filter(resource => resource.kind !== 'Job')); + await apply(config, rendered.resources.filter(resource => resource.kind === 'Job')); + return rendered.receipt; +} diff --git a/apps/ide/provisioner/resource-grants.mjs b/apps/ide/provisioner/resource-grants.mjs new file mode 100644 index 0000000..1143e15 --- /dev/null +++ b/apps/ide/provisioner/resource-grants.mjs @@ -0,0 +1,15 @@ +import { createHmac, timingSafeEqual } from 'node:crypto'; +const fields = ['schemaVersion','tenantId','runId','generation','planId','planVersion','image','cpuMilli','memoryMiB','storageMiB','issuedAt','expiresAt']; +export function resourceGrantPayload(grant) { return JSON.stringify(Object.fromEntries(fields.map(name => [name, grant[name]]))); } +export function verifyResourceGrant(config, request, { allowExpired = false, allowRetiredImage = false, cleanup = false } = {}) { + const grant = request.resourceGrant; + if (!config.resourceGrantSecret || config.resourceGrantSecret.length < 32 || !grant || Object.keys(grant).some(key => ![...fields,'signature'].includes(key))) throw new Error('RESOURCE_GRANT_INVALID'); + const expected = createHmac('sha256', config.resourceGrantSecret).update(resourceGrantPayload(grant)).digest('base64url'); + const supplied = typeof grant.signature === 'string' ? Buffer.from(grant.signature) : Buffer.alloc(0), signature = Buffer.from(expected); + if (supplied.length !== signature.length || !timingSafeEqual(supplied,signature) || grant.schemaVersion !== 1 || grant.tenantId !== request.tenantId || request.tenantId !== config.tenantId || grant.runId !== request.runId || grant.generation !== request.generation) throw new Error('RESOURCE_GRANT_INVALID'); + const now = Math.floor(Date.now()/1000); + if (!Number.isSafeInteger(grant.issuedAt) || !Number.isSafeInteger(grant.expiresAt) || grant.issuedAt > now + 30 || grant.expiresAt <= grant.issuedAt || grant.expiresAt - grant.issuedAt > 300 || (!allowExpired && grant.expiresAt <= now)) throw new Error('RESOURCE_GRANT_EXPIRED'); + if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]*@sha256:[a-f0-9]{64}$/.test(grant.image) || (!allowRetiredImage && ![config.image, ...(config.previousImages ?? [])].includes(grant.image))) throw new Error('RUNTIME_IMAGE_MIGRATION_REQUIRED'); + for (const [field, maximum, minimum] of [['cpuMilli',config.cpuMilliCap??2000,100],['memoryMiB',config.memoryMiBCap??4096,512],['storageMiB',Number.parseInt(config.storageSize,10)*1024,128]]) if (!Number.isSafeInteger(grant[field]) || grant[field] < minimum || (!cleanup && grant[field] > maximum)) throw new Error('RESOURCE_LIMIT'); + return grant; +} diff --git a/apps/ide/provisioner/run-operations.mjs b/apps/ide/provisioner/run-operations.mjs new file mode 100644 index 0000000..3946a5d --- /dev/null +++ b/apps/ide/provisioner/run-operations.mjs @@ -0,0 +1,12 @@ +/** Serialize provision/cleanup for a run across generations in this provisioner process. */ +export function createRunOperationQueue() { + const pending = new Map(); + return async function runOperation(tenantId, runId, operation) { + const key = `${tenantId}\0${runId}`; + const previous = pending.get(key) ?? Promise.resolve(); + const current = previous.catch(() => {}).then(operation); + pending.set(key, current); + try { return await current; } + finally { if (pending.get(key) === current) pending.delete(key); } + }; +} diff --git a/apps/ide/provisioner/run-release.mjs b/apps/ide/provisioner/run-release.mjs new file mode 100644 index 0000000..909b896 --- /dev/null +++ b/apps/ide/provisioner/run-release.mjs @@ -0,0 +1,17 @@ +import { createHash } from 'node:crypto'; +import { verifyResourceGrant } from './resource-grants.mjs'; +import { lifecycleCommand } from './provisioner.mjs'; +/** Stops only matching compute Jobs; PVCs are retained and never called free storage. */ +export async function releaseRun(config, request, execute = lifecycleCommand) { + if (!request || Object.keys(request).some(key=>!['tenantId','runId','generation','resourceGrant'].includes(key)) || !/^[A-Za-z0-9_-]{1,128}$/.test(request.runId??'') || !/^[A-Za-z0-9_-]{1,128}$/.test(request.generation??'')) throw new Error('RESOURCE_GRANT_INVALID'); + verifyResourceGrant(config,request,{allowExpired:true,allowRetiredImage:true,cleanup:true}); + const run = createHash('sha256').update(`${request.tenantId}\0${request.runId}`).digest('hex').slice(0,24), generation = createHash('sha256').update(request.generation).digest('hex').slice(0,24); + const prefix = `wf-${createHash('sha256').update(`${request.tenantId}\0${request.runId}\0${request.generation}`).digest('hex').slice(0,24)}`; + const selector=`app.kubernetes.io/managed-by=wishforge-provisioner,wishforge.io/run=${run},wishforge.io/generation=${generation},wishforge.io/component=runner`; + const assertScope = value => { if(value.metadata?.namespace!==config.namespace || value.metadata?.labels?.['app.kubernetes.io/managed-by']!=='wishforge-provisioner' || value.metadata?.labels?.['wishforge.io/component']!=='runner' || value.metadata?.labels?.['wishforge.io/run']!==run || value.metadata?.labels?.['wishforge.io/generation']!==generation)throw new Error('KUBERNETES_RELEASE_SCOPE_MISMATCH'); }; + const jobs=JSON.parse(await execute(config,['get','jobs','-l',selector,'-o','json']));if(!Array.isArray(jobs.items))throw new Error('KUBERNETES_RELEASE_INVALID'); + for(const job of jobs.items){assertScope(job);if(![`${prefix}-executor`,`${prefix}-verifier`].includes(job.metadata.name))throw new Error('KUBERNETES_RELEASE_SCOPE_MISMATCH');await execute(config,['delete','job',job.metadata.name,'--ignore-not-found=true','--cascade=foreground','--wait=true','--timeout=30s']);} + const pods=JSON.parse(await execute(config,['get','pods','-l',selector,'-o','json']));if(!Array.isArray(pods.items))throw new Error('KUBERNETES_RELEASE_INVALID');for(const pod of pods.items)assertScope(pod); + const active=pods.items.some(pod=>!['Succeeded','Failed'].includes(pod.status?.phase)); + return {tenantId:request.tenantId,runId:request.runId,generation:request.generation,status:active?'releasing':'released',computeReleased:!active,persistentStorageRetained:true}; +} diff --git a/apps/ide/provisioner/test/provisioner.test.mjs b/apps/ide/provisioner/test/provisioner.test.mjs new file mode 100644 index 0000000..32522e1 --- /dev/null +++ b/apps/ide/provisioner/test/provisioner.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHmac } from 'node:crypto'; +import { readConfig, renderRunResources, provisionRun, reconcileRunJobs } from '../provisioner.mjs'; +import { resourceGrantPayload } from '../resource-grants.mjs'; +import { releaseRun } from '../run-release.mjs'; +import { createRunOperationQueue } from '../run-operations.mjs'; + +const env = { WF_TENANT_ID: 'tenant-a', WF_KUBE_CONTEXT: 'explicit-test-context', WF_KUBE_NAMESPACE: 'wishforge-tenant-a', WF_RUN_WORKER_IMAGE: `registry.example.invalid/worker@sha256:${'a'.repeat(64)}`, WF_RUN_STORAGE_CLASS: 'reviewed-rwx', WF_CONTROL_PLANE_URL: 'https://api.wishforge-control.svc:8443', WF_CONTROL_NAMESPACE: 'wishforge-control', TEMPORAL_ADDRESS: 'temporal.wishforge-control.svc:7233', TEMPORAL_NAMESPACE: 'wishforge' }; +env.WF_RESOURCE_GRANT_SECRET = 'test-only-resource-signing-secret-longer-than-32'; +const config = readConfig(env); +function grant(overrides={}) { + const issuedAt=Math.floor(Date.now()/1000); + const payload={schemaVersion:1,tenantId:'tenant-a',runId:'run-123',generation:'generation-1',planId:'pilot',planVersion:'pilot-v1',image:config.image,cpuMilli:1500,memoryMiB:3072,storageMiB:8192,issuedAt,expiresAt:issuedAt+300,...overrides}; + return {...payload,signature:createHmac('sha256',env.WF_RESOURCE_GRANT_SECRET).update(resourceGrantPayload(payload)).digest('base64url')}; +} +function token(kind, run = 'run-123') { return `header.${Buffer.from(JSON.stringify({ tenant_id: 'tenant-a', run_id: run, generation: 'generation-1', kind, iss: 'wishforge-control-plane', aud: 'wishforge-internal', exp: Math.floor(Date.now() / 1000) + 14400 })).toString('base64url')}.signature`; } +const request = { tenantId: 'tenant-a', runId: 'run-123', generation: 'generation-1', executorToken: token('worker'), verifierToken: token('verifier'), resourceGrant:grant() }; + +test('fails closed without explicit cluster, namespace, image digest and storage', () => { + assert.throws(() => readConfig({}), /unconfigured/); + assert.throws(() => readConfig({ ...env, WF_RUN_WORKER_IMAGE: 'worker:latest' }), /immutable/); + assert.throws(() => renderRunResources(config, { ...request, tenantId: 'tenant-b' }), /outside/); + assert.throws(() => renderRunResources(config, { ...request, executorToken: token('worker', 'other-run') }), /token/); +}); + +test('renders independent Kata jobs with role-scoped credentials and separate role PVCs', () => { + const { resources } = renderRunResources(config, request); + const jobs = resources.filter(r => r.kind === 'Job'); assert.equal(jobs.length, 2); + assert.notEqual(jobs[0].spec.template.spec.serviceAccountName, jobs[1].spec.template.spec.serviceAccountName); + for (const job of jobs) { + const pod = job.spec.template.spec, container = pod.containers[0]; + assert.equal(pod.runtimeClassName, 'wishforge-kata'); assert.equal(pod.automountServiceAccountToken, false); + assert.equal(container.securityContext.allowPrivilegeEscalation, false); assert.equal(container.securityContext.readOnlyRootFilesystem, true); + assert.deepEqual(container.securityContext.capabilities.drop, ['ALL']); + assert.ok(!pod.hostNetwork && !pod.hostPID && !pod.hostIPC); + assert.ok(pod.volumes.every(v => !v.hostPath)); + assert.ok(!JSON.stringify(pod).includes('docker.sock')); + assert.equal(container.env.filter(e => /TOKEN$/.test(e.name)).length, 1); + assert.ok(container.env.find(e => /TOKEN$/.test(e.name)).valueFrom.secretKeyRef); + assert.ok(!JSON.stringify(pod).includes(request.executorToken)); assert.ok(!JSON.stringify(pod).includes(request.verifierToken)); + assert.equal(container.image,request.resourceGrant.image); + assert.equal(container.resources.limits.cpu,'750m');assert.equal(container.resources.limits.memory,'1536Mi'); + } + const pvc = resources.filter(r => r.kind === 'PersistentVolumeClaim'); assert.equal(pvc.length, 2); assert.ok(pvc.every(claim => claim.spec.accessModes[0] === 'ReadWriteOnce')); + assert.notEqual(jobs[0].spec.template.spec.volumes[0].persistentVolumeClaim.claimName, jobs[1].spec.template.spec.volumes[0].persistentVolumeClaim.claimName); + const policy = resources.find(r => r.kind === 'NetworkPolicy'); assert.deepEqual(policy.spec.ingress, []); + assert.ok(policy.spec.egress.every(rule => rule.to.every(to => to.namespaceSelector && to.podSelector && !to.ipBlock))); + assert.ok(pvc.every(claim=>claim.spec.resources.requests.storage==='4096Mi')); + assert.ok(jobs.reduce((total,job)=>total+parseInt(job.spec.template.spec.containers[0].resources.limits.cpu),0)<=request.resourceGrant.cpuMilli); + assert.ok(jobs.reduce((total,job)=>total+parseInt(job.spec.template.spec.containers[0].resources.limits.memory),0)<=request.resourceGrant.memoryMiB); + assert.ok(pvc.reduce((total,claim)=>total+parseInt(claim.spec.resources.requests.storage),0)<=request.resourceGrant.storageMiB); + const other = renderRunResources(config, { ...request, runId: 'run-456', executorToken: token('worker', 'run-456'), verifierToken: token('verifier', 'run-456'),resourceGrant:grant({runId:'run-456'}) }); + assert.notEqual(other.receipt.workspaceClaim, pvc[0].metadata.name); +}); + +test('rejects tampered, expired, wrong-scope and above-cap resource grants',()=>{ + for(const change of [{cpuMilli:1600},{generation:'other'},{tenantId:'other'}])assert.throws(()=>renderRunResources(config,{...request,resourceGrant:{...request.resourceGrant,...change}}),/RESOURCE_GRANT_INVALID/); + assert.throws(()=>renderRunResources(config,{...request,resourceGrant:grant({runId:'other'})}),/RESOURCE_GRANT_INVALID/); + assert.throws(()=>renderRunResources(config,{...request,resourceGrant:grant({issuedAt:1,expiresAt:301})}),/RESOURCE_GRANT_EXPIRED/); + for(const change of [{cpuMilli:2001},{memoryMiB:4097},{storageMiB:10241}])assert.throws(()=>renderRunResources(config,{...request,resourceGrant:grant(change)}),/RESOURCE_LIMIT/); +}); + +test('pins signed previous runtime image and requires migration after its retirement',()=>{ + const previous=`registry.example.invalid/worker@sha256:${'b'.repeat(64)}`; + const requestWithPrevious={...request,resourceGrant:grant({image:previous})}; + const configured=readConfig({...env,WF_RUN_PREVIOUS_IMAGES:previous}); + assert.ok(renderRunResources(configured,requestWithPrevious).resources.filter(r=>r.kind==='Job').every(r=>r.spec.template.spec.containers[0].image===previous)); + assert.throws(()=>renderRunResources(config,requestWithPrevious),/RUNTIME_IMAGE_MIGRATION_REQUIRED/); +}); + +test('cleanup verifies ownership, stops matching jobs, retains PVCs and never fabricates measurement',async()=>{ + const {resources}=renderRunResources(config,request);const job=resources.find(r=>r.kind==='Job');const calls=[]; + const release={tenantId:request.tenantId,runId:request.runId,generation:request.generation,resourceGrant:grant({issuedAt:1,expiresAt:301,image:`registry.example.invalid/retired@sha256:${'c'.repeat(64)}`})}; + const execute=async(_config,args)=>{calls.push(args);return args[0]==='get'?JSON.stringify({items:args[1]==='jobs'?[job]:[]}):'';}; + const receipt=await releaseRun(config,release,execute); + assert.equal(receipt.status,'released');assert.equal(receipt.computeReleased,true);assert.equal(receipt.persistentStorageRetained,true); + assert.equal(receipt.computeSeconds,undefined);assert.ok(calls.every(args=>!args.includes('pvc'))); + assert.equal(calls.filter(args=>args[0]==='delete').length,1); + await assert.rejects(releaseRun(config,release,async()=>JSON.stringify({items:[{...job,metadata:{...job.metadata,namespace:'other'}}]})),/SCOPE_MISMATCH/); + const pending=await releaseRun(config,release,async(_config,args)=>JSON.stringify({items:args[1]==='pods'?[{metadata:job.metadata,status:{phase:'Running'}}]:[]})); + assert.equal(pending.status,'releasing');assert.equal(pending.computeReleased,false); +}); + +test('serializes delayed provision with cleanup while allowing independent runs',async()=>{ + const queue=createRunOperationQueue(),order=[];let resolve; + const first=queue('tenant-a','run-1',async()=>{order.push('provision');await new Promise(r=>{resolve=r;});order.push('provisioned');}); + await Promise.resolve(); + const cleanup=queue('tenant-a','run-1',async()=>{order.push('cleanup');}); + await queue('tenant-a','run-2',async()=>{order.push('independent');}); + assert.deepEqual(order,['provision','independent']);resolve();await Promise.all([first,cleanup]);assert.deepEqual(order,['provision','independent','provisioned','cleanup']); + await assert.rejects(queue('tenant-a','run-1',async()=>{throw new Error('fixture');}),/fixture/); + assert.equal(await queue('tenant-a','run-1',async()=> 'reconciled'),'reconciled'); +}); + +test('applies policy before jobs, retries deterministic names and propagates infrastructure failure', async () => { + const calls = []; const apply = async (cfg, resources) => { assert.equal(cfg.context, 'explicit-test-context'); calls.push(resources); }; + const first = await provisionRun(config, request, apply, async () => ({terminal:false})); const second = await provisionRun(config, request, apply, async () => ({terminal:false})); + assert.deepEqual(first, second); assert.equal(calls.length, 4); + assert.ok(calls[0].every(r => r.kind !== 'Job')); assert.ok(calls[1].every(r => r.kind === 'Job')); + await assert.rejects(provisionRun(config, request, async () => { throw new Error('KUBERNETES_APPLY_FAILED'); }, async () => ({terminal:false})), /KUBERNETES_APPLY_FAILED/); +}); + +test('reconciles only old owned run jobs and refuses to pretend a terminal generation resumed', async () => { + const {resources}=renderRunResources(config,request); + const job=resources.find(r=>r.kind==='Job');const calls=[]; + const old={...job,metadata:{...job.metadata,labels:{...job.metadata.labels,'wishforge.io/generation':'old-generation'}}}; + const execute=async(cfg,args)=>{calls.push(args);return args[0]==='get'?JSON.stringify({items:[old]}):'';}; + assert.deepEqual(await reconcileRunJobs(config,request,execute),{terminal:false}); + assert.deepEqual(calls[1],['delete','job',job.metadata.name,'--cascade=foreground','--wait=true','--timeout=30s']); + const terminal=await reconcileRunJobs(config,request,async()=>JSON.stringify({items:[{...job,status:{failed:1}}]})); + assert.equal(terminal.terminal,true); + let applied=false; + const response=await provisionRun(config,request,async()=>{applied=true;},async()=>terminal); + assert.equal(response.status,'failed');assert.equal(applied,false); + await assert.rejects(reconcileRunJobs(config,request,async()=>JSON.stringify({items:[{...old,metadata:{...old.metadata,namespace:'other-tenant'}}]})),/SCOPE/); +}); diff --git a/apps/ide/provisioner/test/workspace-lifecycle.test.mjs b/apps/ide/provisioner/test/workspace-lifecycle.test.mjs new file mode 100644 index 0000000..d24dc2a --- /dev/null +++ b/apps/ide/provisioner/test/workspace-lifecycle.test.mjs @@ -0,0 +1,10 @@ +import test from 'node:test';import assert from 'node:assert/strict'; +import {renderWorkspaceResources} from '../workspaces.mjs'; +import {observeWorkspaceLifecycle,reconcileWorkspaceLifecycle} from '../workspace-lifecycle.mjs'; +const config={tenantId:'alpha',namespace:'wf-alpha',context:'fixture',controlNamespace:'wf-control',runtimeClass:'kata',storageClass:'fixture',storageSize:'10Gi'}; +const input={tenantId:'alpha',projectId:'project',workspaceId:'workspace'}; +function fixture(){const rendered=renderWorkspaceResources(config,input,`registry.example/theia@sha256:${'a'.repeat(64)}`);const d=rendered.resources.find(r=>r.kind==='Deployment');d.metadata.uid='immutable-uid';d.metadata.resourceVersion='1';d.metadata.generation=1;d.status={observedGeneration:1,availableReplicas:1,updatedReplicas:1,replicas:1};let pods=[];let lose=false;const calls=[];const execute=async(_config,args)=>{calls.push(args);if(args[0]==='get'&&args[1]==='pods')return{items:pods};if(args[0]==='get')return structuredClone(d);assert.equal(args[0],'patch');assert.equal(args[1],'deployment');assert.equal(args[2],rendered.name);const patch=JSON.parse(args[args.indexOf('-p')+1]);assert.equal(patch[0].value,d.metadata.resourceVersion);assert.equal(patch[1].value,d.metadata.uid);d.metadata.annotations=patch[2].value;d.spec.replicas=patch[3].value;d.metadata.resourceVersion=String(Number(d.metadata.resourceVersion)+1);d.metadata.generation++;if(lose)throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');return structuredClone(d);};return{d,calls,execute,setPods:value=>{pods=value;},lose:()=>{lose=true;},converge:()=>{d.status={observedGeneration:d.metadata.generation,replicas:d.spec.replicas,availableReplicas:d.spec.replicas,updatedReplicas:d.spec.replicas};}};} +test('pause only patches the owned IDE deployment, retains all PVCs, and waits for observed termination',async()=>{const f=fixture();const request={...input,revision:1,desired:'paused'};assert.equal((await reconcileWorkspaceLifecycle(config,request,{execute:f.execute})).status,'pending');f.converge();f.setPods([{status:{phase:'Running'},metadata:{deletionTimestamp:new Date().toISOString()}}]);assert.equal((await observeWorkspaceLifecycle(config,input,{execute:f.execute})).status,'pending');f.setPods([]);assert.equal((await observeWorkspaceLifecycle(config,input,{execute:f.execute})).status,'paused');assert.ok(f.calls.every(args=>!args.includes('pvc')&&!args.includes('delete')&&!args.includes('service')));}); +test('resume does not claim ready until updated and available replica is observed',async()=>{const f=fixture();await reconcileWorkspaceLifecycle(config,{...input,revision:1,desired:'paused'},{execute:f.execute});f.converge();assert.equal((await reconcileWorkspaceLifecycle(config,{...input,revision:2,desired:'running'},{execute:f.execute})).status,'pending');f.converge();assert.equal((await observeWorkspaceLifecycle(config,input,{execute:f.execute})).status,'ready');}); +test('lost mutation response reconciles by observation and does not send a duplicate patch',async()=>{const f=fixture();f.lose();const request={...input,revision:1,desired:'paused'};await assert.rejects(reconcileWorkspaceLifecycle(config,request,{execute:f.execute}),/UNKNOWN/);f.converge();assert.equal((await reconcileWorkspaceLifecycle(config,request,{execute:f.execute})).status,'paused');assert.equal(f.calls.filter(a=>a[0]==='patch').length,1);}); +test('tenant, namespace, managed labels and revision fencing reject without mutations',async()=>{const f=fixture();await assert.rejects(reconcileWorkspaceLifecycle(config,{...input,tenantId:'other',revision:1,desired:'paused'},{execute:f.execute}),/SCOPE/);f.d.metadata.labels['wishforge.io/component']='production-app';await assert.rejects(reconcileWorkspaceLifecycle(config,{...input,revision:1,desired:'paused'},{execute:f.execute}),/OWNERSHIP/);f.d.metadata.labels['wishforge.io/component']='ide';f.d.metadata.namespace='production';await assert.rejects(reconcileWorkspaceLifecycle(config,{...input,revision:1,desired:'paused'},{execute:f.execute}),/OWNERSHIP/);f.d.metadata.namespace=config.namespace;f.d.metadata.annotations={'wishforge.io/lifecycle-revision':'3','wishforge.io/lifecycle-desired':'running'};await assert.rejects(reconcileWorkspaceLifecycle(config,{...input,revision:2,desired:'paused'},{execute:f.execute}),/STALE/);await assert.rejects(reconcileWorkspaceLifecycle(config,{...input,revision:3,desired:'paused'},{execute:f.execute}),/CONFLICT/);assert.equal(f.calls.filter(a=>a[0]==='patch').length,0);}); diff --git a/apps/ide/provisioner/test/workspaces.test.mjs b/apps/ide/provisioner/test/workspaces.test.mjs new file mode 100644 index 0000000..98e6041 --- /dev/null +++ b/apps/ide/provisioner/test/workspaces.test.mjs @@ -0,0 +1,34 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { renderWorkspaceResources, provisionWorkspace } from '../workspaces.mjs'; +const config = { tenantId: 'alpha', namespace: 'wf-alpha', controlNamespace: 'wf-control', runtimeClass: 'wishforge-kata', storageClass: 'test-storage', storageSize: '10Gi' }; +const input = { tenantId: 'alpha', projectId: 'project-1', workspaceId: 'workspace-1' }; +const image = `registry.invalid/theia@sha256:${'a'.repeat(64)}`; +test('workspace provisioning uses the actual Theia start contract and a private isolated endpoint', () => { + const rendered = renderWorkspaceResources(config, input, image); + const pod = rendered.resources.find(r => r.kind === 'Deployment').spec.template.spec; + assert.equal(pod.runtimeClassName, 'wishforge-kata'); assert.equal(pod.automountServiceAccountToken, false); + const env = Object.fromEntries(pod.containers[0].env.map(e => [e.name, e.value])); + assert.equal(env.WISHFORGE_IDE_PORT, '3000'); assert.equal(env.WISHFORGE_GATEWAY_ENFORCED, 'true'); + assert.equal(env.WISHFORGE_WORKSPACE_PATH, '/home/theia/data/workspace'); assert.equal(env.WISHFORGE_COLLABORATION_ENABLED, 'false'); + assert.equal(rendered.resources.find(r => r.kind === 'Service').spec.type, 'ClusterIP'); +}); +test('creating manifests does not mark an unready IDE available', async () => { + let applied = false; + const result = await provisionWorkspace(config, input, { image, apply: async () => { applied = true; }, observe: async () => false }); + assert.ok(applied); assert.equal(result.status, 'pending'); + assert.throws(() => renderWorkspaceResources(config, { ...input, tenantId: 'beta' }, image)); +}); +test('scoped collaboration and coordination expose only public identity material to the workspace', () => { + const rendered = renderWorkspaceResources({...config,gatewayPublicKeyConfigMap:'gateway-public'}, input, image, {image,gatewayBase:'https://ide.example/'}); + const pod=rendered.resources.find(r=>r.kind==='Deployment').spec.template.spec; + { + assert.equal(pod.containers.length,2); + assert.ok(pod.containers[0].env.some(e=>e.name==='WF_IDE_GATEWAY_PUBLIC_KEY_FILE')); + assert.ok(!JSON.stringify(pod).includes('PRIVATE_KEY')); + assert.ok(pod.volumes.some(v=>v.name==='coordination-state')); + const octEnv=Object.fromEntries(pod.containers[1].env.map(e=>[e.name,e.value])); + assert.equal(octEnv.WF_WORKSPACE_ID,input.workspaceId);assert.equal(octEnv.WISHFORGE_GATEWAY_ENFORCED,'true'); + assert.ok(rendered.collaborationUpstreamUrl.endsWith(':8100')); + } +}); diff --git a/apps/ide/provisioner/workspace-lifecycle.mjs b/apps/ide/provisioner/workspace-lifecycle.mjs new file mode 100644 index 0000000..138c731 --- /dev/null +++ b/apps/ide/provisioner/workspace-lifecycle.mjs @@ -0,0 +1,10 @@ +import { createHash } from 'node:crypto'; +import { spawn } from 'node:child_process'; +const id=/^[a-zA-Z0-9_-]{1,128}$/; +const revisionKey='wishforge.io/lifecycle-revision'; +const desiredKey='wishforge.io/lifecycle-desired'; +function scope(config,input){if(!input||input.tenantId!==config.tenantId||!id.test(input.projectId??'')||!id.test(input.workspaceId??''))throw new Error('INVALID_WORKSPACE_SCOPE');return `wf-ide-${createHash('sha256').update(`${input.tenantId}/${input.workspaceId}`).digest('hex').slice(0,24)}`;} +function assertOwned(config,name,value){if(value?.metadata?.name!==name||value.metadata.namespace!==config.namespace||value.metadata.labels?.['app.kubernetes.io/managed-by']!=='wishforge-provisioner'||value.metadata.labels?.['wishforge.io/component']!=='ide'||value.metadata.labels?.['wishforge.io/workspace']!==name)throw new Error('WORKSPACE_OWNERSHIP_MISMATCH');} +export function kubectlJson(config,args){return new Promise((resolve,reject)=>{const child=spawn('kubectl',['--context',config.context,'--namespace',config.namespace,...args],{stdio:['ignore','pipe','pipe']});let output='';let settled=false;const fail=()=>{if(!settled){settled=true;reject(new Error('KUBERNETES_LIFECYCLE_UNKNOWN'));}};const timeout=setTimeout(()=>{child.kill('SIGTERM');fail();},10000);child.stdout.on('data',part=>{output+=part;if(output.length>2*1024*1024){child.kill('SIGTERM');fail();}});child.stderr.resume();child.on('error',fail);child.on('close',code=>{clearTimeout(timeout);if(settled)return;try{if(code!==0)throw Error();const value=JSON.parse(output);settled=true;resolve(value);}catch{fail();}});});} +export async function observeWorkspaceLifecycle(config,input,options={}){const name=scope(config,input);const execute=options.execute??kubectlJson;const deployment=await execute(config,['get','deployment',name,'-o','json']);assertOwned(config,name,deployment);const revision=Number(deployment.metadata.annotations?.[revisionKey]??0);const desired=deployment.metadata.annotations?.[desiredKey]??'running';if(!Number.isSafeInteger(revision)||revision<0||!['running','paused'].includes(desired))throw new Error('INVALID_WORKSPACE_LIFECYCLE_STATE');let status='pending';const observed=deployment.status?.observedGeneration>=deployment.metadata.generation;if(desired==='running'&&deployment.spec?.replicas===1&&observed&&deployment.status.availableReplicas===1&&deployment.status.updatedReplicas===1)status='ready';if(desired==='paused'&&deployment.spec?.replicas===0&&observed&&(deployment.status.replicas??0)===0){const selector=`wishforge.io/workspace=${name},wishforge.io/component=ide,app.kubernetes.io/managed-by=wishforge-provisioner`;const pods=await execute(config,['get','pods','--selector',selector,'-o','json']);if(!Array.isArray(pods.items))throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');if(pods.items.every(p=>['Succeeded','Failed'].includes(p.status?.phase)))status='paused';}return{workspaceId:input.workspaceId,revision,desired,status,deploymentUid:deployment.metadata.uid,resourceVersion:deployment.metadata.resourceVersion};} +export async function reconcileWorkspaceLifecycle(config,input,options={}){if(!['running','paused'].includes(input?.desired)||!Number.isSafeInteger(input.revision)||input.revision<1||Object.keys(input).some(k=>!['tenantId','projectId','workspaceId','revision','desired'].includes(k)))throw new Error('INVALID_WORKSPACE_LIFECYCLE_REQUEST');const execute=options.execute??kubectlJson;const name=scope(config,input);const deployment=await execute(config,['get','deployment',name,'-o','json']);assertOwned(config,name,deployment);const previous=Number(deployment.metadata.annotations?.[revisionKey]??0);if(!Number.isSafeInteger(previous)||previous>input.revision)throw new Error('STALE_WORKSPACE_REVISION');if(previous===input.revision){if(deployment.metadata.annotations?.[desiredKey]!==input.desired)throw new Error('WORKSPACE_REVISION_CONFLICT');return observeWorkspaceLifecycle(config,input,{execute});}if(!deployment.metadata.resourceVersion||!deployment.metadata.uid)throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');const annotations={...deployment.metadata.annotations,[revisionKey]:String(input.revision),[desiredKey]:input.desired};const patch=[{op:'test',path:'/metadata/resourceVersion',value:deployment.metadata.resourceVersion},{op:'test',path:'/metadata/uid',value:deployment.metadata.uid},{op:'add',path:'/metadata/annotations',value:annotations},{op:'replace',path:'/spec/replicas',value:input.desired==='paused'?0:1}];await execute(config,['patch','deployment',name,'--type=json','-p',JSON.stringify(patch),'-o','json']);return observeWorkspaceLifecycle(config,input,{execute});} diff --git a/apps/ide/provisioner/workspaces.mjs b/apps/ide/provisioner/workspaces.mjs new file mode 100644 index 0000000..2acc471 --- /dev/null +++ b/apps/ide/provisioner/workspaces.mjs @@ -0,0 +1,59 @@ +import { createHash } from 'node:crypto'; +import { spawn } from 'node:child_process'; +import { runKubectl } from './provisioner.mjs'; +const safe = /^[a-zA-Z0-9_-]{1,128}$/; + +export function renderWorkspaceResources(config, input, image, collaboration) { + if (!image || !/^[^\s]+@sha256:[a-f0-9]{64}$/.test(image)) throw new Error('UNCONFIGURED_THEIA_IMAGE'); + if (!input || input.tenantId !== config.tenantId || !safe.test(input.projectId ?? '') || !safe.test(input.workspaceId ?? '') || Object.keys(input).some(k => !['tenantId', 'projectId', 'workspaceId'].includes(k))) throw new Error('INVALID_WORKSPACE_REQUEST'); + const name = `wf-ide-${createHash('sha256').update(`${input.tenantId}/${input.workspaceId}`).digest('hex').slice(0, 24)}`; + const labels = { 'wishforge.io/component': 'ide', 'wishforge.io/workspace': name, 'app.kubernetes.io/managed-by': 'wishforge-provisioner' }; + const metadata = n => ({ name: n, namespace: config.namespace, labels }); + const resources = [ + { apiVersion: 'v1', kind: 'PersistentVolumeClaim', metadata: metadata(name), spec: { storageClassName: config.storageClass, accessModes: ['ReadWriteOnce'], resources: { requests: { storage: config.storageSize } } } }, + { apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata: metadata(`${name}-isolation`), spec: { podSelector: { matchLabels: { 'wishforge.io/workspace': name } }, policyTypes: ['Ingress', 'Egress'], ingress: [{ from: [{ namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': config.controlNamespace } }, podSelector: { matchLabels: { 'wishforge.io/component': 'workspace-gateway' } } }], ports: [{ protocol: 'TCP', port: 3000 }] }], egress: [{ to: [{ namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': 'kube-system' } }, podSelector: { matchLabels: { 'k8s-app': 'kube-dns' } } }], ports: [{ protocol: 'UDP', port: 53 }, { protocol: 'TCP', port: 53 }] }] } }, + { apiVersion: 'apps/v1', kind: 'Deployment', metadata: metadata(name), spec: { replicas: 1, strategy: { type: 'Recreate' }, selector: { matchLabels: { 'wishforge.io/workspace': name } }, template: { metadata: { labels }, spec: { runtimeClassName: config.runtimeClass, automountServiceAccountToken: false, securityContext: { runAsNonRoot: true, runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000, seccompProfile: { type: 'RuntimeDefault' } }, initContainers: [{ name: 'workspace-directories', image, command: ['node', '-e', "const fs=require('fs');for(const dir of ['workspace','config'])fs.mkdirSync('/home/theia/data/'+dir,{recursive:true});"], securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } }, volumeMounts: [{ name: 'workspace', mountPath: '/home/theia/data' }] }], containers: [{ name: 'theia', image, ports: [{ containerPort: 3000 }], env: [{ name: 'NODE_ENV', value: 'production' }, { name: 'WISHFORGE_GATEWAY_ENFORCED', value: 'true' }, { name: 'WISHFORGE_WORKSPACE_PATH', value: '/home/theia/data/workspace' }, { name: 'THEIA_CONFIG_DIR', value: '/home/theia/data/config' }, { name: 'WISHFORGE_IDE_HOST', value: '0.0.0.0' }, { name: 'WISHFORGE_IDE_PORT', value: '3000' }, { name: 'WISHFORGE_COLLABORATION_ENABLED', value: 'false' }, { name: 'COLLABORATION_SERVER_URL', value: 'https://disabled.invalid/' }], resources: { requests: { cpu: '500m', memory: '1Gi' }, limits: { cpu: '2', memory: '4Gi' } }, securityContext: { allowPrivilegeEscalation: false, capabilities: { drop: ['ALL'] } }, readinessProbe: { httpGet: { path: '/', port: 3000 }, initialDelaySeconds: 10, periodSeconds: 5 }, volumeMounts: [{ name: 'workspace', mountPath: '/home/theia/data' }] }], volumes: [{ name: 'workspace', persistentVolumeClaim: { claimName: name } }] } } } }, + { apiVersion: 'v1', kind: 'Service', metadata: metadata(name), spec: { selector: { 'wishforge.io/workspace': name }, type: 'ClusterIP', ports: [{ port: 3000, targetPort: 3000 }] } }, + ]; + const workspacePod = resources.find(r => r.kind === 'Deployment').spec.template.spec; + workspacePod.containers[0].securityContext.readOnlyRootFilesystem = true; + workspacePod.containers[0].env.push({ name: 'HOME', value: '/home/theia/data' }, { name: 'WF_TENANT_ID', value: input.tenantId }, { name: 'WF_WORKSPACE_ID', value: input.workspaceId }); + workspacePod.volumes.push({ name: 'temporary', emptyDir: { sizeLimit: '2Gi' } }); + workspacePod.containers[0].volumeMounts.push({ name: 'temporary', mountPath: '/tmp' }); + if (config.gatewayPublicKeyConfigMap) { + if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(config.gatewayPublicKeyConfigMap) || config.gatewayPublicKeyConfigMap.length > 63) throw new Error('INVALID_GATEWAY_PUBLIC_KEY_CONFIGMAP'); + resources.unshift({ apiVersion:'v1',kind:'PersistentVolumeClaim',metadata:metadata(`${name}-state`),spec:{storageClassName:config.storageClass,accessModes:['ReadWriteOnce'],resources:{requests:{storage:'1Gi'}}} }); + workspacePod.volumes.push({ name:'coordination-state',persistentVolumeClaim:{claimName:`${name}-state`} },{ name:'gateway-public-key',configMap:{name:config.gatewayPublicKeyConfigMap,items:[{key:'public.pem',path:'public.pem'}]} }); + workspacePod.containers[0].volumeMounts.push({name:'coordination-state',mountPath:'/var/lib/wishforge-coordination'},{name:'gateway-public-key',mountPath:'/run/wishforge-identity',readOnly:true}); + workspacePod.containers[0].env.push({name:'WF_COORDINATION_STATE_DIR',value:'/var/lib/wishforge-coordination'},{name:'WF_IDE_GATEWAY_PUBLIC_KEY_FILE',value:'/run/wishforge-identity/public.pem'}); + } + let collaborationUpstreamUrl; + if (collaboration) { + if (!/^[^\s]+@sha256:[a-f0-9]{64}$/.test(collaboration.image ?? '')) throw new Error('UNCONFIGURED_OCT_WORKSPACE_IMAGE'); + const gateway = new URL(collaboration.gatewayBase); + if (gateway.protocol !== 'https:' || gateway.username || gateway.password || gateway.pathname !== '/' || gateway.search || gateway.hash) throw new Error('INVALID_PUBLIC_WORKSPACE_GATEWAY'); + const pod = resources.find(r => r.kind === 'Deployment').spec.template.spec; + pod.containers[0].env.push({ name: 'WF_COLLABORATION_GATEWAY_URL', value: `${gateway.origin}/workspaces/${input.workspaceId}/collaboration/` }); + pod.containers.push({ name: 'collaboration', image: collaboration.image, env: [{name:'WF_TENANT_ID',value:input.tenantId},{name:'WF_WORKSPACE_ID',value:input.workspaceId},{name:'WISHFORGE_GATEWAY_ENFORCED',value:'true'}], ports: [{ containerPort: 8100 }], resources: { requests: { cpu: '100m', memory: '128Mi' }, limits: { cpu: '500m', memory: '512Mi' } }, securityContext: { allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: { drop: ['ALL'] } }, readinessProbe: { httpGet: { path: '/api/meta', port: 8100 }, initialDelaySeconds: 3, periodSeconds: 5 } }); + resources.find(r => r.kind === 'Service').spec.ports = [{ name: 'theia', port: 3000, targetPort: 3000 }, { name: 'collaboration', port: 8100, targetPort: 8100 }]; + resources.find(r => r.kind === 'NetworkPolicy').spec.ingress[0].ports.push({ protocol: 'TCP', port: 8100 }); + collaborationUpstreamUrl = `http://${name}.${config.namespace}.svc:8100`; + } + return { name, resources, upstreamUrl: `http://${name}.${config.namespace}.svc:3000`, collaborationUpstreamUrl }; +} +async function observe(config, name) { + return new Promise((resolve, reject) => { + const child = spawn('kubectl', ['--context', config.context, '--namespace', config.namespace, 'get', 'deployment', name, '-o', 'json'], { stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; const timer = setTimeout(() => { child.kill('SIGTERM'); reject(new Error('KUBERNETES_OBSERVE_TIMEOUT')); }, 10000); + child.stderr.resume(); child.stdout.on('data', b => { stdout += b; if (stdout.length > 1000000) child.kill('SIGTERM'); }); + child.on('error', () => { clearTimeout(timer); reject(new Error('KUBERNETES_OBSERVE_FAILED')); }); + child.on('close', code => { clearTimeout(timer); try { if (code !== 0) throw new Error(); const d = JSON.parse(stdout); resolve(d.status?.observedGeneration >= d.metadata.generation && d.status?.availableReplicas === 1 && d.status?.updatedReplicas === 1); } catch { reject(new Error('KUBERNETES_OBSERVE_FAILED')); } }); + }); +} +export async function provisionWorkspace(config, input, options = {}) { + const collaboration = options.collaboration ?? (process.env.WF_OCT_WORKSPACE_IMAGE ? { image: process.env.WF_OCT_WORKSPACE_IMAGE, gatewayBase: process.env.WF_WORKSPACE_GATEWAY_BASE } : undefined); + const rendered = renderWorkspaceResources({ ...config, gatewayPublicKeyConfigMap: options.gatewayPublicKeyConfigMap ?? process.env.WF_IDE_GATEWAY_PUBLIC_KEY_CONFIGMAP }, input, options.image ?? process.env.WF_THEIA_IMAGE, collaboration); + await (options.apply ?? runKubectl)(config, rendered.resources); + const ready = await (options.observe ?? observe)(config, rendered.name); + return { status: ready ? 'ready' : 'pending', workspaceId: input.workspaceId, upstreamUrl: rendered.upstreamUrl, collaborationUpstreamUrl: rendered.collaborationUpstreamUrl }; +} diff --git a/apps/ide/scripts/catalog-builtin-plugins.mjs b/apps/ide/scripts/catalog-builtin-plugins.mjs new file mode 100644 index 0000000..4d5a87b --- /dev/null +++ b/apps/ide/scripts/catalog-builtin-plugins.mjs @@ -0,0 +1,27 @@ +// Operator-only lockfile maintenance. Input must be the exact official release +// archive; this never signs or approves an arbitrary installed runtime directory. +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +const source = { + url: 'https://github.com/eclipse-theia/vscode-builtin-extensions/releases/download/1.108.2/vscode-builtin-extensions-1.108.2.tar.gz', + sha256: '05a20cf3e671c8d328b04d9ce72b25688b0e762e4a3f5592f31a21ee38280367', +}; +if (process.argv.length !== 3) throw new Error('Usage: node scripts/catalog-builtin-plugins.mjs /path/to/vscode-builtin-extensions-1.108.2.tar.gz'); +const archive = process.argv[2]; +if (createHash('sha256').update(await readFile(archive)).digest('hex') !== source.sha256) throw new Error('BUILTIN_ARCHIVE_DIGEST_REJECTED'); +const plugins = JSON.parse(execFileSync('python3', ['-c', ` +import hashlib,io,json,pathlib,sys,tarfile,zipfile +plugins=[] +with tarfile.open(sys.argv[1],'r:gz') as tar: + for item in tar.getmembers(): + if item.isdir(): continue + if not item.isfile() or not item.name.endswith('.vsix'): raise ValueError('Unexpected release entry') + with zipfile.ZipFile(io.BytesIO(tar.extractfile(item).read())) as z: + manifest=json.loads(z.read('extension/package.json')) + files=sorted((i.filename,hashlib.sha256(z.read(i)).hexdigest()) for i in z.infolist() if not i.is_dir()) + digest=hashlib.sha256(''.join(name+'\\0'+sha+'\\n' for name,sha in files).encode()).hexdigest() + plugins.append({'directory':pathlib.PurePosixPath(item.name).stem,'id':manifest['publisher']+'.'+manifest['name'],'version':manifest['version'],'sha256':digest}) +print(json.dumps(sorted(plugins,key=lambda p:p['directory']))) +`, archive], { encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })); +console.log(JSON.stringify({ schemaVersion: 1, source, plugins }, null, 2)); diff --git a/apps/ide/scripts/download-python-debugger.mjs b/apps/ide/scripts/download-python-debugger.mjs new file mode 100644 index 0000000..ec67b9f --- /dev/null +++ b/apps/ide/scripts/download-python-debugger.mjs @@ -0,0 +1,116 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { execFile } from 'node:child_process'; +import { readFile, writeFile, mkdir, rename, rm, stat } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { promisify } from 'node:util'; + +const lock = JSON.parse(await readFile(new URL('./python-debugger.lock.json', import.meta.url), 'utf8')); +const maxBytes = 64 * 1024 * 1024; +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); +const run = promisify(execFile); + +export async function installPythonDebugger({ + platform = `${process.platform}-${process.arch}`, + archive, + pythonArchive, + pyrightArchive, + directory = fileURLToPath(new URL('../plugins/', import.meta.url)), + fetcher = fetch, +} = {}) { + const expected = lock.platforms[platform]; + if (!expected) throw new Error(`Python debugger package is not pinned for ${platform}`); + const filename = `${lock.id}-${lock.version}@${platform}.vsix`; + const dependency = lock.pythonDependency; + const python = await installArchive({ + expected: dependency.sha256, filename: `${dependency.id}-${dependency.version}.vsix`, + id: dependency.id, version: dependency.version, url: dependency.url, archive: pythonArchive, directory, fetcher, + }); + const debuggerExtension = await installArchive({ + expected, filename, archive, directory, fetcher, id: lock.id, version: lock.version, + url: `https://open-vsx.org/api/ms-python/debugpy/${platform}/${lock.version}/file/${filename}`, + }); + const languageServer = await installArchive({ + expected: lock.languageServer.sha256, + filename: `${lock.languageServer.id}-${lock.languageServer.version}.vsix`, + id: lock.languageServer.id, version: lock.languageServer.version, + url: lock.languageServer.url, archive: pyrightArchive, directory, fetcher, + }); + return { version: lock.version, platform, python, debugger: debuggerExtension, languageServer }; +} + +async function installArchive({ expected, filename, url, archive, directory, fetcher, id, version }) { + const target = join(directory, '.downloads', filename); + let bytes; + let cached = false; + if (!archive) { + try { + bytes = await readFile(target); + if (sha256(bytes) !== expected) throw new Error(`Cached Python debugger checksum mismatch: ${target}`); + cached = true; + } catch (error) { if (error.code !== 'ENOENT') throw error; } + } + if (archive) { + if ((await stat(archive)).size > maxBytes) throw new Error('Python debugger archive exceeds 64 MiB'); + bytes = await readFile(archive); + } else if (!cached) { + const response = await fetcher(url, { signal: AbortSignal.timeout(120_000) }); + if (!response.ok || !response.body) throw new Error(`Python debugger download failed: HTTP ${response.status}`); + if (Number(response.headers.get('content-length')) > maxBytes) throw new Error('Python debugger archive exceeds 64 MiB'); + const chunks = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.length; + if (size > maxBytes) throw new Error('Python debugger archive exceeds 64 MiB'); + chunks.push(chunk); + } + bytes = Buffer.concat(chunks); + } + if (sha256(bytes) !== expected) throw new Error('Python debugger checksum mismatch; nothing was installed'); + await mkdir(dirname(target), { recursive: true }); + const temporary = `${target}.${randomUUID()}.partial`; + try { + await writeFile(temporary, bytes, { flag: 'wx', mode: 0o644 }); + await rename(temporary, target); + } finally { await rm(temporary, { force: true }); } + // Theia's local-dir resolver requires unpacked system plugins. Keep VSIX files + // in its explicitly ignored dot-directory and verify before every extraction. + const unpacked = join(directory, `.${id}-${randomUUID()}`); + const plugin = join(directory, id); + const previous = `${unpacked}-previous`; + let moved = false; + try { + await run('python3', ['-c', ` +import json,os,pathlib,stat,sys,zipfile +archive,target,expected_id,expected_version=sys.argv[1:] +with zipfile.ZipFile(archive) as z: + entries=z.infolist() + if len(entries)>100000 or sum(i.file_size for i in entries)>268435456: raise ValueError('Plugin extraction size limit') + for item in entries: + p=pathlib.PurePosixPath(item.filename) + if p.is_absolute() or '..' in p.parts or '\\\\' in item.filename or stat.S_ISLNK(item.external_attr>>16): raise ValueError('Unsafe plugin archive path') + manifest=json.loads(z.read('extension/package.json')) + if manifest.get('publisher')+'.'+manifest.get('name')!=expected_id or manifest.get('version')!=expected_version: raise ValueError('Plugin identity mismatch') + z.extractall(target) + for item in entries: + if not item.is_dir(): os.chmod(pathlib.Path(target)/item.filename, 0o755 if (item.external_attr>>16)&0o111 else 0o644) +`, target, unpacked, id, version], { timeout: 30_000 }); + try { await rename(plugin, previous); moved = true; } catch (error) { if (error.code !== 'ENOENT') throw error; } + try { await rename(unpacked, plugin); } catch (error) { if (moved) await rename(previous, plugin); throw error; } + await rm(previous, { recursive: true, force: true }); + } finally { await rm(unpacked, { recursive: true, force: true }); } + return { target: plugin, archive: target, sha256: expected, cached }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const args = process.argv.slice(2); + const flags = new Map(); + for (let index = 0; index < args.length; index += 2) flags.set(args[index], args[index + 1]); + if (args.length % 2 || [...flags].some(([key, value]) => !['--archive', '--python-archive', '--pyright-archive'].includes(key) || !value) || flags.size * 2 !== args.length) { + console.error('Usage: node scripts/download-python-debugger.mjs [--archive /path/to/debugpy.vsix] [--python-archive /path/to/python.vsix] [--pyright-archive /path/to/pyright.vsix]'); + process.exitCode = 1; + } else { + try { console.log(JSON.stringify(await installPythonDebugger({ archive: flags.get('--archive'), pythonArchive: flags.get('--python-archive'), pyrightArchive: flags.get('--pyright-archive') }))); } + catch (error) { console.error(error.message); process.exitCode = 1; } + } +} diff --git a/apps/ide/scripts/python-debugger.lock.json b/apps/ide/scripts/python-debugger.lock.json new file mode 100644 index 0000000..59cdba8 --- /dev/null +++ b/apps/ide/scripts/python-debugger.lock.json @@ -0,0 +1,26 @@ +{ + "id": "ms-python.debugpy", + "version": "2026.6.0", + "vscodeEngine": "^1.92.0", + "source": "https://open-vsx.org/extension/ms-python/debugpy/2026.6.0", + "pythonDependency": { + "id": "ms-python.python", + "version": "2026.4.0", + "vscodeEngine": "^1.95.0", + "url": "https://open-vsx.org/api/ms-python/python/2026.4.0/file/ms-python.python-2026.4.0.vsix", + "sha256": "232aeafb01f069824fdd92d3e628c1c442bbcfa1d3cc945ff97076340bb2b4a6" + }, + "languageServer": { + "id": "ms-pyright.pyright", + "version": "1.1.402", + "vscodeEngine": "^1.99.0", + "url": "https://open-vsx.org/api/ms-pyright/pyright/1.1.402/file/ms-pyright.pyright-1.1.402.vsix", + "sha256": "7ffa5a8649fa800b282c25ad70ce290367e036238d52727da7cdcac3d57439e9" + }, + "platforms": { + "darwin-arm64": "3425b5251b0f0642b569e64397effe72ab141d138abd966b567041baa5609b4b", + "darwin-x64": "7a87aeba6a4dc1f46cfb8e6d457e53256c80b5be75a1781d51d3e0ad5dbb1574", + "linux-x64": "c7744af4bf72978f5792624a71c80e2b622a1118574fada3a903d70ac03d5bca", + "linux-arm64": "4e7aa92b0459c1010ee010a79b35ecc16328b943a84589bd9e8ead3d4eb0010b" + } +} diff --git a/apps/ide/scripts/start.mjs b/apps/ide/scripts/start.mjs new file mode 100644 index 0000000..5607919 --- /dev/null +++ b/apps/ide/scripts/start.mjs @@ -0,0 +1,42 @@ +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { existsSync, mkdirSync } from 'node:fs'; + +const appRoot = fileURLToPath(new URL('../', import.meta.url)); +const cli = fileURLToPath(new URL('../node_modules/@theia/cli/bin/theia.js', import.meta.url)); +const production = process.env.NODE_ENV === 'production'; +if (!existsSync(cli) || !existsSync(`${appRoot}lib/frontend/index.html`)) { + // Theia releases may emit frontend assets under lib; use backend generation + // as the authoritative build prerequisite below. + if (!existsSync(`${appRoot}src-gen/backend/main.js`)) { + console.error('Install and build this independent package first: npm install && npm run build'); + process.exit(1); + } +} +if (production && process.env.WISHFORGE_GATEWAY_ENFORCED !== 'true') { + console.error('Production requires an authenticated workspace gateway. See README.md.'); + process.exit(1); +} +const port = process.env.WISHFORGE_IDE_PORT ?? '4300'; +if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) throw new Error('Invalid WISHFORGE_IDE_PORT'); +const hostname = process.env.WISHFORGE_IDE_HOST ?? '127.0.0.1'; +const workspace = process.env.WISHFORGE_WORKSPACE_PATH ?? `${appRoot}workspace`; +if (!process.env.WISHFORGE_WORKSPACE_PATH) mkdirSync(workspace, { recursive: true }); +if (!existsSync(workspace)) throw new Error('Configured workspace path does not exist'); +const child = spawn(process.execPath, [cli, 'start', workspace, '--hostname', hostname, '--port', port, '--plugins', `local-dir:${appRoot}plugins`], { + cwd: appRoot, + detached: process.platform !== 'win32', + stdio: 'inherit', + env: { + ...process.env, + PYTHONDONTWRITEBYTECODE: '1', + WF_IDE_MANAGED_PLUGINS_DIR: `${appRoot}plugins`, + // No public/default OCT fallback while project-bound room admission is absent. + COLLABORATION_SERVER_URL: process.env.WF_COLLABORATION_GATEWAY_URL ?? 'https://collaboration-disabled.invalid/', + }, +}); +for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { + try { if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal); else child.kill(signal); } + catch { child.kill(signal); } +}); +child.on('exit', (code) => process.exit(code ?? 1)); diff --git a/apps/ide/scripts/verify-managed-plugins.mjs b/apps/ide/scripts/verify-managed-plugins.mjs new file mode 100644 index 0000000..e4158d0 --- /dev/null +++ b/apps/ide/scripts/verify-managed-plugins.mjs @@ -0,0 +1,5 @@ +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +const { validateManagedPlugins } = createRequire(import.meta.url)('../policy/managed-plugins.cjs'); +const plugins = validateManagedPlugins(fileURLToPath(new URL('../plugins', import.meta.url))); +console.log(`Verified ${plugins.length} operator-managed extensions against pinned IDs, versions and content digests.`); diff --git a/apps/ide/security/assertions.cjs b/apps/ide/security/assertions.cjs new file mode 100644 index 0000000..e7462c4 --- /dev/null +++ b/apps/ide/security/assertions.cjs @@ -0,0 +1,21 @@ +const { createPrivateKey, createPublicKey, sign, verify } = require('node:crypto'); +const roles = new Set(['owner','admin','developer']); +function signAssertion(privateKey, grant, now = Date.now()) { + if (!grant.userId || !roles.has(grant.role)) throw new Error('Workspace actor is not authorized'); + const body = Buffer.from(JSON.stringify({ aud:'wishforge-workspace', purpose:grant.purpose??'interactive', tenantId:grant.tenantId, workspaceId:grant.workspaceId, actorId:grant.userId, role:grant.role, iat:Math.floor(now/1000), exp:Math.floor(now/1000)+900 })).toString('base64url'); + return `${body}.${sign(null,Buffer.from(body),createPrivateKey(privateKey)).toString('base64url')}`; +} +function verifyAssertion(publicKey, value, scope, now = Date.now()) { + if(typeof value!=='string'||value.length>4096)throw new Error('WORKSPACE_IDENTITY_REQUIRED'); + const parts=value.split('.'); + if(parts.length!==2||parts.some(part=>!part||!/^[A-Za-z0-9_-]+$/.test(part)||Buffer.from(part,'base64url').toString('base64url')!==part)||Buffer.from(parts[1],'base64url').length!==64)throw new Error('WORKSPACE_IDENTITY_INVALID'); + const [body, signature]=parts; + const key=createPublicKey(publicKey); + if(key.asymmetricKeyType!=='ed25519'||!verify(null,Buffer.from(body),key,Buffer.from(signature,'base64url')))throw new Error('WORKSPACE_IDENTITY_INVALID'); + const claims=JSON.parse(Buffer.from(body,'base64url').toString()); + const time=Math.floor(now/1000); + if((claims.purpose??'interactive')!==(scope.purpose??'interactive'))throw new Error('WORKSPACE_IDENTITY_PURPOSE'); + if(claims.aud!=='wishforge-workspace'||claims.tenantId!==scope.tenantId||claims.workspaceId!==scope.workspaceId||typeof claims.actorId!=='string'||!claims.actorId||!roles.has(claims.role)||!Number.isInteger(claims.iat)||!Number.isInteger(claims.exp)||claims.iat>time+30||claims.exp<=time||claims.exp<=claims.iat||claims.exp-claims.iat>900)throw new Error('WORKSPACE_IDENTITY_SCOPE'); + return claims; +} +module.exports={signAssertion,verifyAssertion}; diff --git a/apps/ide/security/create-local-keys.cjs b/apps/ide/security/create-local-keys.cjs new file mode 100644 index 0000000..f04ae8b --- /dev/null +++ b/apps/ide/security/create-local-keys.cjs @@ -0,0 +1,10 @@ +const fs=require('node:fs');const path=require('node:path');const {generateKeyPairSync,createPrivateKey,createPublicKey}=require('node:crypto'); +const directory=path.resolve(process.argv[2]??'.wishforge/gateway-keys'); +fs.mkdirSync(directory,{recursive:true,mode:0o700}); +const privateFile=path.join(directory,'private.pem'),publicFile=path.join(directory,'public.pem'); +if(!fs.existsSync(privateFile)){const keys=generateKeyPairSync('ed25519');fs.writeFileSync(privateFile,keys.privateKey.export({type:'pkcs8',format:'pem'}),{flag:'wx',mode:0o600});} +const privateKey=createPrivateKey(fs.readFileSync(privateFile));if(privateKey.asymmetricKeyType!=='ed25519')throw new Error('Existing gateway key is not Ed25519'); +const publicPem=createPublicKey(privateKey).export({type:'spki',format:'pem'}); +if(fs.existsSync(publicFile)&&fs.readFileSync(publicFile,'utf8')!==publicPem)throw new Error('Existing public key does not match; inspect key rotation explicitly'); +if(!fs.existsSync(publicFile))fs.writeFileSync(publicFile,publicPem,{flag:'wx',mode:0o644}); +console.log(JSON.stringify({privateKeyFile:privateFile,publicKeyFile:publicFile})); diff --git a/apps/ide/security/test/assertions.test.cjs b/apps/ide/security/test/assertions.test.cjs new file mode 100644 index 0000000..2460446 --- /dev/null +++ b/apps/ide/security/test/assertions.test.cjs @@ -0,0 +1,81 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { generateKeyPairSync, sign } = require('node:crypto'); +const { signAssertion, verifyAssertion } = require('../assertions.cjs'); + +const pair = generateKeyPairSync('ed25519'); +const privateKey = pair.privateKey.export({ format: 'pem', type: 'pkcs8' }); +const publicKey = pair.publicKey.export({ format: 'pem', type: 'spki' }); +const time = 1_725_000_000_000; +const scope = { tenantId: 'tenant-one', workspaceId: 'workspace-one' }; +const grant = { ...scope, userId: 'actor-alice', role: 'developer' }; +function claims(overrides = {}) { + return { aud: 'wishforge-workspace', purpose: 'interactive', ...scope, actorId: grant.userId, role: grant.role, iat: Math.floor(time / 1000), exp: Math.floor(time / 1000) + 900, ...overrides }; +} +function signedClaims(value) { + const body = Buffer.from(JSON.stringify(value)).toString('base64url'); + return `${body}.${sign(null, Buffer.from(body), privateKey).toString('base64url')}`; +} + +test('Ed25519 assertion roundtrip binds each authorized role to actor, tenant and workspace', () => { + for (const role of ['owner', 'admin', 'developer']) { + const token = signAssertion(privateKey, { ...grant, role }, time); + assert.deepEqual(verifyAssertion(publicKey, token, scope, time), claims({ role })); + } +}); + +test('body tampering, forged signature and untrusted signing keys are rejected', () => { + const token = signAssertion(privateKey, grant, time); + const [body, signature] = token.split('.'); + const tampered = Buffer.from(JSON.stringify(claims({ actorId: 'attacker' }))).toString('base64url'); + assert.throws(() => verifyAssertion(publicKey, `${tampered}.${signature}`, scope, time), /WORKSPACE_IDENTITY_INVALID/); + const forgedSignature = Buffer.from(signature, 'base64url'); + forgedSignature[0] ^= 1; + assert.throws(() => verifyAssertion(publicKey, `${body}.${forgedSignature.toString('base64url')}`, scope, time), /WORKSPACE_IDENTITY_INVALID/); + const untrusted = generateKeyPairSync('ed25519'); + assert.throws(() => verifyAssertion(untrusted.publicKey.export({ type: 'spki', format: 'pem' }), token, scope, time), /WORKSPACE_IDENTITY_INVALID/); +}); + +test('expiry boundary, future issue time and overlong assertion lifetime fail closed', () => { + const token = signAssertion(privateKey, grant, time); + assert.equal(verifyAssertion(publicKey, token, scope, time + 899_999).actorId, grant.userId); + assert.throws(() => verifyAssertion(publicKey, token, scope, time + 900_000), /WORKSPACE_IDENTITY_SCOPE/); + assert.throws(() => verifyAssertion(publicKey, signedClaims(claims({ iat: Math.floor(time / 1000) + 31 })), scope, time), /WORKSPACE_IDENTITY_SCOPE/); + assert.throws(() => verifyAssertion(publicKey, signedClaims(claims({ exp: Math.floor(time / 1000) + 901 })), scope, time), /WORKSPACE_IDENTITY_SCOPE/); + assert.throws(() => verifyAssertion(publicKey, signedClaims(claims({ exp: 'later' })), scope, time), /WORKSPACE_IDENTITY_SCOPE/); +}); + +test('valid signatures cannot cross tenant, workspace, audience or role boundaries', () => { + const token = signAssertion(privateKey, grant, time); + assert.throws(() => verifyAssertion(publicKey, token, { ...scope, tenantId: 'tenant-two' }, time), /WORKSPACE_IDENTITY_SCOPE/); + assert.throws(() => verifyAssertion(publicKey, token, { ...scope, workspaceId: 'workspace-two' }, time), /WORKSPACE_IDENTITY_SCOPE/); + for (const overrides of [{ aud: 'another-service' }, { role: 'viewer' }, { role: 'deployer' }, { role: 'root' }, { actorId: '' }, { actorId: 5 }]) { + assert.throws(() => verifyAssertion(publicKey, signedClaims(claims(overrides)), scope, time), /WORKSPACE_IDENTITY_SCOPE/); + } + assert.throws(() => signAssertion(privateKey, { ...grant, role: 'viewer' }, time), /not authorized/); + assert.throws(() => signAssertion(privateKey, { ...grant, userId: '' }, time), /not authorized/); +}); + +test('assertions require exactly two canonical base64url segments', () => { + const token = signAssertion(privateKey, grant, time); + const [body, signature] = token.split('.'); + for (const value of [token + '.', token + '..', token + '!!!!', token + '=', `${body}. ${signature}`, `${body}.${signature}.extra`, `${body}.`, `.${signature}`, '', undefined, 5, 'x'.repeat(4097)]) { + assert.throws(() => verifyAssertion(publicKey, value, scope, time), undefined, `Accepted malformed assertion ${String(value).slice(-20)}`); + } +}); + +test('a non-Ed25519 public key cannot authorize an otherwise valid assertion', () => { + const token = signAssertion(privateKey, grant, time); + const other = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + assert.throws(() => verifyAssertion(other.publicKey.export({ type: 'spki', format: 'pem' }), token, scope, time), /WORKSPACE_IDENTITY_INVALID/); +}); + + +test('integration inspection assertion cannot invoke interactive coordination or debug', () => { + const token = signAssertion(privateKey, { ...grant, purpose: 'integration-state' }, time); + assert.equal(verifyAssertion(publicKey, token, { ...scope, purpose: 'integration-state' }, time).purpose, 'integration-state'); + assert.throws(() => verifyAssertion(publicKey, token, scope, time), /WORKSPACE_IDENTITY_PURPOSE/); + assert.throws(() => verifyAssertion(publicKey, signAssertion(privateKey, grant, time), { ...scope, purpose: 'integration-state' }, time), /WORKSPACE_IDENTITY_PURPOSE/); +}); diff --git a/apps/preview-gateway/README.md b/apps/preview-gateway/README.md new file mode 100644 index 0000000..379c433 --- /dev/null +++ b/apps/preview-gateway/README.md @@ -0,0 +1,192 @@ +# Private application preview gateway + +This standalone Node service fronts **one tenant / project / environment** on one +dedicated public hostname. It is separate from Theia and never grants terminal, +editor, debugger or filesystem access. No external deployment, DNS change or public +listener is created by its tests or startup defaults. + +## Operator configuration + +The API reads `WF_PREVIEW_TARGETS_FILE`, an operator-controlled JSON file: + +```json +{ + "schemaVersion": 1, + "targets": [{ + "tenantId": "tenant-a", + "projectId": "project-a", + "environmentId": "environment-a", + "publicOrigin": "https://app-a.preview.example.net", + "upstreamOrigin": "http://private-app-a.namespace.svc:3000", + "gatewayTokenEnv": "WF_TENANT_A_PREVIEW_TOKEN", + "proofPublicKeyFile": "/run/secrets/preview-a-proof-public.pem" + }] +} +``` + +Each environment must have a unique hostname, even when ports differ. Preview hosts +cannot match console, API or IDE authentication hosts. The API rejects duplicate +environment mappings, shared hosts, URLs with credentials/path/query/fragment and +missing environment service credentials. Production public origins require HTTPS; +development HTTP is restricted to loopback. No user, model or project manifest can +submit a target URL or key to these routes. + +Run one gateway with its fixed corresponding values: + +```text +NODE_ENV=production +WF_PREVIEW_TENANT_ID=tenant-a +WF_PREVIEW_PROJECT_ID=project-a +WF_PREVIEW_ENVIRONMENT_ID=environment-a +WF_PREVIEW_PUBLIC_ORIGIN=https://app-a.preview.example.net +WF_PREVIEW_UPSTREAM_ORIGIN=http://private-app-a.namespace.svc:3000 +WF_API_PUBLIC_URL=https://control.example.net +WF_PREVIEW_GATEWAY_TOKEN= +WF_PREVIEW_PROOF_PRIVATE_KEY_FILE=/run/secrets/preview-a-proof-private.pem +HOST=127.0.0.1 +PORT=4460 +``` + +The proof key is an independently generated Ed25519 key pair. Mount the private key +read-only in the gateway, never in the application, coding sandbox, browser or API. +The API and independent verifier receive only its public key. The gateway service +token is separate from all OIDC, internal worker, deployment and resource-grant keys. +The API environment reference must resolve to the same service token as this gateway. + +`node apps/preview-gateway/main.mjs` starts the service. A production TLS ingress must +preserve the exact public `Host`, reach this gateway and deny direct external access +to the upstream application. The process listens only on loopback by default. Its +protocol tests do not prove external routing, TLS, DNS or upstream network isolation. + +## Browser flow and live authorization + +1. An authenticated user calls `POST /v1/environments/:id/preview-launch`. +2. The API verifies current tenant membership, project ACL, an accepted private + release, its current policy digest and the original identity expiry. It returns + a single-use launch URL valid for at most 30 seconds. +3. Navigation to `/_wishforge/session?code=...` makes the gateway consume the code + through `POST /preview-control/authorize`, authenticated with its environment + service token. Consumption and session issuance are transactional. Only the hash + of the opaque code/session capability is persisted. +4. The gateway sets `__Host-WF_PREVIEW_SESSION` with `Secure`, `HttpOnly`, `Path=/`, + `SameSite=Lax` and **no Domain**, then redirects to the exact release-bound + `applicationUrl`, including a non-root entry path. The gateway checks that the + destination belongs to its fixed public origin. Its lifetime is the smaller + of 15 minutes and the user's original credential expiry. Plain HTTP loopback + fixtures use `WF_PREVIEW_SESSION` without Secure. Production launch requires a + trusted expiring identity; worker identities cannot launch a browser session. +5. Every HTTP request and WebSocket handshake rechecks membership, project ACL, + release, policy and expiry. Active HTTP streams/WebSockets recheck at most every + five seconds and close on revocation or authorization-service failure. + +Viewer access permits GET/HEAD and denies mutations and WebSockets. This is an HTTP +method restriction: applications must not mutate data in GET handlers. Other user +roles may use application writes only with an exact same-origin Origin header; +WebSockets always require that header. Cross-origin CORS allowances from the upstream +are removed. Anonymous application requests are denied by the gateway itself. + +The fixed target hostname and current `privateAccessPolicyDigest` are checked for +every session. The digest covers tenant, project, environment, public origin, upstream +origin and proof public key; it excludes service-token rotation. Changing routing or +keys invalidates old authorizations and prevents issuing new ones for an old healthy +release. An accepted new release must bind the new policy first. + +## Application authentication and proxy behavior + +Non-reserved application cookies pass through. Response cookies have Domain removed +so they remain host-only. Application attempts to set reserved `WF_*` / `__Host-WF_*` +cookies are discarded. Gateway/console cookies are removed before forwarding; probe +and service headers never reach the application. Application cookie-based login has +a real HTTP round-trip fixture. + +The proxy removes Authorization and proxy-authorization headers, all +`X-WishForge-*`, spoofed forwarding headers and upstream authentication/identity +metadata. **Application login protocols that require forwarding Authorization are +not supported by this first gateway.** It does not treat application tokens as +platform identities. External absolute redirects are blocked; redirects to the +configured upstream are rewritten to the private public origin. The proxy does not +rewrite arbitrary application HTML/JavaScript: an application must use public or +relative asset URLs instead of embedding internal network addresses. + +Requests are limited to 8 MiB. Probe responses are bounded to 4 MiB and 15 seconds. +Normal response bodies and WebSockets stream with live authorization checks. This +gateway does not expose its service URL, key, token or internal upstream in a browser +launch response. It does not store or forward the user's OIDC bearer token. + +## Independent release probes + +`Previews.issueProbeInTransaction(tx, actor, releaseId)` can be called inside the +Runner transaction without opening another database transaction. The release must +already own `environment.activeReleaseId` in deploying/unknown state, or be the +healthy current release. It returns: + +```text +tenantId, environmentId, publicOrigin, releaseId, bindingDigest, +policyDigest, capability, capabilitySha256, challenge, expiresAt, proofPublicKeyPem +``` + +The opaque capability expires after 120 seconds. The API independently generates and +persists its random challenge and capability hash. It is bound to the active release +and its current gateway policy. It permits GET/HEAD only to that release's protected +health path, business smoke paths and configured application URL path. It is not a +general application session or an arbitrary URL fetcher. The runner endpoint +`POST /internal/runner/releases/:id/preview-probe` requires `{ "taskId": "..." }` +and issues a fresh capability only for the current environment Runner's pending, +unexpired signed task with the same release/binding. It binds `runnerTaskId` in the +persisted authorization and caps capability expiry at that task's expiry. Keep capabilities out of build artifacts, logs, +evidence and immutable release identity; they are short-lived transport credentials. + +For an authenticated probe, use: + +```text +X-WishForge-Preview-Capability: +X-WishForge-Preview-Challenge: +``` + +For an anonymous-denial probe, send the issued challenge and no cookie/capability. +The gateway returns a signed 401 without contacting the application. This avoids +mistaking an application's own 401 for a private gateway. An authenticated request +whose application returns 401 has `decision: authorized`, which cannot satisfy an +anonymous-denial check. + +`X-WishForge-Preview-Proof` contains +`base64url(JSON payload).base64url(Ed25519 signature over the encoded payload)`. +`proof.mjs` exports `verifyPreviewProof` and `bodySha256`. The payload contains: + +```text +schemaVersion=1, tenantId, environmentId, publicOrigin, +releaseId, bindingDigest, policyDigest, capabilitySha256, challenge, +decision='authorized' | 'anonymous_denied', method, path, status, +bodySha256, issuedAt, expiresAt +``` + +Times are milliseconds. Proof lifetime is at most 120 seconds. `path` is the exact +request path including query. Anonymous denial has null release/binding/policy/capability fields; +pair it with an authenticated proof bound to the expected release and policy. The +verifier must check signature, all expected scope fields, fresh challenge, method, +path, HTTP status and actual received body digest. Verifying a signature alone is +insufficient. Gateway proof response headers from an application are discarded. +The independent API receipt verifier can locate the persisted `probe-` +authorization, verify the issued challenge/expiry and mark it consumed by a single +runner task. Repeated receipts for that same task may be idempotent; another task must +not reuse it. No raw capability needs to be retained in acceptance evidence. + +## Evidence and remaining deployment acceptance + +`tests/previews.test.ts` covers one-use replay, tenant/project ACL, Viewer restrictions, +revocation, original identity expiry, release binding, protected probe paths, policy +changes and unique hostname checks. `node --test apps/preview-gateway/test/*.test.mjs` +uses real loopback HTTP and WebSocket sockets to verify anonymous/probe signatures, +credential stripping, host/cookie/Origin restrictions, login cookies, streaming and +socket revocation. API tests use an explicitly labelled transactional memory fixture; +socket tests use a fixture authorization service. They are not production identity or +Kubernetes acceptance. + +Malformed authorization expiry fails closed. Invalid application WebSocket upgrade +headers terminate that upstream connection without crashing the gateway process. + +Actual deployment must additionally verify TLS ingress, dedicated DNS, upstream +inaccessibility, gateway key separation, real OIDC expiry, durable API storage and +the runtime's independent proof-validation path. Sessions depend on the API database +and fail closed during its outage. Expired authorization records are small audit +records; an operator retention policy is still required for long-term cleanup. diff --git a/apps/preview-gateway/main.mjs b/apps/preview-gateway/main.mjs new file mode 100644 index 0000000..ae61376 --- /dev/null +++ b/apps/preview-gateway/main.mjs @@ -0,0 +1,6 @@ +import { readFile } from 'node:fs/promises'; +import { createPreviewGateway } from './server.mjs'; +const required=name=>{const value=process.env[name];if(!value)throw new Error(`Unconfigured: ${name}`);return value;}; +const gateway=createPreviewGateway({tenantId:required('WF_PREVIEW_TENANT_ID'),environmentId:required('WF_PREVIEW_ENVIRONMENT_ID'),projectId:required('WF_PREVIEW_PROJECT_ID'),publicOrigin:required('WF_PREVIEW_PUBLIC_ORIGIN'),upstreamOrigin:required('WF_PREVIEW_UPSTREAM_ORIGIN'),apiOrigin:required('WF_API_PUBLIC_URL'),serviceToken:required('WF_PREVIEW_GATEWAY_TOKEN'),proofPrivateKey:await readFile(required('WF_PREVIEW_PROOF_PRIVATE_KEY_FILE'),'utf8'),production:process.env.NODE_ENV==='production'}); +gateway.server.listen(Number(process.env.PORT??4460),process.env.HOST??'127.0.0.1',()=>console.log('Private preview gateway started with fixed environment routing.')); +const close=()=>void gateway.close();process.once('SIGINT',close);process.once('SIGTERM',close); diff --git a/apps/preview-gateway/package.json b/apps/preview-gateway/package.json new file mode 100644 index 0000000..691804a --- /dev/null +++ b/apps/preview-gateway/package.json @@ -0,0 +1 @@ +{"name":"@wishforge/preview-gateway","version":"0.1.0","private":true,"type":"module","engines":{"node":">=22"},"scripts":{"start":"node main.mjs","test":"node --test test/*.test.mjs"}} diff --git a/apps/preview-gateway/proof.mjs b/apps/preview-gateway/proof.mjs new file mode 100644 index 0000000..d15856a --- /dev/null +++ b/apps/preview-gateway/proof.mjs @@ -0,0 +1,17 @@ +import { createHash, sign, verify, createPrivateKey, createPublicKey } from 'node:crypto'; +export const bodySha256 = value => createHash('sha256').update(value).digest('hex'); +export function signPreviewProof(privateKey, payload) { + if (createPrivateKey(privateKey).asymmetricKeyType !== 'ed25519') throw new Error('Ed25519 proof key required'); + const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url'); + return `${encoded}.${sign(null,Buffer.from(encoded),privateKey).toString('base64url')}`; +} +export function verifyPreviewProof(publicKey, proof, expected, now=Date.now()) { + try { + if (typeof proof!=='string'||proof.length>8192||createPublicKey(publicKey).asymmetricKeyType!=='ed25519') return undefined; + const parts=proof.split('.');if(parts.length!==2||!verify(null,Buffer.from(parts[0]),publicKey,Buffer.from(parts[1],'base64url')))return undefined; + const value=JSON.parse(Buffer.from(parts[0],'base64url').toString()); + if(value.schemaVersion!==1||!Number.isSafeInteger(value.issuedAt)||value.issuedAt>now+5000||now-value.issuedAt>120000||!Number.isSafeInteger(value.expiresAt)||value.expiresAt<=now||value.expiresAt-value.issuedAt>120000)return undefined; + for(const [key,wanted]of Object.entries(expected))if(value[key]!==wanted)return undefined; + return value; + }catch{return undefined;} +} diff --git a/apps/preview-gateway/server.mjs b/apps/preview-gateway/server.mjs new file mode 100644 index 0000000..2c309c0 --- /dev/null +++ b/apps/preview-gateway/server.mjs @@ -0,0 +1,60 @@ +import http from 'node:http'; +import https from 'node:https'; +import { createPrivateKey } from 'node:crypto'; +import { bodySha256, signPreviewProof } from './proof.mjs'; + +const ID=/^[A-Za-z0-9_-]{1,128}$/; +const CAP=/^[A-Za-z0-9_-]{43}$/; +const CHALLENGE=/^[A-Za-z0-9_-]{32,128}$/; +const HOP=new Set(['connection','keep-alive','proxy-authenticate','proxy-authorization','te','trailer','transfer-encoding','upgrade']); +class Failure extends Error{constructor(status,message){super(message);this.status=status;}} +export function createPreviewGateway(config){ + const publicUrl=new URL(config.publicOrigin),upstream=new URL(config.upstreamOrigin),api=new URL(config.apiOrigin); + for(const value of[publicUrl,upstream,api])if(!['http:','https:'].includes(value.protocol)||value.username||value.password||value.pathname!=='/'||value.search||value.hash)throw new Error('Explicit credential-free origins required'); + if(config.production!==false&&(publicUrl.protocol!=='https:'||api.protocol!=='https:'))throw new Error('Production public and API origins require HTTPS'); + if(config.production===false&&publicUrl.protocol==='http:'&&!['127.0.0.1','localhost','[::1]'].includes(publicUrl.hostname))throw new Error('Development plaintext preview is loopback only'); + if(publicUrl.origin===upstream.origin||publicUrl.hostname===api.hostname||!ID.test(config.tenantId)||!ID.test(config.environmentId)||!ID.test(config.projectId)||typeof config.serviceToken!=='string'||config.serviceToken.length<32||createPrivateKey(config.proofPrivateKey).asymmetricKeyType!=='ed25519')throw new Error('Scoped preview configuration and independent Ed25519 key required'); + const fetcher=config.fetchImpl??fetch,secure=publicUrl.protocol==='https:',cookieName=secure?'__Host-WF_PREVIEW_SESSION':'WF_PREVIEW_SESSION'; + const pollMs=Math.max(20,Math.min(config.reauthorizeMs??3000,5000)),active=new Set(),sockets=new Set(); + function host(req){if(req.headers.host!==publicUrl.host)throw new Failure(421,'Unknown preview host');} + function origin(req,required=false){if(required&&!req.headers.origin||req.headers.origin&&req.headers.origin!==publicUrl.origin)throw new Failure(403,'Preview origin denied');} + function route(req){if(!req.url?.startsWith('/')||req.url.startsWith('//')||req.url.includes('\\'))throw new Failure(400,'Invalid preview path');const url=new URL(req.url,publicUrl);if(url.origin!==publicUrl.origin)throw new Failure(400,'Invalid preview path');return url;} + function credential(req){const values=(req.headers.cookie??'').split(';').map(value=>value.trim()).filter(value=>value.startsWith(`${cookieName}=`));if(values.length!==1)throw new Failure(401,'Private preview authentication required');const value=values[0].slice(cookieName.length+1);if(!CAP.test(value))throw new Failure(401,'Private preview authentication required');return value;} + async function authorize(kind,value,method,path,challenge){ + if(!CAP.test(value??''))throw new Failure(401,'Private preview authentication required'); + let response;try{response=await fetcher(`${api.origin}/preview-control/authorize`,{method:'POST',headers:{authorization:`Bearer ${config.serviceToken}`,'content-type':'application/json'},body:JSON.stringify({tenantId:config.tenantId,environmentId:config.environmentId,kind,credential:value,method,path,...(kind==='probe'?{challenge}:{})}),redirect:'error',signal:AbortSignal.timeout(3000)});}catch{throw new Failure(503,'Preview authorization unavailable');} + if(!response.ok)throw new Failure([401,403,404].includes(response.status)?response.status:503,'Private preview authorization denied'); + const payload=await response.json(),grant=payload.data??payload; + if(grant.tenantId!==config.tenantId||grant.environmentId!==config.environmentId||grant.projectId!==config.projectId||grant.publicOrigin!==publicUrl.origin||!grant.releaseId||!grant.bindingDigest||!Number.isFinite(Date.parse(grant.expiresAt))||Date.parse(grant.expiresAt)<=Date.now()||kind==='probe'&&grant.role!=='probe'||kind!=='probe'&&!['owner','admin','developer','deployer','viewer'].includes(grant.role))throw new Failure(403,'Preview grant mismatch'); + let destination;try{destination=new URL(grant.applicationUrl);}catch{throw new Failure(403,'Preview application URL missing');}if(destination.origin!==publicUrl.origin||destination.username||destination.password||destination.pathname.startsWith('/_wishforge/'))throw new Failure(403,'Preview application URL mismatch'); + if(grant.role==='viewer'&&!['GET','HEAD'].includes(method))throw new Failure(403,'Viewer access is read-only'); + return grant; + } + function baseHeaders(){return{'cache-control':'no-store','referrer-policy':'no-referrer','x-content-type-options':'nosniff','origin-agent-cluster':'?1','cross-origin-opener-policy':'same-origin'};} + function proof(req,grant,decision,status,body){const challenge=req.headers['x-wishforge-preview-challenge'];if(!CHALLENGE.test(challenge??''))return undefined;const issuedAt=Date.now();return signPreviewProof(config.proofPrivateKey,{schemaVersion:1,tenantId:config.tenantId,environmentId:config.environmentId,publicOrigin:publicUrl.origin,releaseId:grant?.releaseId??null,bindingDigest:grant?.bindingDigest??null,policyDigest:grant?.policyDigest??null,capabilitySha256:decision==='authorized'?bodySha256(req.headers['x-wishforge-preview-capability']):null,challenge,decision,method:req.method,path:req.url,status,bodySha256:bodySha256(body),issuedAt,expiresAt:issuedAt+120000});} + function fail(req,res,error,anonymous=false){if(res.headersSent){res.destroy();return;}const status=error.status??502,body=Buffer.from(JSON.stringify({error:status===401?'Private preview authentication required':error.status?error.message:'Preview unavailable'})),headers={...baseHeaders(),'content-type':'application/json','content-length':String(body.length)};if(anonymous&&status===401){const signed=proof(req,undefined,'anonymous_denied',status,body);if(signed)headers['x-wishforge-preview-proof']=signed;}res.writeHead(status,headers);res.end(body);} + function proxyHeaders(req,websocket=false){const headers={...req.headers},connectionFields=String(headers.connection??'').split(',').map(value=>value.trim().toLowerCase());for(const key of Object.keys(headers))if(HOP.has(key)||connectionFields.includes(key)||['authorization','host','origin','referer'].includes(key)||key.startsWith('x-forwarded-')||key.startsWith('x-wishforge-'))delete headers[key];const appCookies=(req.headers.cookie??'').split(';').map(value=>value.trim()).filter(value=>value&&!value.startsWith(`${cookieName}=`)&&!/^(__Host-)?WF_/i.test(value));if(appCookies.length)headers.cookie=appCookies.join('; ');else delete headers.cookie;headers.host=upstream.host;headers.origin=upstream.origin;if(websocket){headers.connection='Upgrade';headers.upgrade='websocket';}return headers;} + function responseHeaders(raw){const headers={};for(const[key,value]of Object.entries(raw)){if(value===undefined||HOP.has(key)||key.startsWith('x-wishforge-')||key.startsWith('access-control-')||['server','x-powered-by','content-location','refresh','link','access-control-allow-origin','access-control-allow-credentials'].includes(key))continue;if(key==='set-cookie'){headers[key]=(Array.isArray(value)?value:[value]).filter(item=>!/^\s*(?:__Host-)?WF_/i.test(item)).map(item=>item.replace(/;\s*domain=[^;]*/ig,'')+(secure&&!/;\s*secure(?:;|$)/i.test(item)?'; Secure':''));continue;}if(key==='location'){const location=new URL(String(value),upstream);if(location.origin!==upstream.origin)throw new Failure(502,'External application redirect is not permitted');headers.location=`${publicUrl.origin}${location.pathname}${location.search}${location.hash}`;continue;}headers[key]=value;}return{...headers,...baseHeaders()};} + function watch(kind,value,method,path,stop){let busy=false,closed=false;const timer=setInterval(async()=>{if(busy||closed)return;busy=true;try{await authorize(kind,value,method,path);}catch{stop();}finally{busy=false;}},pollMs);timer.unref();const close=()=>{closed=true;clearInterval(timer);active.delete(close);};active.add(close);return close;} + const server=http.createServer(async(req,res)=>{let anonymous=false;try{ + host(req);const url=route(req); + if(url.pathname==='/_wishforge/session'&&req.method==='GET'){ + const grant=await authorize('launch',url.searchParams.get('code'),'GET','/');if(!CAP.test(grant.sessionToken??''))throw new Failure(502,'Invalid preview session'); + res.writeHead(303,{...baseHeaders(),location:new URL(grant.applicationUrl).href, 'set-cookie':`${cookieName}=${grant.sessionToken}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${Math.max(0,Math.min(900,Math.floor((Date.parse(grant.expiresAt)-Date.now())/1000)))}${secure?'; Secure':''}`});res.end();return; + } + if(url.pathname.startsWith('/_wishforge/'))throw new Failure(404,'Reserved preview path'); + const isProbe=typeof req.headers['x-wishforge-preview-capability']==='string'; + let value;if(isProbe){value=req.headers['x-wishforge-preview-capability'];if(!CHALLENGE.test(req.headers['x-wishforge-preview-challenge']??''))throw new Failure(400,'Release probe challenge required');if(!['GET','HEAD'].includes(req.method))throw new Failure(403,'Read-only release probe required');} + else{try{value=credential(req);}catch(error){anonymous=true;throw error;}origin(req,!['GET','HEAD'].includes(req.method));} + const kind=isProbe?'probe':'session',grant=await authorize(kind,value,req.method,req.url,req.headers['x-wishforge-preview-challenge']); + if(req.headers['content-length']!==undefined&&(!/^\d+$/.test(req.headers['content-length'])||Number(req.headers['content-length'])>8*1024*1024))throw new Failure(413,'Preview request exceeds 8 MiB'); + const target=new URL(req.url,upstream); + if(isProbe){const response=await fetcher(target,{method:req.method,headers:{accept:'*/*','accept-encoding':'identity'},redirect:'manual',signal:AbortSignal.timeout(15000)});const chunks=[];let size=0;if(response.body)for await(const chunk of response.body){size+=chunk.length;if(size>4*1024*1024)throw new Failure(502,'Preview probe exceeds body limit');chunks.push(chunk);}const body=Buffer.concat(chunks);await authorize(kind,value,req.method,req.url,req.headers['x-wishforge-preview-challenge']);const signed=proof(req,grant,'authorized',response.status,body),headers=responseHeaders(Object.fromEntries(response.headers));delete headers['content-encoding'];headers['content-length']=String(body.length);headers['x-wishforge-preview-proof']=signed;res.writeHead(response.status,headers);res.end(req.method==='HEAD'?undefined:body);return;} + const transport=target.protocol==='https:'?https:http;const forward=transport.request(target,{method:req.method,headers:proxyHeaders(req)},response=>{try{res.writeHead(response.statusCode??502,responseHeaders(response.headers));response.pipe(res);}catch(error){response.destroy();fail(req,res,error);}}); + forward.setTimeout(60000,()=>forward.destroy());forward.on('error',()=>fail(req,res,new Failure(502,'Preview upstream unavailable'))); + const endWatch=watch(kind,value,req.method,req.url,()=>{forward.destroy();res.destroy();});res.on('close',()=>{endWatch();forward.destroy();});req.on('aborted',()=>forward.destroy());let received=0;req.on('data',chunk=>{received+=chunk.length;if(received>8*1024*1024){req.unpipe(forward);forward.destroy();fail(req,res,new Failure(413,'Preview request exceeds 8 MiB'));}});req.pipe(forward); + }catch(error){fail(req,res,error,anonymous);}}); + server.on('connection',socket=>{sockets.add(socket);socket.on('close',()=>sockets.delete(socket));}); + server.on('upgrade',async(req,socket,head)=>{try{host(req);origin(req,true);const url=route(req);if(url.pathname.startsWith('/_wishforge/'))throw new Failure(404,'Reserved preview path');const value=credential(req);await authorize('session',value,'WS',req.url);const target=new URL(req.url,upstream),transport=target.protocol==='https:'?https:http;const forward=transport.request(target,{method:'GET',headers:proxyHeaders(req,true)});forward.setTimeout(10000,()=>forward.destroy());forward.on('upgrade',(response,peer,peerHead)=>{if(response.statusCode!==101){peer.destroy();socket.destroy();return;}let headers;try{headers=responseHeaders(response.headers);}catch{peer.destroy();socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');return;}headers.connection='Upgrade';headers.upgrade='websocket';socket.write(`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(headers).flatMap(([key,value])=>(Array.isArray(value)?value:[value]).map(item=>`${key}: ${item}`)).join('\r\n')}\r\n\r\n`);if(head.length)peer.write(head);if(peerHead.length)socket.write(peerHead);socket.pipe(peer);peer.pipe(socket);const endWatch=watch('session',value,'WS',req.url,()=>{peer.destroy();socket.destroy();});socket.on('close',()=>{endWatch();peer.destroy();});peer.on('close',()=>{endWatch();socket.destroy();});peer.on('error',()=>socket.destroy());socket.on('error',()=>peer.destroy());});forward.on('response',response=>{response.resume();socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');});forward.on('error',()=>socket.destroy());socket.on('close',()=>forward.destroy());forward.end();}catch(error){socket.end(`HTTP/1.1 ${error.status??502} Access Denied\r\nConnection: close\r\n\r\n`);}}); + return{server,cookieName,async close(){for(const end of active)end();for(const socket of sockets)socket.destroy();if(server.listening)await new Promise(resolve=>server.close(resolve));}}; +} diff --git a/apps/preview-gateway/test/gateway.test.mjs b/apps/preview-gateway/test/gateway.test.mjs new file mode 100644 index 0000000..72c0280 --- /dev/null +++ b/apps/preview-gateway/test/gateway.test.mjs @@ -0,0 +1,38 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import net from 'node:net'; +import { createHash, generateKeyPairSync } from 'node:crypto'; +import { once } from 'node:events'; +import { createPreviewGateway } from '../server.mjs'; +import { bodySha256, verifyPreviewProof } from '../proof.mjs'; +const serviceToken='local-fixture-preview-service-token-32-plus',launch='L'.repeat(43),session='S'.repeat(43),probe='P'.repeat(43),challenge='C'.repeat(43); +const listen=async(server,host='127.0.0.1')=>{server.listen(0,host);await once(server,'listening');return server.address().port;}; +const close=server=>new Promise(resolve=>{server.closeAllConnections?.();server.close(resolve);}); +async function fixture({secure=false,entryPath='/'}={}){ + const keys=generateKeyPairSync('ed25519'),privateKey=keys.privateKey.export({type:'pkcs8',format:'pem'}),publicKey=keys.publicKey.export({type:'spki',format:'pem'}); + let authorized=true,role='developer',used=false,expiryOverride;const seen=[],upgraded=new Set(); + const application=http.createServer((req,res)=>{seen.push({headers:req.headers,path:req.url,method:req.method});if(req.url==='/login'&&req.method==='POST'){res.writeHead(200,{'set-cookie':'application_session=logged-in; HttpOnly; Domain=internal.invalid; Path=/'});res.end('logged in');return;}if(req.url==='/account'){res.writeHead(req.headers.cookie==='application_session=logged-in'?200:401,{'content-type':'text/plain'});res.end(req.headers.cookie==='application_session=logged-in'?'private application account':'application login required');return;}if(req.url==='/stream'){res.writeHead(200,{'content-type':'text/plain'});res.write('first');const timer=setInterval(()=>res.write('next'),30);res.on('close',()=>clearInterval(timer));return;}if(req.url==='/redirect'){res.writeHead(302,{location:`http://127.0.0.1:${application.address().port}/actual`});res.end();return;}res.writeHead(req.url==='/app-401'?401:200,{'content-type':'text/plain','x-wishforge-preview-proof':'forged-application-proof','set-cookie':['app=allowed; Domain=internal.invalid; HttpOnly','WF_PREVIEW_SESSION=malicious; Path=/']});res.end('fixture application');}); + application.on('upgrade',(req,socket)=>{seen.push({headers:req.headers,path:req.url,method:'WS'});upgraded.add(socket);socket.on('close',()=>upgraded.delete(socket));const accept=createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n${req.url==='/bad-socket-headers'?'Location: https://external.invalid/\r\n':''}\r\n`);}); + const upstreamPort=await listen(application);let publicOrigin; + const api=http.createServer(async(req,res)=>{let input='';for await(const chunk of req)input+=chunk;const body=JSON.parse(input);if(req.url!=='/preview-control/authorize'||req.headers.authorization!==`Bearer ${serviceToken}`||body.tenantId!=='tenant-a'||body.environmentId!=='environment-a'){res.writeHead(403);res.end('{}');return;}let granted=authorized;if(body.kind==='launch'){granted&&=body.credential===launch&&!used;if(granted)used=true;}else if(body.kind==='probe')granted&&=body.credential===probe&&body.challenge===challenge&&['GET','HEAD'].includes(body.method);else granted&&=body.credential===session&&!(role==='viewer'&&!['GET','HEAD'].includes(body.method));if(!granted){res.writeHead(403);res.end('{}');return;}res.setHeader('content-type','application/json');res.end(JSON.stringify({data:{tenantId:'tenant-a',projectId:'project-a',environmentId:'environment-a',publicOrigin,applicationUrl:publicOrigin+entryPath,role:body.kind==='probe'?'probe':role,releaseId:'release-a',bindingDigest:'sha256:'+ 'a'.repeat(64),policyDigest:'sha256:'+ 'b'.repeat(64),expiresAt:expiryOverride??new Date(Date.now()+60000).toISOString(),...(body.kind==='launch'?{sessionToken:session}:{})}}));}); + const apiPort=await listen(api,'localhost');const reservation=net.createServer();const gatewayPort=await listen(reservation);await close(reservation);const requestOrigin=`http://127.0.0.1:${gatewayPort}`;publicOrigin=`${secure?'https':'http'}://127.0.0.1:${gatewayPort}`; + const gateway=createPreviewGateway({tenantId:'tenant-a',projectId:'project-a',environmentId:'environment-a',publicOrigin,upstreamOrigin:`http://127.0.0.1:${upstreamPort}`,apiOrigin:`http://localhost:${apiPort}`,serviceToken,proofPrivateKey:privateKey,production:false,reauthorizeMs:30});gateway.server.listen(gatewayPort,'127.0.0.1');await once(gateway.server,'listening'); + return{publicOrigin,publicKey,seen,gateway,setRole:value=>{role=value;},setExpiry:value=>{expiryOverride=value;},revoke:()=>{authorized=false;},async launch(){return fetch(`${requestOrigin}/_wishforge/session?code=${launch}`,{redirect:'manual'});},cookie:`${gateway.cookieName}=${session}`,async close(){await gateway.close();for(const socket of upgraded)socket.destroy();await Promise.all([close(application),close(api)]);}}; +} +test('anonymous denial is signed by the gateway and cannot be forged by an application 401',async()=>{const f=await fixture();try{const denied=await fetch(f.publicOrigin+'/app-401',{headers:{'x-wishforge-preview-challenge':challenge}});const body=Buffer.from(await denied.arrayBuffer());assert.equal(denied.status,401);assert.equal(f.seen.length,0);const signed=denied.headers.get('x-wishforge-preview-proof');assert.ok(verifyPreviewProof(f.publicKey,signed,{decision:'anonymous_denied',status:401,path:'/app-401',challenge,publicOrigin:f.publicOrigin,bodySha256:bodySha256(body),releaseId:null}));assert.equal(verifyPreviewProof(f.publicKey,signed,{challenge:'different-challenge'}),undefined);const response=await fetch(f.publicOrigin+'/app-401',{headers:{'x-wishforge-preview-capability':probe,'x-wishforge-preview-challenge':challenge}});const appBody=Buffer.from(await response.arrayBuffer());assert.equal(response.status,401);assert.ok(verifyPreviewProof(f.publicKey,response.headers.get('x-wishforge-preview-proof'),{decision:'authorized',releaseId:'release-a',status:401,bodySha256:bodySha256(appBody)}));assert.equal(verifyPreviewProof(f.publicKey,response.headers.get('x-wishforge-preview-proof'),{decision:'anonymous_denied'}),undefined);}finally{await f.close();}}); +test('launch is one-use, sets host-only HttpOnly cookie, strips credentials and hides upstream redirects',async()=>{const f=await fixture();try{const response=await f.launch();assert.equal(response.status,303);assert.equal(response.headers.get('location'),f.publicOrigin+'/');const cookie=response.headers.get('set-cookie');assert.match(cookie,/HttpOnly/);assert.match(cookie,/SameSite=Lax/);assert.match(cookie,/Path=\//);assert.doesNotMatch(cookie,/Domain=/i);assert.equal((await f.launch()).status,403);const app=await fetch(f.publicOrigin+'/actual',{headers:{cookie:f.cookie+'; app=allowed; WF_OTHER=not-forwarded',authorization:'Bearer user-must-not-reach-app','x-wishforge-service-token':serviceToken}});assert.equal(app.status,200);await app.text();assert.equal(f.seen.at(-1).headers.authorization,undefined);assert.equal(f.seen.at(-1).headers['x-wishforge-service-token'],undefined);assert.equal(f.seen.at(-1).headers.cookie,'app=allowed');assert.doesNotMatch(app.headers.get('set-cookie'),/Domain|WF_PREVIEW_SESSION/i);assert.equal(app.headers.get('x-wishforge-preview-proof'),null);const redirect=await fetch(f.publicOrigin+'/redirect',{headers:{cookie:f.cookie},redirect:'manual'});assert.equal(redirect.headers.get('location'),f.publicOrigin+'/actual');assert.equal(await new Promise((resolve,reject)=>{const request=http.get(f.publicOrigin+'/',{headers:{host:'other-preview.invalid',cookie:f.cookie}},response=>{response.resume();resolve(response.statusCode);});request.on('error',reject);}),421);}finally{await f.close();}}); +test('Viewer reads are permitted but mutations and cross-origin requests are denied',async()=>{const f=await fixture();try{f.setRole('viewer');await f.launch();assert.equal((await fetch(f.publicOrigin+'/',{headers:{cookie:f.cookie}})).status,200);assert.equal((await fetch(f.publicOrigin+'/',{method:'POST',headers:{cookie:f.cookie,origin:f.publicOrigin},body:'unsafe mutation'})).status,403);assert.equal((await fetch(f.publicOrigin+'/',{headers:{cookie:f.cookie,origin:'https://other.preview.invalid'}})).status,403);}finally{await f.close();}}); +test('release probes bind the body, path, challenge, scope and active release, without forwarding capabilities',async()=>{const f=await fixture();try{const response=await fetch(f.publicOrigin+'/business?fixture=1',{headers:{'x-wishforge-preview-capability':probe,'x-wishforge-preview-challenge':challenge,authorization:'Bearer ignored'}});const body=Buffer.from(await response.arrayBuffer());const signed=response.headers.get('x-wishforge-preview-proof');assert.ok(verifyPreviewProof(f.publicKey,signed,{tenantId:'tenant-a',environmentId:'environment-a',releaseId:'release-a',bindingDigest:'sha256:'+'a'.repeat(64),policyDigest:'sha256:'+'b'.repeat(64),decision:'authorized',capabilitySha256:bodySha256(probe),path:'/business?fixture=1',challenge,status:200,bodySha256:bodySha256(body)}));assert.equal(verifyPreviewProof(f.publicKey,signed,{bodySha256:bodySha256('different')}),undefined);assert.equal(f.seen.at(-1).headers['x-wishforge-preview-capability'],undefined);assert.equal(f.seen.at(-1).headers.authorization,undefined);f.revoke();assert.equal((await fetch(f.publicOrigin+'/',{headers:{'x-wishforge-preview-capability':probe,'x-wishforge-preview-challenge':challenge}})).status,403);}finally{await f.close();}}); +test('revocation closes an existing streamed response',async()=>{const f=await fixture();try{await f.launch();const response=await fetch(f.publicOrigin+'/stream',{headers:{cookie:f.cookie}}),reader=response.body.getReader();assert.equal((await reader.read()).done,false);f.revoke();await assert.rejects(async()=>{for(;;){const value=await reader.read();if(value.done)throw new Error('terminated');}},/terminated/);}finally{await f.close();}}); +test('WebSocket proxy requires session and origin, strips credentials, and closes on revocation',async()=>{const f=await fixture();let socket;try{await f.launch();const req=http.request(f.publicOrigin+'/socket',{headers:{connection:'Upgrade',upgrade:'websocket','sec-websocket-version':'13','sec-websocket-key':Buffer.alloc(16).toString('base64'),cookie:f.cookie,origin:f.publicOrigin,authorization:'Bearer not-forwarded'}});const upgraded=once(req,'upgrade');req.end();const [response,peer]=await upgraded;socket=peer;assert.equal(response.statusCode,101);assert.equal(f.seen.at(-1).headers.cookie,undefined);assert.equal(f.seen.at(-1).headers.authorization,undefined);const ended=once(socket,'close');f.revoke();await ended;}finally{socket?.destroy();await f.close();}}); + +test('TLS-terminated preview uses the Secure host-prefix cookie',async()=>{const f=await fixture({secure:true});try{const response=await f.launch();assert.equal(response.status,303);const cookie=response.headers.get('set-cookie');assert.match(cookie,/^__Host-WF_PREVIEW_SESSION=/);assert.match(cookie,/; Secure/);assert.match(cookie,/HttpOnly/);assert.doesNotMatch(cookie,/Domain=/i);}finally{await f.close();}}); + +test('application cookie login survives the proxy without forwarding WishForge credentials',async()=>{const f=await fixture();try{await f.launch();const before=await fetch(f.publicOrigin+'/account',{headers:{cookie:f.cookie}});assert.equal(before.status,401);const login=await fetch(f.publicOrigin+'/login',{method:'POST',headers:{cookie:f.cookie,origin:f.publicOrigin,'content-type':'application/json'},body:JSON.stringify({fixture:true})});assert.equal(login.status,200);const cookie=login.headers.get('set-cookie');assert.match(cookie,/application_session=logged-in/);assert.doesNotMatch(cookie,/Domain=/i);const account=await fetch(f.publicOrigin+'/account',{headers:{cookie:f.cookie+'; '+cookie.split(';')[0]}});assert.equal(account.status,200);assert.equal(await account.text(),'private application account');assert.equal(f.seen.at(-1).headers.cookie,'application_session=logged-in');}finally{await f.close();}}); + +test('launch redirects to the release-bound non-root application entry path',async()=>{const f=await fixture({entryPath:'/catalog/start'});try{const response=await f.launch();assert.equal(response.status,303);assert.equal(response.headers.get('location'),f.publicOrigin+'/catalog/start');}finally{await f.close();}}); + +test('malformed authorization expiry is denied before application forwarding',async()=>{const f=await fixture();try{await f.launch();f.setExpiry('not-a-date');assert.equal((await fetch(f.publicOrigin+'/',{headers:{cookie:f.cookie}})).status,403);assert.equal(f.seen.length,0);}finally{await f.close();}}); + +test('malicious upgrade response headers cannot crash the preview gateway',async()=>{const f=await fixture();try{await f.launch();const status=await new Promise((resolve,reject)=>{const request=http.get(f.publicOrigin+'/bad-socket-headers',{headers:{connection:'Upgrade',upgrade:'websocket','sec-websocket-version':'13','sec-websocket-key':Buffer.alloc(16).toString('base64'),cookie:f.cookie,origin:f.publicOrigin}},response=>{response.resume();resolve(response.statusCode);});request.on('error',reject);});assert.equal(status,502);assert.equal((await fetch(f.publicOrigin+'/',{headers:{cookie:f.cookie}})).status,200);}finally{await f.close();}}); diff --git a/apps/runner/package.json b/apps/runner/package.json new file mode 100644 index 0000000..a57386b --- /dev/null +++ b/apps/runner/package.json @@ -0,0 +1,5 @@ +{ + "name": "@wishforge/runner", "version": "0.1.0", "private": true, "type": "module", + "scripts": { "dev": "tsx src/main.ts", "typecheck": "tsc --noEmit", "test": "vitest run" }, + "dependencies": { "@wishforge/runtime": "*" } +} diff --git a/apps/runner/src/main.ts b/apps/runner/src/main.ts new file mode 100644 index 0000000..129fbc0 --- /dev/null +++ b/apps/runner/src/main.ts @@ -0,0 +1,44 @@ +import type {PrivatePreviewProbe} from '@wishforge/contracts'; +import https from 'node:https'; +import { readFile } from 'node:fs/promises'; +import { ComposeDeploymentAdapter, KubernetesDeploymentAdapter, DeploymentSecretBroker, type SignedRunnerTask,type ReleaseManifest } from '@wishforge/runtime'; +import { OutboundRunner } from './runner.js'; + +async function main() { + const required = ['WF_CONTROL_PLANE_URL','WF_RUNNER_TOKEN','WF_TENANT_ID','WF_ENVIRONMENT_ID','WF_RUNNER_CA','WF_RUNNER_CERT','WF_RUNNER_KEY','WF_RUNNER_PUBLIC_KEYS','WF_RUNNER_STATE_DIR']; + for (const key of required) if (!process.env[key]) throw new Error(`unconfigured: ${key} is required`); + const base = new URL(process.env.WF_CONTROL_PLANE_URL!); + if (base.protocol !== 'https:') throw new Error('Runner only connects to an HTTPS control plane with mTLS'); + const agent = new https.Agent({ ca: await readFile(process.env.WF_RUNNER_CA!), cert: await readFile(process.env.WF_RUNNER_CERT!), key: await readFile(process.env.WF_RUNNER_KEY!), rejectUnauthorized: true }); + const request = (route: string, body?: unknown): Promise => new Promise((resolve, reject) => { + const url = new URL(route, base); + if (url.origin !== base.origin) { reject(new Error('Runner request origin mismatch')); return; } + const req = https.request(url, { agent, method: body ? 'POST' : 'GET', headers: { authorization: `Bearer ${process.env.WF_RUNNER_TOKEN!}`, 'x-wishforge-tenant': process.env.WF_TENANT_ID!, 'content-type': 'application/json' }, timeout: 30_000 }, response => { + let output = ''; response.setEncoding('utf8'); + response.on('data', chunk => { output += chunk; if (output.length > 4 * 1024 * 1024) req.destroy(new Error('Response exceeded limit')); }); + response.on('end', () => { if ((response.statusCode ?? 500) >= 300) reject(new Error(`Control plane returned ${response.statusCode}`)); else { try { resolve(output ? JSON.parse(output) : null); } catch (error) { reject(error); } } }); + }); + req.on('timeout', () => req.destroy(new Error('Control plane request timed out'))); req.on('error', reject); req.end(body ? JSON.stringify(body) : undefined); + }); + let currentTaskId:string|undefined; + const refreshPrivateProbe=async(release:ReleaseManifest):Promise=>{if(!currentTaskId)throw new Error('No active signed runner task for private probe');const value=await request(`/internal/runner/releases/${encodeURIComponent(release.id)}/preview-probe`,{taskId:currentTaskId}) as {data:PrivatePreviewProbe};return value.data;}; + const runner = new OutboundRunner({ tenantId: process.env.WF_TENANT_ID!, environmentId: process.env.WF_ENVIRONMENT_ID!, publicKeys: JSON.parse(await readFile(process.env.WF_RUNNER_PUBLIC_KEYS!, 'utf8')), stateDirectory: process.env.WF_RUNNER_STATE_DIR!, execute: process.env.WF_RUNNER_EXECUTE === 'true', adapters: { + compose: new ComposeDeploymentAdapter({ refreshPrivateProbe, secretBroker:new DeploymentSecretBroker(),dockerConfig:process.env.WF_DEPLOYMENT_DOCKER_CONFIG, directory: process.env.WF_COMPOSE_DIRECTORY, project: process.env.WF_COMPOSE_PROJECT, healthUrl: process.env.WF_HEALTH_URL, dockerContext: process.env.WF_DOCKER_CONTEXT, candidateHealthUrlTemplate: process.env.WF_CANDIDATE_HEALTH_URL_TEMPLATE, proxyAdminUrl: process.env.WF_CADDY_ADMIN_URL, proxyConfigPath: process.env.WF_CADDY_PROXY_CONFIG_PATH, proxyDialHost: process.env.WF_CADDY_DIAL_HOST }), + kubernetes: new KubernetesDeploymentAdapter({ refreshPrivateProbe, secretBroker:new DeploymentSecretBroker(), context: process.env.WF_KUBE_CONTEXT, namespace: process.env.WF_KUBE_NAMESPACE, healthUrl: process.env.WF_HEALTH_URL, candidateHealthUrlTemplate: process.env.WF_CANDIDATE_HEALTH_URL_TEMPLATE }), + } }); + let stopped = false; process.once('SIGTERM', () => { stopped = true; }); process.once('SIGINT', () => { stopped = true; }); + while (!stopped) { + try { + const task = await request(`/internal/runner/tasks?environmentId=${encodeURIComponent(process.env.WF_ENVIRONMENT_ID!)}`) as SignedRunnerTask | null; + if (task) { + currentTaskId=task.payload.id; + const result = await runner.execute(task); + await request(`/internal/runner/tasks/${encodeURIComponent(task.payload.id)}/result`, { result }); + } + } catch (error) { console.error(JSON.stringify({ level: 'error', message: error instanceof Error ? error.message : 'Runner poll failed' })); } + currentTaskId=undefined; + await new Promise(resolve => setTimeout(resolve, 5_000)); + } + agent.destroy(); +} +void main().catch(error => { console.error(error.message); process.exitCode = 1; }); diff --git a/apps/runner/src/runner.ts b/apps/runner/src/runner.ts new file mode 100644 index 0000000..5065d69 --- /dev/null +++ b/apps/runner/src/runner.ts @@ -0,0 +1,37 @@ +import { createHash } from 'node:crypto'; +import { mkdir, open, readFile, rename, unlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { canonicalJson, FileNonceStore, RuntimeError, verifyRunnerTask, type DeploymentAdapter, type DeploymentResult, type SignedRunnerTask } from '@wishforge/runtime'; + +export interface RunnerConfig { tenantId: string; environmentId: string; publicKeys: Record; stateDirectory: string; execute: boolean; adapters: Partial>; } +export class OutboundRunner { + constructor(private readonly config: RunnerConfig) {} + async execute(envelope: SignedRunnerTask): Promise { + const task = verifyRunnerTask(envelope, this.config); + const adapter = this.config.adapters[task.target]; + if (!adapter) throw new RuntimeError('UNCONFIGURED', 'Deployment adapter is not configured'); + await mkdir(this.config.stateDirectory, { recursive: true, mode: 0o700 }); + const digest = createHash('sha256').update(canonicalJson(envelope)).digest('hex'); + const journal = path.join(this.config.stateDirectory, `${task.id}.json`); + try { + const saved = JSON.parse(await readFile(journal, 'utf8')) as { digest: string; result?: DeploymentResult }; + if (saved.digest !== digest) throw new RuntimeError('TASK_ID_REUSE', 'Task ID was reused with a different signed payload'); + if (saved.result) return saved.result; + // A previous attempt may have applied successfully before its receipt was saved. + // Reconcile only; never repeat an ambiguous deployment automatically. + return adapter.reconcile(task.release); + } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } + const lockPath = path.join(this.config.stateDirectory, 'environment.lock'); + const lock = await open(lockPath, 'wx', 0o600).catch(() => { throw new RuntimeError('ENVIRONMENT_BUSY', 'An environment deployment is active; stale locks require operator reconciliation'); }); + try { + const fresh = await new FileNonceStore(path.join(this.config.stateDirectory, 'nonces')).consume(`${task.tenantId}/${task.environmentId}`, task.nonce); + if (!fresh) throw new RuntimeError('TASK_REPLAY', 'Runner task nonce has already been consumed'); + await writeFile(journal, JSON.stringify({ digest, state: 'started' }), { flag: 'wx', mode: 0o600 }); + const output = task.action === 'reconcile' ? await adapter.reconcile(task.release) : await adapter.deploy(task.release, { execute: this.config.execute }); + const temp = `${journal}.tmp`; + await writeFile(temp, JSON.stringify({ digest, state: 'finished', result: output }), { mode: 0o600 }); + await rename(temp, journal); + return output; + } finally { await lock.close(); await unlink(lockPath); } + } +} diff --git a/apps/runner/test/runner.test.ts b/apps/runner/test/runner.test.ts new file mode 100644 index 0000000..cd7dae7 --- /dev/null +++ b/apps/runner/test/runner.test.ts @@ -0,0 +1,26 @@ +import { it, expect } from 'vitest'; +import { generateKeyPairSync } from 'node:crypto'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { canonicalJson, signRunnerTask, type RunnerTask } from '@wishforge/runtime'; +import { createHash } from 'node:crypto'; +import { OutboundRunner } from '../src/runner.js'; + +it('returns a saved receipt on duplicate delivery and reconciles an ambiguous prior operation without redeploying', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'wishforge-runner-')); + try { + const keys = generateKeyPairSync('ed25519'); const now = Date.now(); + const task: RunnerTask = { schemaVersion: 1, id: 'task-1', tenantId: 'tenant', environmentId: 'env', nonce: 'nonce-1', issuedAt: new Date(now).toISOString(), expiresAt: new Date(now + 60_000).toISOString(), action: 'deploy', target: 'compose', release: { schemaVersion: 1, id: 'release', tenantId: 'tenant', environmentId: 'env', sourceCommit: 'a'.repeat(40), image: `registry/web@sha256:${'b'.repeat(64)}`, containerPort: 3000, healthPath: '/health' } }; + let deploys = 0; let reconciles = 0; + const runner = new OutboundRunner({ tenantId: 'tenant', environmentId: 'env', publicKeys: { key: keys.publicKey.export({ type: 'spki', format: 'pem' }).toString() }, stateDirectory: directory, execute: true, adapters: { compose: { render: () => '{}', deploy: async () => { deploys++; return { releaseId: 'release', target: 'compose', status: 'verified', evidence: {} }; }, reconcile: async () => { reconciles++; return { releaseId: 'release', target: 'compose', status: 'applied', evidence: {} }; } } } }); + const envelope = signRunnerTask(task, 'key', keys.privateKey); + expect((await runner.execute(envelope)).status).toBe('verified'); + expect((await runner.execute(envelope)).status).toBe('verified'); + expect(deploys).toBe(1); + const ambiguous = signRunnerTask({ ...task, id: 'task-2', nonce: 'nonce-2' }, 'key', keys.privateKey); + await writeFile(path.join(directory, 'task-2.json'), JSON.stringify({ digest: createHash('sha256').update(canonicalJson(ambiguous)).digest('hex'), state: 'started' })); + expect((await runner.execute(ambiguous)).status).toBe('applied'); + expect(reconciles).toBe(1); expect(deploys).toBe(1); + } finally { await rm(directory, { recursive: true, force: true }); } +}); diff --git a/apps/runner/tsconfig.json b/apps/runner/tsconfig.json new file mode 100644 index 0000000..7f4b8b9 --- /dev/null +++ b/apps/runner/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../../tsconfig.base.json", "compilerOptions": { "noEmit": true, "types": ["node"] }, "include": ["src/**/*.ts", "test/**/*.ts"] } diff --git a/apps/web/design/console-concept.png b/apps/web/design/console-concept.png new file mode 100644 index 0000000..ac850cf Binary files /dev/null and b/apps/web/design/console-concept.png differ diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts new file mode 100644 index 0000000..ce4e94a --- /dev/null +++ b/apps/web/next-env.d.ts @@ -0,0 +1,7 @@ +/// +/// +import "./.next/types/routes.d.ts"; +import "./.next/types/root-params.d.ts"; + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts new file mode 100644 index 0000000..db9a8ea --- /dev/null +++ b/apps/web/next.config.ts @@ -0,0 +1,22 @@ +import type { NextConfig } from "next"; + +const config: NextConfig = { + output: "standalone", + poweredByHeader: false, + agentRules: false, + devIndicators: false, + experimental: { optimizePackageImports: ["lucide-react"] }, + async headers() { + return [ + { + source: "/:path*", + headers: [ + { key: "X-Content-Type-Options", value: "nosniff" }, + { key: "Referrer-Policy", value: "same-origin" }, + { key: "X-Frame-Options", value: "SAMEORIGIN" }, + ], + }, + ]; + }, +}; +export default config; diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..b70962d --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,26 @@ +{ + "name": "@wishforge/web", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev --hostname 127.0.0.1 --port 3000", + "build": "next build", + "start": "next start --hostname 127.0.0.1 --port 3000", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "next": "^16.1.6", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "lucide-react": "^0.577.0", + "swr": "^2.4.1", + "jose": "^6.1.3", + "server-only": "^0.0.1" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@types/react": "^19.2.0", + "@types/react-dom": "^19.2.0", + "typescript": "^5.9.3" + } +} diff --git a/apps/web/src/app/(console)/environments/page.tsx b/apps/web/src/app/(console)/environments/page.tsx new file mode 100644 index 0000000..f509e2c --- /dev/null +++ b/apps/web/src/app/(console)/environments/page.tsx @@ -0,0 +1,4 @@ +import { EnvironmentsView } from "@/features/environments"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/evolution/page.tsx b/apps/web/src/app/(console)/evolution/page.tsx new file mode 100644 index 0000000..056bf55 --- /dev/null +++ b/apps/web/src/app/(console)/evolution/page.tsx @@ -0,0 +1,4 @@ +import { EvolutionView } from "@/features/evolution"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/layout.tsx b/apps/web/src/app/(console)/layout.tsx new file mode 100644 index 0000000..7f1f5be --- /dev/null +++ b/apps/web/src/app/(console)/layout.tsx @@ -0,0 +1,4 @@ +import { ConsoleShell } from "@/components/console-shell"; +export default function Layout({ children }: { children: React.ReactNode }) { + return {children}; +} diff --git a/apps/web/src/app/(console)/page.tsx b/apps/web/src/app/(console)/page.tsx new file mode 100644 index 0000000..76c1b2e --- /dev/null +++ b/apps/web/src/app/(console)/page.tsx @@ -0,0 +1,4 @@ +import { DashboardView } from "@/features/dashboard"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/projects/[id]/page.tsx b/apps/web/src/app/(console)/projects/[id]/page.tsx new file mode 100644 index 0000000..0582b0e --- /dev/null +++ b/apps/web/src/app/(console)/projects/[id]/page.tsx @@ -0,0 +1,9 @@ +import { ProjectView } from "@/features/projects"; +export default async function Page({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + return ; +} diff --git a/apps/web/src/app/(console)/projects/new/page.tsx b/apps/web/src/app/(console)/projects/new/page.tsx new file mode 100644 index 0000000..87efe7a --- /dev/null +++ b/apps/web/src/app/(console)/projects/new/page.tsx @@ -0,0 +1,4 @@ +import { ProjectsView } from "@/features/projects"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/projects/page.tsx b/apps/web/src/app/(console)/projects/page.tsx new file mode 100644 index 0000000..d43a4ea --- /dev/null +++ b/apps/web/src/app/(console)/projects/page.tsx @@ -0,0 +1,4 @@ +import { ProjectsView } from "@/features/projects"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/providers/page.tsx b/apps/web/src/app/(console)/providers/page.tsx new file mode 100644 index 0000000..8fc9884 --- /dev/null +++ b/apps/web/src/app/(console)/providers/page.tsx @@ -0,0 +1,4 @@ +import { ProvidersView } from "@/features/providers"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/releases/page.tsx b/apps/web/src/app/(console)/releases/page.tsx new file mode 100644 index 0000000..d608bca --- /dev/null +++ b/apps/web/src/app/(console)/releases/page.tsx @@ -0,0 +1,4 @@ +import { ReleasesView } from "@/features/releases"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/runs/[id]/page.tsx b/apps/web/src/app/(console)/runs/[id]/page.tsx new file mode 100644 index 0000000..12ebe6d --- /dev/null +++ b/apps/web/src/app/(console)/runs/[id]/page.tsx @@ -0,0 +1,9 @@ +import { RunDetailView } from "@/features/runs"; +export default async function Page({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + return ; +} diff --git a/apps/web/src/app/(console)/runs/new/page.tsx b/apps/web/src/app/(console)/runs/new/page.tsx new file mode 100644 index 0000000..08ba67d --- /dev/null +++ b/apps/web/src/app/(console)/runs/new/page.tsx @@ -0,0 +1,4 @@ +import { NewWishView } from "@/features/runs"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/runs/page.tsx b/apps/web/src/app/(console)/runs/page.tsx new file mode 100644 index 0000000..c372974 --- /dev/null +++ b/apps/web/src/app/(console)/runs/page.tsx @@ -0,0 +1,4 @@ +import { RunsView } from "@/features/runs"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/(console)/usage/page.tsx b/apps/web/src/app/(console)/usage/page.tsx new file mode 100644 index 0000000..fc12037 --- /dev/null +++ b/apps/web/src/app/(console)/usage/page.tsx @@ -0,0 +1,4 @@ +import { UsageView } from "@/features/usage"; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/api/[...path]/route.ts b/apps/web/src/app/api/[...path]/route.ts new file mode 100644 index 0000000..7d1ea9c --- /dev/null +++ b/apps/web/src/app/api/[...path]/route.ts @@ -0,0 +1,113 @@ +import { NextRequest, NextResponse } from "next/server"; +import { publicOrigin, tokenFor } from "@/lib/auth"; +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; +type Context = { params: Promise<{ path: string[] }> }; +async function proxy(request: NextRequest, context: Context) { + const { path } = await context.params; + if ( + path.some( + (part) => + !part || + part === ".." || + part === "." || + part.includes("/") || + part.includes("\\"), + ) + ) + return NextResponse.json( + { error: { code: "INVALID_PATH", message: "无效的 API 路径。" } }, + { status: 400 }, + ); + if (!["GET", "HEAD"].includes(request.method)) { + const origin = request.headers.get("origin"); + if ( + (origin && origin !== publicOrigin(request)) || + request.headers.get("sec-fetch-site") === "cross-site" + ) + return NextResponse.json( + { error: { code: "ORIGIN_DENIED", message: "请求来源不被允许。" } }, + { status: 403 }, + ); + } + const token = await tokenFor(request); + if (!token) + return NextResponse.json( + { + error: { + code: "UNAUTHENTICATED", + message: "需要有效的工作空间登录会话。", + }, + }, + { status: 401 }, + ); + const base = (process.env.WF_API_URL ?? "http://127.0.0.1:4000").replace( + /\/$/, + "", + ); + const url = `${base}/v1/${path.map(encodeURIComponent).join("/")}${request.nextUrl.search}`; + const headers = new Headers({ Authorization: `Bearer ${token}` }); + for (const key of [ + "content-type", + "accept", + "idempotency-key", + "last-event-id", + ]) { + const value = request.headers.get(key); + if (value) headers.set(key, value); + } + const stream = path.at(-1) === "stream"; + try { + const upstream = await fetch(url, { + method: request.method, + headers, + body: ["GET", "HEAD"].includes(request.method) + ? undefined + : await request.arrayBuffer(), + cache: "no-store", + redirect: "manual", + signal: stream + ? request.signal + : AbortSignal.any([request.signal, AbortSignal.timeout(30000)]), + }); + if (upstream.status >= 300 && upstream.status < 400) + return NextResponse.json( + { + error: { + code: "UPSTREAM_REDIRECT", + message: "控制面返回了意外重定向。", + }, + }, + { status: 502 }, + ); + const responseHeaders = new Headers({ + "Cache-Control": "no-store", + "Content-Type": + upstream.headers.get("content-type") ?? "application/json", + }); + if (stream) { + responseHeaders.set("X-Accel-Buffering", "no"); + responseHeaders.set("Connection", "keep-alive"); + } + return new Response(upstream.body, { + status: upstream.status, + headers: responseHeaders, + }); + } catch { + return NextResponse.json( + { + error: { + code: "CONTROL_PLANE_UNAVAILABLE", + message: "无法连接控制面。请检查服务地址与运行状态。", + }, + }, + { status: 502 }, + ); + } +} +export const GET = proxy; +export const POST = proxy; +export const PATCH = proxy; +export const PUT = proxy; +export const DELETE = proxy; +export const HEAD = proxy; diff --git a/apps/web/src/app/api/session/route.ts b/apps/web/src/app/api/session/route.ts new file mode 100644 index 0000000..698553e --- /dev/null +++ b/apps/web/src/app/api/session/route.ts @@ -0,0 +1,16 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getSession, isDevelopmentAuth, oidcConfigured } from "@/lib/auth"; +export async function GET(request: NextRequest) { + const session = await getSession(request); + return NextResponse.json( + { + data: { + authenticated: isDevelopmentAuth() || Boolean(session), + mode: isDevelopmentAuth() ? "development" : "oidc", + name: session?.name, + oidcConfigured: oidcConfigured(), + }, + }, + { headers: { "Cache-Control": "no-store" } }, + ); +} diff --git a/apps/web/src/app/delivery/[environmentId]/launch/route.ts b/apps/web/src/app/delivery/[environmentId]/launch/route.ts new file mode 100644 index 0000000..09b99c7 --- /dev/null +++ b/apps/web/src/app/delivery/[environmentId]/launch/route.ts @@ -0,0 +1,57 @@ +import { NextRequest, NextResponse } from "next/server"; +import { tokenFor } from "@/lib/auth"; +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ environmentId: string }> }, +) { + const token = await tokenFor(request); + if (!token) return NextResponse.redirect(new URL( + `/login?returnTo=${encodeURIComponent(request.nextUrl.pathname)}`, + request.nextUrl.origin, + )); + const { environmentId } = await params; + const api = (process.env.WF_API_URL ?? "http://127.0.0.1:4000").replace(/\/$/, ""); + try { + const response = await fetch(`${api}/v1/environments/${encodeURIComponent(environmentId)}/preview-launch`, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify({}), cache: "no-store", redirect: "error", + signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]), + }); + if (!response.ok) return NextResponse.json({ error: { + code: "PRIVATE_DELIVERY_DENIED", + message: response.status === 403 ? "你没有权限访问此私有成果。" : + response.status === 401 ? "登录凭据已失效,请重新登录后访问私有成果。" : + "私有成果尚未就绪或访问配置不可用。", + } }, { status: response.status, headers: { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" } }); + const payload = (await response.json()) as { + data?: { launchUrl?: string; expiresAt?: string; visibility?: string }; + }; + const expiresAt = Date.parse(payload.data?.expiresAt ?? ""); + if (payload.data?.visibility !== "private" || typeof payload.data.launchUrl !== "string" || + !Number.isFinite(expiresAt) || expiresAt <= Date.now() || expiresAt > Date.now() + 60000) { + throw new Error("Invalid private delivery authorization"); + } + // The authenticated control plane owns environment routing and validates its + // dedicated origin. No gateway map or gateway credential belongs in this BFF. + const url = new URL(payload.data.launchUrl); + const localHttp = process.env.NODE_ENV !== "production" && url.protocol === "http:" && + ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + const keys = [...url.searchParams.keys()]; + if ((url.protocol !== "https:" && !localHttp) || url.username || url.password || url.hash || + url.pathname !== "/_wishforge/session" || keys.length !== 1 || keys[0] !== "code" || + !/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code") ?? "")) { + throw new Error("Invalid private delivery redirect"); + } + const result = NextResponse.redirect(url, 303); + result.headers.set("Cache-Control", "no-store"); + result.headers.set("Referrer-Policy", "no-referrer"); + return result; + } catch { + return NextResponse.json({ error: { code: "PRIVATE_DELIVERY_UNAVAILABLE", message: "无法取得私有成果访问授权,请稍后重试。" } }, { + status: 503, headers: { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }, + }); + } +} diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css new file mode 100644 index 0000000..47eda50 --- /dev/null +++ b/apps/web/src/app/globals.css @@ -0,0 +1,2655 @@ +:root { + --navy: #102031; + --navy-light: #1b3443; + --bg: #f8fafc; + --surface: #fff; + --ink: #122033; + --muted: #77869d; + --border: #e1e7ef; + --teal: #168574; + --teal-dark: #116d60; + --teal-pale: #eaf5f1; + --amber: #b77a17; + --red: #be444c; + --radius: 7px; + --sidebar: 248px; + --font: + "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", + "Microsoft YaHei", sans-serif; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: var(--bg); + color: var(--ink); + font-family: var(--font); + font-size: 14px; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} +button, +input, +textarea, +select { + font: inherit; +} +button, +a, +input, +textarea, +select { + -webkit-tap-highlight-color: transparent; +} +a { + color: inherit; + text-decoration: none; +} +button { + cursor: pointer; +} +button:disabled { + cursor: not-allowed; + opacity: 0.55; +} +svg { + flex-shrink: 0; + vertical-align: middle; +} +h1, +h2, +h3, +p { + margin: 0; +} +h1 { + font-size: 34px; + line-height: 1.3; + letter-spacing: -1px; + font-weight: 700; +} +h2 { + font-size: 16px; + font-weight: 600; + line-height: 1.5; +} +h3 { + font-size: 14px; + line-height: 1.5; + font-weight: 600; +} +code, +pre { + font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace; + font-size: 12px; +} +button:focus-visible, +a:focus-visible, +input:focus-visible, +textarea:focus-visible, +select:focus-visible, +summary:focus-visible { + outline: 3px solid #78c7b7; + outline-offset: 3px; +} +::selection { + background: #c9e8e0; +} +input, +select, +textarea { + border: 1px solid #d8e0ea; + background: white; + color: var(--ink); + border-radius: 6px; + min-height: 42px; + padding: 10px 12px; + font-size: 14px; + line-height: 1.5; + transition: + border-color 0.15s, + box-shadow 0.15s; +} +input:hover, +select:hover, +textarea:hover { + border-color: #b4c1d0; +} +input:focus, +select:focus, +textarea:focus { + border-color: var(--teal); + box-shadow: 0 0 0 3px #1685740c; + outline: none; +} +input::placeholder, +textarea::placeholder { + color: #9aa6b8; +} +textarea { + resize: vertical; + min-height: 90px; +} +select { + cursor: pointer; +} +small { + font-size: 12px; +} +ul, +ol { + margin: 0; + padding: 0; +} +button { + border: none; + background: none; + color: inherit; +} +.muted { + color: var(--muted); +} +.text-small { + font-size: 12px; +} +.nowrap { + white-space: nowrap; +} +.break-all { + overflow-wrap: anywhere; +} +.sr-only { + position: absolute; + left: 0; + top: 0; + width: 1px; + height: 1px; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); +} +.inline-icon { + display: inline-flex; + align-items: center; + gap: 7px; +} +.spin { + animation: spin 1.1s linear infinite; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} +.skip-link { + position: fixed; + top: -80px; + left: 20px; + background: white; + padding: 10px; + z-index: 1000; +} +.skip-link:focus { + top: 8px; +} +.sidebar { + position: fixed; + inset: 0 auto 0 0; + width: var(--sidebar); + background: var(--navy); + color: #d7e0eb; + display: flex; + flex-direction: column; + z-index: 50; + padding: 0 12px; +} +.brand { + display: flex; + align-items: center; + gap: 18px; + padding: 16px 15px 23px; + color: #f8fafc; +} +.brand strong { + font-size: 24px; + line-height: 1.25; + display: block; + letter-spacing: -0.6px; +} +.brand small { + font-size: 10px; + letter-spacing: 1.1px; + color: #aebccb; + display: block; + margin-top: 4px; +} +.sidebar nav { + display: flex; + flex-direction: column; + gap: 8px; +} +.nav-link { + height: 46px; + display: flex; + align-items: center; + gap: 20px; + padding: 0 16px; + border-left: 3px solid transparent; + border-radius: 6px; + font-size: 14px; + transition: + background 0.15s, + color 0.15s; +} +.nav-link:hover { + background: #ffffff09; + color: white; +} +.nav-link.active { + color: #eefdfa; + background: #1c3a45; + border-left-color: #58c9ac; + font-weight: 600; +} +.sidebar-bottom { + display: flex; + align-items: center; + gap: 18px; + margin-top: auto; + border-top: 1px solid #314151; + padding: 22px 14px 28px; +} +.sidebar-bottom span { + flex: 1; +} +.sidebar-bottom small { + display: block; + font-size: 10px; + letter-spacing: 0.5px; +} +.sidebar-bottom strong { + display: block; + font-size: 12px; + font-weight: 400; + margin-top: 3px; +} +.main-shell { + margin-left: var(--sidebar); + min-height: 100vh; + display: flex; + flex-direction: column; +} +.topbar { + height: 58px; + border-bottom: 1px solid var(--border); + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 30px; + background: #fbfcfe; +} +.breadcrumb { + display: flex; + align-items: center; + gap: 14px; + font-size: 13px; + color: #8190a7; +} +.breadcrumb strong { + color: #344357; + font-weight: 500; +} +.slash { + color: #b3bfce; +} +.topbar-actions { + display: flex; + align-items: center; + gap: 16px; +} +.topbar-divider { + height: 22px; + width: 1px; + background: var(--border); +} +.mode-badge { + font-size: 11px; + color: #5e605d; + padding: 4px 11px; + background: #fffaf0; + border: 1px solid #f1e5cf; + border-radius: 20px; + display: flex; + align-items: center; + gap: 7px; +} +.mode-badge i { + width: 8px; + height: 8px; + background: #f2b449; + border-radius: 50%; +} +.icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 5px; + color: #405168; + transition: background 0.15s; +} +.icon-button:hover { + background: #eaf0f5; +} +.main-content { + padding: 27px 30px 20px; + max-width: 1680px; + width: 100%; + margin: 0 auto; + flex: 1; +} +.page-header { + margin-bottom: 23px; +} +.page-heading-row { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 20px; +} +.page-header p { + color: #7a89a0; + font-size: 15px; + margin-top: 5px; + line-height: 1.7; + max-width: 820px; +} +.page-header .button { + flex-shrink: 0; +} +.page-heading-row > .button { + margin-top: 7px; + min-height: 48px; + padding: 11px 22px; + font-size: 14px; +} +.back-link { + display: inline-flex; + align-items: center; + gap: 5px; + font-size: 12px; + color: var(--muted); + margin: 0 0 10px; +} +.footer { + display: flex; + justify-content: space-between; + margin: 0 30px; + padding: 12px 0 18px; + color: #99a4b5; + font-size: 11px; +} +.footer span:first-child { + font-weight: 600; + letter-spacing: 0.2px; +} +.mobile-menu, +.mobile-close { + display: none; +} +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 9px; + min-height: 41px; + padding: 9px 17px; + font-size: 13px; + font-weight: 600; + border-radius: 6px; + line-height: 1.5; + white-space: nowrap; + transition: + background 0.15s, + border-color 0.15s, + transform 0.15s; + border: 1px solid transparent; +} +.button-primary { + color: #fff; + background: var(--teal); + border-color: var(--teal); +} +.button-primary:hover:not(:disabled) { + background: var(--teal-dark); + border-color: var(--teal-dark); +} +.button-secondary { + border-color: #dce4ec; + background: #fff; + color: #33455a; +} +.button-secondary:hover:not(:disabled) { + background: #f2f6f8; + border-color: #bdcbd7; +} +.button-ghost { + color: #68768a; + background: transparent; +} +.button-ghost:hover:not(:disabled) { + background: #edf2f6; +} +.button-danger { + color: #b13d49; + border-color: #efd6da; + background: #fff5f5; +} +.button-danger:hover:not(:disabled) { + background: #ffe9ec; +} +.button-group { + display: flex; + align-items: center; + gap: 8px; +} +.text-link { + display: inline-flex; + align-items: center; + gap: 7px; + color: #344b67; + font-size: 12px; + line-height: 1.5; + cursor: pointer; + padding: 0; +} +.text-link:hover { + color: var(--teal); +} +.subtle-link { + display: inline-flex; + align-items: center; + gap: 5px; + color: #78889c; + font-size: 12px; +} +.subtle-link:hover { + color: var(--teal); +} +.panel { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + min-width: 0; + overflow: hidden; + margin-bottom: 18px; +} +.panel-heading { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + padding: 19px 22px 15px; +} +.panel-heading h2 { + font-size: 16px; +} +.metrics-strip { + display: flex; + border: 1px solid var(--border); + border-radius: var(--radius); + background: white; + padding: 18px 0; + margin-bottom: 17px; +} +.metric { + flex: 1; + padding: 4px 29px; + min-width: 0; +} +.metric + .metric { + border-left: 1px solid var(--border); +} +.metric h2 { + font-size: 13px; + font-weight: 600; +} +.metric strong { + display: block; + font-size: 29px; + line-height: 1.4; + font-weight: 500; + margin: 6px 0; +} +.metric p { + font-size: 12px; + color: #8190a6; +} +.dashboard-columns { + display: grid; + grid-template-columns: 1.68fr 1fr; + gap: 17px; + align-items: stretch; +} +.recent-panel { + min-height: 480px; +} +.recent-panel .empty-state { + min-height: 370px; +} +.journey-panel { + padding-bottom: 11px; +} +.journey { + list-style: none; + padding: 0 24px; +} +.journey li { + display: flex; + gap: 24px; + min-height: 82px; + position: relative; +} +.journey li:last-child { + min-height: 62px; +} +.journey li:not(:last-child):before { + content: ""; + position: absolute; + top: 33px; + bottom: 7px; + left: 15px; + border-left: 1px dashed #c6d4e3; +} +.journey-number { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border: 1px solid #d8e2ed; + border-radius: 50%; + background: #f7f9fc; + font-size: 15px; +} +.journey li h3 { + font-size: 13px; + margin: 3px 0 3px; +} +.journey li p { + font-size: 12px; + color: #8291a8; + line-height: 1.65; + max-width: 290px; +} +.connection-note { + margin: 2px 12px 0; + border: 1px solid #f5e8d1; + border-radius: 6px; + background: #fffbf4; + display: flex; + gap: 12px; + padding: 11px 13px; + align-items: center; + color: #c48a28; +} +.connection-note div { + flex: 1; +} +.connection-note strong { + display: block; + font-size: 12px; + color: #775827; +} +.connection-note p { + font-size: 10px; + color: #969184; + line-height: 1.5; + margin-top: 2px; +} +.connection-note a { + color: #445369; +} +.connection-note.connected { + background: #f3faf7; + border-color: #d9ebe3; + color: var(--teal); +} +.connection-note.connected strong { + color: #2b6d5d; +} +.onboarding-panel .panel-heading { + padding-bottom: 10px; +} +.onboarding { + display: flex; + padding: 0 20px 18px; +} +.onboarding > a { + display: flex; + gap: 15px; + align-items: flex-start; + flex: 1; + min-width: 0; + padding: 4px 13px 3px 1px; +} +.onboarding > a + a { + border-left: 1px solid var(--border); + padding-left: 23px; +} +.onboarding-number { + font-size: 12px; + color: #6f83a0; + line-height: 24px; +} +.onboarding > a > svg { + margin-top: 2px; +} +.onboarding h3 { + font-size: 13px; +} +.onboarding p { + font-size: 11px; + color: #8190a6; + line-height: 1.8; + margin-top: 4px; +} +.onboarding > a:hover h3 { + color: var(--teal); +} +.onboarding-arrow { + display: none; +} +.table-scroll { + position: relative; + overflow-x: auto; + width: 100%; + padding: 0 21px 6px; +} +.data-table { + border-collapse: collapse; + text-align: left; + width: 100%; + font-size: 12px; +} +.data-table th { + font-size: 11px; + font-weight: 500; + color: #697a93; + background: #f6f8fb; + border-top: 1px solid #eef2f6; + border-bottom: 1px solid #eef2f6; + padding: 12px 17px; + white-space: nowrap; +} +.data-table th:first-child { + border-radius: 5px 0 0 5px; +} +.data-table th:last-child { + border-radius: 0 5px 5px 0; +} +.data-table td { + border-bottom: 1px solid #edf1f5; + padding: 17px; + vertical-align: middle; + max-width: 360px; +} +.data-table tbody tr:last-child td { + border-bottom: 0; +} +.data-table tbody tr:hover { + background: #fbfcfe; +} +.row-title { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + font-size: 13px; + line-height: 1.6; + font-weight: 500; + min-width: 180px; + max-width: 440px; +} +.row-title:hover { + color: var(--teal); +} +.row-meta { + display: flex; + align-items: center; + gap: 10px; + margin-top: 7px; +} +.row-meta code { + font-size: 10px; + color: #98a3b3; +} +.stage-label { + white-space: nowrap; + color: #54667e; +} +.status { + display: inline-flex; + align-items: center; + gap: 5px; + white-space: nowrap; + line-height: 1.5; + font-size: 11px; + padding: 3px 7px; + border-radius: 5px; + background: #f0f3f6; + color: #758298; +} +.status > span { + height: 5px; + width: 5px; + border-radius: 50%; + background: currentColor; +} +.status-teal, +.status-green { + color: #287d6e; + background: #eaf6f1; +} +.status-amber { + color: #a87921; + background: #fff6e5; +} +.status-red { + color: #b64c57; + background: #fff0f0; +} +.empty-state { + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + text-align: center; + padding: 50px 24px; + min-height: 285px; +} +.empty-state.compact { + min-height: 195px; + padding: 30px; +} +.empty-icon { + color: #91a4bc; + margin-bottom: 20px; +} +.empty-state h3 { + font-size: 17px; + font-weight: 600; + margin-bottom: 7px; +} +.empty-state p { + font-size: 13px; + color: #8492a7; + line-height: 1.8; + max-width: 400px; +} +.empty-state .button { + margin-top: 20px; +} +.loading-state { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + color: #7c8aa0; + padding: 65px 20px; + min-height: 170px; +} +.notice { + display: flex; + align-items: flex-start; + gap: 12px; + padding: 14px 17px; + border: 1px solid #dce6ee; + border-radius: 6px; + background: #f2f7fa; + color: #62758b; + font-size: 12px; + line-height: 1.7; + margin-bottom: 18px; +} +.notice > svg { + margin-top: 2px; +} +.notice > div { + flex: 1; + min-width: 0; +} +.notice strong { + font-weight: 600; + display: block; + color: #3a4f66; +} +.notice p { + font-size: 12px; + margin-top: 2px; +} +.notice .text-link { + align-self: center; + white-space: nowrap; +} +.notice-error { + background: #fff7f6; + border-color: #f1dad6; + color: #af6b63; +} +.notice-error strong { + color: #8e4c46; +} +.notice-warning { + background: #fffbf2; + border-color: #f2e5ce; + color: #8f7348; +} +.notice-success { + background: #f0f9f4; + border-color: #d2eade; + color: #337a60; +} +.list-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 20px 22px; + border-bottom: 1px solid var(--border); +} +.search-field { + display: flex; + align-items: center; + border: 1px solid #dfe5ec; + border-radius: 6px; + padding-left: 12px; + color: #8b9bb0; + width: 320px; + max-width: 100%; + background: white; +} +.search-field input { + border: 0; + min-height: 35px; + box-shadow: none; + width: 100%; + font-size: 12px; + padding: 8px 10px; + background: transparent; +} +.search-field:focus-within { + border-color: var(--teal); +} +.filter-controls { + display: flex; + gap: 10px; +} +.filter-controls select { + font-size: 12px; + min-height: 36px; + padding: 7px 26px 7px 10px; +} +.project-list { + padding: 0 22px; +} +.project-row { + display: flex; + align-items: center; + gap: 19px; + padding: 25px 0; + border-bottom: 1px solid #eaf0f4; +} +.project-row:last-child { + border-bottom: 0; +} +.project-mark, +.release-mark, +.provider-mark { + display: flex; + align-items: center; + justify-content: center; + width: 46px; + height: 46px; + background: #f2f6f8; + color: #4a6a7d; + border: 1px solid #e4ebf0; + border-radius: 9px; + flex-shrink: 0; +} +.project-information { + min-width: 0; + flex: 1; +} +.project-information h2 { + font-size: 15px; +} +.project-information p { + font-size: 12px; + color: #8a98ab; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin-top: 4px; +} +.project-row:hover h2 { + color: var(--teal); +} +.project-row > time { + font-size: 12px; +} +.project-branch { + display: flex; + align-items: center; + gap: 7px; + color: #5f7289; + font-size: 12px; + padding: 4px 9px; + background: #f6f8fb; + border-radius: 5px; +} +.project-row > svg { + margin-left: 10px; + color: #8c9aab; +} +.detail-columns { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 18px; +} +.details-list { + margin: 0; + padding: 0 22px 20px; +} +.key-value { + display: grid; + grid-template-columns: 110px minmax(0, 1fr); + align-items: start; + gap: 20px; + padding: 10px 0; + font-size: 12px; +} +.key-value dt { + color: #8591a3; +} +.key-value dd { + margin: 0; + overflow-wrap: anywhere; +} +.panel-intro { + color: #7b8a9e; + font-size: 12px; + padding: 0 22px 17px; + line-height: 1.8; +} +.panel > .notice { + margin: 0 20px 12px; +} +.panel > .field-hint { + padding: 0 22px 15px; +} +.panel-bottom-action { + padding: 0 22px 20px; +} +.panel-note { + font-size: 11px; + color: #92a0b1; + padding: 14px 22px; + border-top: 1px solid #edf1f5; +} +.workspace-list { + padding: 0 22px 20px; +} +.workspace-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + margin-bottom: 10px; +} +.workspace-row strong { + font-size: 13px; + display: block; +} +.workspace-row .status { + margin-top: 5px; +} +.workspace-row p { + font-size: 12px; + color: #8695a7; + margin-top: 5px; +} +.workspace-row > span { + font-size: 12px; +} +.form-columns { + display: grid; + grid-template-columns: minmax(0, 1.7fr) minmax(250px, 1fr); + gap: 45px; + align-items: start; +} +.wish-form-panel { + padding: 27px; +} +.form-stack { + display: flex; + flex-direction: column; + gap: 19px; +} +.form-section + .form-section { + border-top: 1px solid var(--border); + padding-top: 23px; +} +.form-section h2 { + font-size: 15px; + margin-bottom: 19px; +} +.form-section .field + .field { + margin-top: 20px; +} +.field { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} +.field-label { + font-size: 12px; + color: #41536b; + font-weight: 500; +} +.field-hint { + font-size: 11px; + line-height: 1.7; + color: #8b99ab; +} +.field input, +.field select, +.field textarea { + width: 100%; +} +.form-pair { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 17px; +} +.budget-fields { + display: grid; + grid-template-columns: 1.1fr 1fr 0.8fr; + gap: 14px; + margin-top: 20px; +} +.form-section .budget-fields .field { + margin-top: 0; +} +.form-section .notice { + margin-top: 15px; + margin-bottom: 0; +} +.form-submit { + display: flex; + align-items: center; + justify-content: space-between; + gap: 15px; + border-top: 1px solid var(--border); + padding-top: 20px; +} +.form-submit p { + font-size: 11px; + color: #93a0b0; +} +.form-guide { + padding: 30px 10px; + max-width: 345px; +} +.guide-glyph { + display: block; + color: var(--teal); + margin-bottom: 22px; +} +.form-guide h2 { + font-size: 24px; + line-height: 1.7; + letter-spacing: -0.5px; + font-weight: 500; + margin-bottom: 14px; +} +.form-guide > p { + font-size: 13px; + color: #8a99ac; + line-height: 1.9; +} +.form-guide ol { + list-style: none; + margin-top: 30px; + counter-reset: guide; +} +.form-guide li { + counter-increment: guide; + padding: 0 0 22px 35px; + position: relative; +} +.form-guide li:before { + content: "0" counter(guide); + position: absolute; + left: 0; + top: 1px; + font-size: 11px; + color: #89a99e; +} +.form-guide li strong { + display: block; + font-size: 12px; + font-weight: 600; +} +.form-guide li span { + display: block; + font-size: 12px; + color: #8d9aaa; + margin-top: 3px; +} +.form-guide .guide-footnote { + font-size: 11px; + padding-top: 10px; + border-top: 1px solid var(--border); +} +.form-error, +.form-success { + display: flex; + align-items: flex-start; + gap: 8px; + font-size: 12px; + line-height: 1.7; + padding: 11px 13px; + border-radius: 5px; + overflow-wrap: anywhere; +} +.form-error { + background: #fff0f0; + color: #af4451; + border: 1px solid #f0d7dc; +} +.form-success { + background: #edf8f1; + color: #2b7b58; +} +.form-error > svg, +.form-success > svg { + margin-top: 3px; +} +.panel > .form-error { + margin: 0 20px 20px; +} +.modal { + border: 1px solid #d9e2e9; + border-radius: 12px; + box-shadow: 0 24px 100px #0b1b3740; + padding: 0; + width: min(560px, calc(100% - 32px)); + max-height: 90vh; + color: var(--ink); + background: white; +} +.modal::backdrop { + background: #0a192c74; + backdrop-filter: blur(3px); +} +.modal-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 20px; + padding: 25px 27px 18px; + border-bottom: 1px solid var(--border); +} +.modal-header h2 { + font-size: 20px; + font-weight: 600; +} +.modal-header p { + font-size: 12px; + color: #8493a8; + margin-top: 6px; +} +.modal-header .icon-button { + margin: -5px -7px 0 0; +} +.modal > .form-stack, +.modal-body { + padding: 23px 27px 26px; +} +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + padding-top: 14px; + margin-top: 6px; +} +.modal .notice { + margin-bottom: 0; +} +.modal .release-binding { + padding: 15px 0; +} +.modal .key-value { + font-size: 11px; + grid-template-columns: 85px minmax(0, 1fr); + gap: 12px; +} +.modal .key-value code { + font-size: 10px; +} +.modal .key-value ul { + padding-left: 16px; +} +.checkbox-label { + display: flex; + align-items: flex-start; + gap: 10px; + font-size: 12px; + line-height: 1.8; + background: #f6f9fb; + border: 1px solid var(--border); + border-radius: 5px; + padding: 12px; + margin: 10px 0 15px; +} +.checkbox-label input { + appearance: auto; + min-height: auto; + margin: 4px 0 0; + accent-color: var(--teal); + width: 15px; + height: 15px; +} +.cancel-goal { + font-size: 14px; + padding: 0 0 10px; +} +.run-identification { + display: flex; + gap: 18px; + align-items: center; + margin-top: -10px; + margin-bottom: 23px; + font-size: 11px; + color: #8592a6; + flex-wrap: wrap; +} +.run-identification code { + font-size: 11px; +} +.stage-rail { + display: flex; + overflow-x: auto; + gap: 5px; + background: white; + border: 1px solid var(--border); + border-radius: 7px; + padding: 20px 18px; + margin-bottom: 22px; +} +.stage-step { + display: flex; + align-items: center; + gap: 9px; + flex: 1; + white-space: nowrap; + color: #96a3b5; + font-size: 11px; +} +.stage-step > span { + width: 24px; + height: 24px; + background: #f0f3f7; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 10px; + flex-shrink: 0; +} +.stage-step strong { + font-weight: 500; +} +.stage-step > svg { + margin-left: auto; + color: #c2cbd7; +} +.stage-step.current { + color: var(--teal); +} +.stage-step.current > span { + color: white; + background: var(--teal); +} +.stage-step.complete { + color: #578c79; +} +.stage-step.complete > span { + background: #eaf4ef; + color: #4f9076; +} +.tabs { + display: flex; + gap: 28px; + border-bottom: 1px solid var(--border); + margin-bottom: 20px; +} +.tabs button { + font-size: 13px; + color: #8190a6; + padding: 11px 0 13px; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + display: flex; + align-items: center; + gap: 7px; +} +.tabs button.active { + color: #187e6e; + border-bottom-color: var(--teal); + font-weight: 600; +} +.tabs button span { + font-size: 10px; + background: #edf2f6; + padding: 0 5px; + border-radius: 3px; +} +.acceptance-list { + list-style: none; + padding: 0 22px 15px; +} +.acceptance-list li { + display: flex; + gap: 14px; + padding: 13px 0; + border-bottom: 1px solid #edf1f6; +} +.acceptance-list li:last-child { + border: 0; +} +.acceptance-list li > span { + font-size: 10px; + color: #8b9aae; + border: 1px solid #dfe6ed; + height: 23px; + min-width: 23px; + text-align: center; + line-height: 21px; + border-radius: 4px; + margin-top: 1px; +} +.acceptance-list li p { + font-size: 13px; + line-height: 1.8; +} +.answer-panel > p { + padding: 0 22px 15px; + color: #78889f; + font-size: 13px; +} +.answer-panel form { + padding: 0 22px 20px; + display: flex; + gap: 15px; + align-items: flex-end; +} +.answer-panel textarea { + flex: 1; + min-width: 0; +} +.event-list { + list-style: none; + padding: 5px 25px 20px; +} +.event-list li { + position: relative; + display: flex; + gap: 18px; + padding-bottom: 24px; +} +.event-list li:not(:last-child):before { + content: ""; + position: absolute; + top: 10px; + bottom: 0; + left: 4px; + border-left: 1px solid #e1e8ee; +} +.event-dot { + width: 9px; + height: 9px; + border: 2px solid #78a99e; + border-radius: 50%; + background: white; + position: relative; + margin-top: 6px; + flex-shrink: 0; +} +.event-body { + min-width: 0; + flex: 1; +} +.event-meta { + display: flex; + align-items: center; + gap: 10px; + font-size: 10px; + color: #90a0b4; + margin-bottom: 7px; +} +.event-meta time { + margin-left: auto; +} +.event-meta code { + font-size: 10px; + color: #647c94; +} +.event-body > p { + font-size: 13px; + line-height: 1.8; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.json-details { + margin-top: 8px; +} +.json-details summary { + font-size: 11px; + color: #8393a8; + cursor: pointer; + list-style: disclosure-closed; +} +.json-details[open] summary { + list-style: disclosure-open; +} +.json-details pre, +.artifact-content { + font-size: 11px; + background: #f6f8fb; + border: 1px solid #e8edf3; + border-radius: 5px; + padding: 13px; + overflow: auto; + max-height: 340px; + white-space: pre-wrap; + overflow-wrap: anywhere; + color: #52657d; + line-height: 1.7; + margin-bottom: 0; +} +.artifact-list { + padding: 0 23px 20px; +} +.artifact-list article { + display: flex; + gap: 17px; + border-top: 1px solid var(--border); + padding: 20px 0; +} +.artifact-list article > svg { + color: #829ab1; + margin-top: 2px; +} +.artifact-list article > div { + flex: 1; + min-width: 0; +} +.artifact-list h3 { + font-size: 13px; +} +.artifact-list .muted { + margin: 4px 0 7px; +} +.artifact-list article > .text-link { + align-self: flex-start; + white-space: nowrap; +} +.release-list { + padding: 0 22px 8px; +} +.release-item { + border-top: 1px solid var(--border); +} +.release-row { + display: flex; + align-items: center; + gap: 17px; + padding: 20px 0; +} +.release-title { + flex: 1; + min-width: 0; +} +.release-title > a { + display: flex; + align-items: center; + gap: 8px; + font-weight: 500; + font-size: 13px; +} +.release-title p { + font-size: 11px; + color: #8b99ac; + margin-top: 5px; +} +.release-mark { + width: 41px; + height: 41px; +} +.release-binding { + background: #f9fbfd; + border-radius: 5px; + margin-bottom: 16px; + padding-top: 8px; +} +.provider-list { + padding: 0 24px; +} +.provider-item { + border-top: 1px solid var(--border); + padding: 25px 0; +} +.provider-heading { + display: flex; + align-items: center; + gap: 16px; +} +.provider-heading > div:nth-child(2) { + flex: 1; +} +.provider-heading h2 { + font-size: 17px; +} +.provider-heading p { + font-size: 12px; + color: #8292a7; + line-height: 1.8; + margin-top: 3px; +} +.provider-mark { + width: 47px; + height: 47px; +} +.capability-row { + display: flex; + flex-wrap: wrap; + gap: 10px 20px; + margin: 19px 0 19px 63px; + font-size: 11px; + color: #9ba7b8; +} +.capability-row span { + display: flex; + align-items: center; + gap: 4px; +} +.capability-row .available { + color: #418b77; +} +.provider-bottom { + display: flex; + align-items: center; + gap: 20px; + margin-left: 63px; +} +.provider-bottom p { + flex: 1; + font-size: 12px; + color: #8c99ab; + line-height: 1.7; +} +.inline-explanation { + display: flex; + align-items: flex-start; + gap: 13px; + padding: 8px 5px; + color: #769486; +} +.inline-explanation h3 { + font-size: 12px; + color: #697e76; +} +.inline-explanation p { + font-size: 11px; + color: #93a0ad; + margin-top: 3px; +} +.evolution-path { + display: flex; + background: #fff; + border: 1px solid var(--border); + border-radius: 7px; + padding: 25px 15px; + margin-bottom: 20px; +} +.evolution-path > div { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 13px; + border-right: 1px solid var(--border); +} +.evolution-path > div:last-child { + border: 0; +} +.evolution-path span { + font-size: 12px; + color: #90a2b3; +} +.evolution-path strong { + font-size: 13px; + font-weight: 500; +} +.experiment-list { + padding: 0 24px; +} +.experiment-list article { + border-top: 1px solid var(--border); + padding: 23px 0; +} +.experiment-heading { + display: flex; + gap: 15px; + align-items: center; + margin-bottom: 16px; +} +.experiment-heading > svg { + color: #8498ac; +} +.experiment-heading > div { + flex: 1; +} +.experiment-heading h3 { + font-size: 14px; +} +.experiment-heading p { + font-size: 11px; + color: #91a0b2; + margin-top: 3px; +} +.experiment-list article > p { + font-size: 13px; + color: #65778e; +} +.experiment-list article > p.text-small { + font-size: 11px; + margin-top: 12px; +} +.usage-metrics { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 18px; + margin-bottom: 20px; +} +.usage-metrics section { + padding: 23px; + background: white; + border: 1px solid var(--border); + border-radius: 7px; + min-width: 0; +} +.usage-metrics section > div { + display: flex; + justify-content: space-between; + gap: 9px; + align-items: center; + color: #8fa1b4; +} +.usage-metrics h2 { + font-size: 12px; + color: #566a82; +} +.usage-metrics strong { + display: block; + font-size: 27px; + letter-spacing: -0.6px; + font-weight: 500; + margin: 14px 0 5px; +} +.usage-metrics p { + font-size: 11px; + color: #91a1b1; +} +.quota-bar { + display: flex; + height: 6px; + margin: 0 22px 22px; + background: #eef3f6; + overflow: hidden; + border-radius: 5px; +} +.quota-bar span { + background: var(--teal); +} +.quota-bar .reserved { + background: #b3d9cb; +} +@media (min-width: 1700px) { + .main-content { + padding-top: 36px; + } + .dashboard-columns { + grid-template-columns: 1.9fr 1fr; + } + .recent-panel { + min-height: 490px; + } +} +@media (max-width: 1250px) { + :root { + --sidebar: 218px; + } + .brand { + gap: 13px; + padding-left: 11px; + } + .brand strong { + font-size: 22px; + } + .brand small { + font-size: 8px; + } + .main-content { + padding: 25px; + } + .topbar { + padding: 0 25px; + } + .dashboard-columns { + grid-template-columns: 1.5fr 1fr; + } + .journey { + padding: 0 19px; + } + .journey li { + gap: 15px; + min-height: 88px; + } + .table-scroll { + padding: 0 15px 5px; + } + .data-table th, + .data-table td { + padding-left: 12px; + padding-right: 12px; + } + .onboarding > a { + gap: 10px; + } + .onboarding > a + a { + padding-left: 17px; + } + .onboarding p { + font-size: 10px; + } + .form-columns { + gap: 25px; + grid-template-columns: 1.9fr 1fr; + } + .stage-step { + gap: 6px; + } + .stage-step > span { + width: 22px; + height: 22px; + } + .stage-rail { + padding: 17px 12px; + } + .usage-metrics { + gap: 12px; + } + .usage-metrics section { + padding: 19px; + } + .usage-metrics strong { + font-size: 24px; + } + .project-row > time { + display: none; + } +} +@media (max-width: 1050px) { + :root { + --sidebar: 200px; + } + .brand { + gap: 10px; + padding-left: 7px; + } + .brand strong { + font-size: 21px; + } + .nav-link { + gap: 15px; + padding-left: 12px; + font-size: 13px; + } + .dashboard-columns { + grid-template-columns: 1fr; + } + .recent-panel { + min-height: 340px; + } + .recent-panel .empty-state { + min-height: 260px; + } + .journey-panel .journey { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 12px; + padding: 5px 20px 18px; + } + .journey li, + .journey li:last-child { + display: block; + min-height: auto; + } + .journey li:not(:last-child):before { + display: none; + } + .journey li h3 { + margin: 10px 0 5px; + font-size: 12px; + } + .journey li p { + font-size: 10px; + } + .journey-number { + width: 27px; + height: 27px; + font-size: 12px; + } + .connection-note { + margin: 0 14px; + } + .onboarding { + display: block; + } + .onboarding > a { + padding: 13px 3px; + align-items: center; + } + .onboarding > a + a { + border-left: 0; + border-top: 1px solid var(--border); + padding-left: 3px; + } + .onboarding p { + font-size: 11px; + } + .onboarding-arrow { + display: block; + margin-left: auto; + } + .onboarding > a > div { + flex: 1; + } + .detail-columns { + grid-template-columns: 1fr; + } + .form-columns { + grid-template-columns: 1fr; + } + .form-guide { + display: none; + } + .project-row { + gap: 12px; + } + .stage-rail { + gap: 15px; + } + .stage-step { + flex: none; + } + .stage-step > svg { + margin-left: 4px; + } + .usage-metrics { + grid-template-columns: repeat(2, 1fr); + } + .evolution-path { + gap: 10px; + padding: 20px 13px; + } + .evolution-path > div { + gap: 8px; + } + .evolution-path strong { + font-size: 11px; + } + .run-identification code { + overflow-wrap: anywhere; + } +} +@media (max-width: 760px) { + :root { + --sidebar: 248px; + } + .sidebar { + transform: translateX(-100%); + transition: transform 0.2s ease; + } + .sidebar.is-open { + transform: translateX(0); + } + .sidebar-scrim { + position: fixed; + inset: 0; + background: #0b182c80; + backdrop-filter: blur(2px); + z-index: 40; + } + .main-shell { + margin-left: 0; + } + .mobile-menu, + .mobile-close { + display: inline-flex; + } + .mobile-close { + position: absolute; + right: 6px; + top: 8px; + color: #bdcad7; + width: 24px; + height: 24px; + } + .brand { + padding: 24px 15px 30px; + gap: 17px; + } + .brand strong { + font-size: 24px; + } + .brand small { + font-size: 10px; + } + .nav-link { + font-size: 14px; + gap: 20px; + padding-left: 16px; + } + .topbar { + height: 56px; + padding: 0 17px; + position: sticky; + top: 0; + z-index: 20; + background: #fbfcfef5; + backdrop-filter: blur(12px); + } + .breadcrumb { + gap: 11px; + font-size: 12px; + } + .breadcrumb .mobile-menu { + margin-left: -7px; + } + .topbar-actions { + gap: 10px; + } + .mode-badge { + font-size: 10px; + padding: 3px 8px; + } + .topbar-divider { + height: 18px; + } + .main-content { + padding: 24px 18px; + } + .page-header { + margin-bottom: 21px; + } + .page-heading-row { + align-items: flex-start; + gap: 13px; + } + .page-header h1 { + font-size: 27px; + letter-spacing: -0.8px; + } + .page-header p { + font-size: 12px; + line-height: 1.8; + margin-top: 7px; + } + .page-heading-row > .button { + min-height: 36px; + padding: 8px 11px; + font-size: 11px; + gap: 5px; + margin-top: 2px; + } + .page-heading-row > .button svg { + width: 15px; + } + .metrics-strip { + padding: 14px 0; + } + .metric { + padding: 2px 14px; + } + .metric h2 { + font-size: 11px; + } + .metric strong { + font-size: 25px; + margin: 6px 0; + } + .metric p { + font-size: 9px; + line-height: 1.7; + } + .panel-heading { + padding: 17px 17px 14px; + } + .panel-heading h2 { + font-size: 14px; + } + .panel-heading .text-link { + font-size: 11px; + } + .recent-panel { + min-height: 330px; + } + .recent-panel .empty-state { + min-height: 245px; + } + .empty-state h3 { + font-size: 15px; + } + .empty-state p { + font-size: 12px; + } + .empty-state { + padding: 35px 17px; + min-height: 250px; + } + .empty-icon { + margin-bottom: 15px; + } + .dashboard-columns { + gap: 0; + } + .table-scroll { + padding: 0 14px 5px; + } + .run-table { + display: block; + } + .run-table thead { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + } + .run-table tbody { + display: block; + } + .run-table tbody tr { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + gap: 8px 12px; + border-bottom: 1px solid #edf1f5; + padding: 16px 3px; + } + .run-table tbody tr:first-child { + padding-top: 5px; + } + .run-table tbody tr:last-child { + border-bottom: 0; + } + .run-table td { + display: block; + min-width: 0; + max-width: none; + border: 0; + padding: 0; + overflow-wrap: anywhere; + } + .run-table td[data-label]::before { + content: attr(data-label); + margin-right: 8px; + color: var(--muted); + font-size: 11px; + } + .run-table .run-primary, + .run-table .run-project { + grid-column: 1 / -1; + } + .run-table .run-primary { + margin-bottom: 3px; + } + .run-table .row-title { + min-width: 0; + max-width: none; + } + .run-table .run-updated { + grid-column: 1; + align-self: center; + white-space: normal; + font-size: 11px; + } + .run-table .run-link { + grid-column: 2; + justify-self: end; + } + .run-table .run-link .icon-button { + width: 38px; + height: 38px; + background: #f5f8fb; + } + .journey-panel .journey { + display: block; + padding: 3px 20px 8px; + } + .journey li, + .journey li:last-child { + display: flex; + gap: 19px; + min-height: 74px; + } + .journey li:last-child { + min-height: 62px; + } + .journey li:not(:last-child):before { + display: block; + left: 13px; + top: 30px; + bottom: 5px; + } + .journey li h3 { + margin: 1px 0 4px; + font-size: 12px; + } + .journey li p { + font-size: 11px; + } + .journey-number { + flex-shrink: 0; + } + .connection-note { + padding: 12px; + margin: 0 11px 1px; + } + .onboarding-panel .panel-heading { + padding-bottom: 2px; + } + .onboarding { + padding: 0 17px 8px; + } + .onboarding > a { + padding: 17px 0; + gap: 13px; + } + .onboarding > a + a { + padding-left: 0; + } + .onboarding h3 { + font-size: 12px; + } + .onboarding p { + font-size: 10px; + } + .onboarding-number { + font-size: 10px; + } + .footer { + margin: 0 18px; + font-size: 10px; + } + .notice { + font-size: 11px; + padding: 12px; + gap: 9px; + } + .notice p { + font-size: 11px; + } + .notice > .text-link { + font-size: 10px; + } + .list-toolbar { + padding: 16px; + gap: 12px; + flex-wrap: wrap; + } + .search-field { + width: 100%; + } + .list-toolbar > .text-small { + display: none; + } + .filter-controls { + width: 100%; + } + .filter-controls select { + flex: 1; + min-width: 0; + } + .project-list { + padding: 0 16px; + } + .project-row { + flex-wrap: wrap; + padding: 22px 0; + } + .project-mark { + width: 39px; + height: 39px; + } + .project-information h2 { + font-size: 14px; + } + .project-information p { + font-size: 11px; + } + .project-branch { + display: none; + } + .project-row > svg { + margin-left: 0; + width: 16px; + } + .details-list { + padding: 0 17px 17px; + } + .key-value { + grid-template-columns: 90px minmax(0, 1fr); + gap: 12px; + font-size: 11px; + } + .key-value code { + font-size: 10px; + } + .panel-intro { + padding: 0 17px 15px; + font-size: 11px; + } + .workspace-list { + padding: 0 17px 16px; + } + .workspace-row { + flex-wrap: wrap; + gap: 12px; + } + .panel > .notice { + margin: 0 17px 13px; + } + .panel-bottom-action { + padding-left: 17px; + } + .wish-form-panel { + padding: 20px 17px; + } + .form-stack { + gap: 17px; + } + .form-section h2 { + font-size: 14px; + } + .field-label { + font-size: 12px; + } + .field input, + .field select, + .field textarea { + font-size: 13px; + } + .field-hint { + font-size: 10px; + } + .budget-fields { + gap: 10px; + grid-template-columns: 1fr 1fr; + } + .budget-fields > .field:last-child { + grid-column: 1/3; + } + .form-submit { + flex-direction: column; + align-items: stretch; + gap: 14px; + } + .form-submit p { + font-size: 10px; + } + .form-submit .button { + width: 100%; + } + .button-group { + gap: 2px; + } + .button-group .button { + font-size: 11px; + padding: 7px; + gap: 5px; + min-height: 34px; + } + .run-identification { + gap: 10px; + font-size: 10px; + margin-top: -9px; + } + .run-identification code { + font-size: 9px; + max-width: 210px; + } + .stage-rail { + padding: 15px 12px; + margin-bottom: 16px; + } + .tabs { + gap: 22px; + } + .tabs button { + font-size: 12px; + } + .answer-panel form { + flex-direction: column; + align-items: stretch; + padding: 0 17px 17px; + } + .answer-panel > p { + padding: 0 17px 12px; + font-size: 12px; + } + .event-list { + padding: 0 17px 15px; + } + .event-meta { + gap: 7px; + font-size: 9px; + flex-wrap: wrap; + } + .event-meta time { + margin-left: 0; + } + .event-body > p { + font-size: 12px; + } + .artifact-list { + padding: 0 17px 17px; + } + .artifact-list article { + gap: 12px; + } + .artifact-list article > svg { + width: 18px; + } + .release-list { + padding: 0 16px 6px; + } + .release-row { + flex-wrap: wrap; + gap: 11px; + } + .release-mark { + width: 35px; + height: 35px; + } + .release-title > a { + font-size: 12px; + } + .release-title p { + font-size: 10px; + overflow-wrap: anywhere; + } + .release-row > .button { + order: 6; + width: 100%; + min-height: 35px; + font-size: 12px; + } + .release-row > .status { + font-size: 10px; + } + .release-row > .icon-button { + width: 23px; + } + .release-binding { + padding-left: 12px; + padding-right: 12px; + } + .provider-list { + padding: 0 17px; + } + .provider-heading { + gap: 12px; + flex-wrap: wrap; + } + .provider-mark { + width: 40px; + height: 40px; + } + .provider-heading > div:nth-child(2) { + min-width: 180px; + } + .provider-heading h2 { + font-size: 15px; + } + .provider-heading p { + font-size: 11px; + } + .provider-heading > .status { + margin-left: 52px; + } + .capability-row { + margin-left: 0; + gap: 9px 14px; + font-size: 10px; + } + .provider-bottom { + margin-left: 0; + flex-wrap: wrap; + gap: 12px; + } + .provider-bottom p { + flex-basis: 100%; + font-size: 11px; + } + .provider-bottom .button { + width: 100%; + min-height: 35px; + font-size: 12px; + } + .inline-explanation { + gap: 11px; + } + .inline-explanation h3 { + font-size: 11px; + } + .inline-explanation p { + font-size: 10px; + } + .evolution-path { + overflow-x: auto; + padding: 17px 12px; + gap: 15px; + } + .evolution-path > div { + min-width: 90px; + flex: none; + padding-right: 15px; + gap: 9px; + } + .evolution-path strong { + font-size: 11px; + } + .evolution-path span { + font-size: 10px; + } + .experiment-list { + padding: 0 17px; + } + .experiment-heading { + gap: 11px; + } + .experiment-heading h3 { + font-size: 12px; + } + .experiment-heading p { + font-size: 10px; + } + .experiment-heading .status { + font-size: 10px; + } + .experiment-list article > p { + font-size: 12px; + } + .usage-metrics { + gap: 12px; + } + .usage-metrics section { + padding: 16px; + } + .usage-metrics section > div > svg { + width: 17px; + } + .usage-metrics h2 { + font-size: 11px; + } + .usage-metrics strong { + font-size: 22px; + } + .usage-metrics p { + font-size: 10px; + } + .modal { + max-height: 90dvh; + } + .modal-header { + padding: 22px 20px 17px; + } + .modal-header h2 { + font-size: 18px; + } + .modal > .form-stack, + .modal-body { + padding: 19px 20px 22px; + } + .form-pair { + gap: 12px; + } + .modal .key-value { + grid-template-columns: 75px minmax(0, 1fr); + } + .modal .notice { + font-size: 11px; + } + .checkbox-label { + font-size: 11px; + } +} +.command-evidence { + margin: 14px 0; +} +.command-evidence > div { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + background: #f7f9fb; + border: 1px solid var(--border); + border-radius: 4px; + padding: 9px 12px; + margin-bottom: 7px; +} +.command-evidence code { + font-size: 11px; + overflow-wrap: anywhere; +} +.connection-list { + padding: 0 22px 12px; +} +.connection-list > div { + display: flex; + align-items: center; + gap: 13px; + border-top: 1px solid var(--border); + padding: 16px 0; +} +.connection-list > div > svg { + color: #889bb1; +} +.connection-list span { + flex: 1; +} +.connection-list strong { + display: block; + font-size: 12px; + font-weight: 500; +} +.connection-list small { + display: block; + font-size: 10px; + color: #8d9bb0; + margin-top: 4px; +} +.candidate-actions { + display: flex; + align-items: center; + gap: 10px; + margin-top: 18px; +} +.candidate-actions select { + min-height: 34px; + padding: 6px 25px 6px 10px; + font-size: 11px; +} +.candidate-actions .button { + min-height: 34px; + padding: 6px 12px; + font-size: 11px; +} +.candidate-actions > span { + font-size: 10px; + color: #91a0b3; +} +@media (max-width: 760px) { + .candidate-actions { + flex-wrap: wrap; + } + .candidate-actions > span { + flex-basis: 100%; + } + .command-evidence > div { + flex-wrap: wrap; + } + .connection-list { + padding: 0 17px 10px; + } +} +@media (prefers-reduced-motion: reduce) { + *, + *:before, + *:after { + scroll-behavior: auto !important; + transition: none !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + } +} + +.code-input { + font-family: SFMono-Regular, Consolas, monospace !important; + font-size: 12px !important; + line-height: 1.8 !important; +} +.verification-profile-form { + border-bottom: 1px solid var(--border); +} + +.workspace-input-panel .form-stack { align-items: stretch; } + +.requirement-amendment > summary { cursor: pointer; padding: 0 22px 18px; color: var(--muted); font-size: 13px; } diff --git a/apps/web/src/app/icon.svg b/apps/web/src/app/icon.svg new file mode 100644 index 0000000..d60f661 --- /dev/null +++ b/apps/web/src/app/icon.svg @@ -0,0 +1 @@ + diff --git a/apps/web/src/app/ide/[id]/launch/route.ts b/apps/web/src/app/ide/[id]/launch/route.ts new file mode 100644 index 0000000..a70de39 --- /dev/null +++ b/apps/web/src/app/ide/[id]/launch/route.ts @@ -0,0 +1,74 @@ +import { NextRequest, NextResponse } from "next/server"; +import { tokenFor } from "@/lib/auth"; +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) { + const token = await tokenFor(request); + if (!token) + return NextResponse.redirect( + new URL( + `/login?returnTo=${encodeURIComponent(request.nextUrl.pathname)}`, + request.nextUrl.origin, + ), + ); + const { id } = await params; + const api = (process.env.WF_API_URL ?? "http://127.0.0.1:4000").replace(/\/$/, ""); + try { + const response = await fetch(`${api}/v1/workspaces/${encodeURIComponent(id)}/launch`, { + method: "POST", + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({}), + cache: "no-store", + redirect: "error", + signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]), + }); + if (!response.ok) + return NextResponse.json( + { + error: { + code: "IDE_LAUNCH_DENIED", + message: + response.status === 403 + ? "你没有权限打开此工作空间。" + : "工作空间尚未就绪或控制面拒绝了连接。", + }, + }, + { status: response.status, headers: { "Cache-Control": "no-store" } }, + ); + const payload = (await response.json()) as { + data?: { launchUrl?: string; expiresIn?: number }; + }; + if (typeof payload.data?.launchUrl !== "string" || payload.data.expiresIn !== 30) + throw new Error("Invalid workspace launch response"); + // The authenticated control plane resolves the tenant's gateway and verifies + // its origin. This BFF never owns tenant routing or gateway service tokens. + const url = new URL(payload.data.launchUrl); + const localHttp = process.env.NODE_ENV !== "production" && url.protocol === "http:" && + ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + const query = [...url.searchParams.keys()]; + if ((url.protocol !== "https:" && !localHttp) || url.username || url.password || url.hash || + url.pathname !== "/session" || query.length !== 1 || query[0] !== "code" || + !/^[A-Za-z0-9_-]{20,256}$/.test(url.searchParams.get("code") ?? "")) + throw new Error("Invalid workspace session redirect"); + const result = NextResponse.redirect(url, 303); + result.headers.set("Cache-Control", "no-store"); + result.headers.set("Referrer-Policy", "no-referrer"); + return result; + } catch { + return NextResponse.json( + { + error: { + code: "IDE_UNAVAILABLE", + message: "无法取得工作空间启动链接。请检查控制面与运行环境配置。", + }, + }, + { status: 503, headers: { "Cache-Control": "no-store" } }, + ); + } +} diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx new file mode 100644 index 0000000..fc92124 --- /dev/null +++ b/apps/web/src/app/layout.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from "next"; +import "./globals.css"; +export const metadata: Metadata = { + title: { default: "WishForge · 工作空间", template: "%s · WishForge" }, + description: "从一句愿望,到有证据的交付。", +}; +export default function RootLayout({ + children, +}: Readonly<{ children: React.ReactNode }>) { + return ( + + {children} + + ); +} diff --git a/apps/web/src/app/login/callback/route.ts b/apps/web/src/app/login/callback/route.ts new file mode 100644 index 0000000..ca23b0e --- /dev/null +++ b/apps/web/src/app/login/callback/route.ts @@ -0,0 +1,61 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + completeLogin, + cookieOptions, + OAUTH_COOKIE, + publicOrigin, + safeReturnTo, + SESSION_COOKIE, + unseal, + type OAuthState, +} from "@/lib/auth"; +export async function GET(request: NextRequest) { + const state = await unseal( + request.cookies.get(OAUTH_COOKIE)?.value, + ); + const code = request.nextUrl.searchParams.get("code"); + if ( + !state || + !code || + state.state !== request.nextUrl.searchParams.get("state") + ) + return NextResponse.json( + { + error: { + code: "INVALID_OAUTH_STATE", + message: "登录会话已失效,请重新登录。", + }, + }, + { status: 400 }, + ); + try { + const session = await completeLogin(request, code, state); + const response = NextResponse.redirect( + new URL(safeReturnTo(state.returnTo), publicOrigin(request)), + ); + response.cookies.set(SESSION_COOKIE, session.cookie, { + ...cookieOptions(request), + maxAge: session.ttl, + }); + response.cookies.set(OAUTH_COOKIE, "", { + ...cookieOptions(request), + maxAge: 0, + }); + return response; + } catch { + const response = NextResponse.json( + { + error: { + code: "LOGIN_FAILED", + message: "登录凭据校验失败,请重新登录。", + }, + }, + { status: 401 }, + ); + response.cookies.set(OAUTH_COOKIE, "", { + ...cookieOptions(request), + maxAge: 0, + }); + return response; + } +} diff --git a/apps/web/src/app/login/route.ts b/apps/web/src/app/login/route.ts new file mode 100644 index 0000000..b448759 --- /dev/null +++ b/apps/web/src/app/login/route.ts @@ -0,0 +1,70 @@ +import { NextRequest, NextResponse } from "next/server"; +import { + cookieOptions, + discovery, + isDevelopmentAuth, + OAUTH_COOKIE, + oidcConfigured, + pkceChallenge, + publicOrigin, + randomToken, + safeReturnTo, + seal, +} from "@/lib/auth"; +export async function GET(request: NextRequest) { + if (isDevelopmentAuth()) + return NextResponse.redirect(new URL("/", publicOrigin(request))); + if (!oidcConfigured()) + return new Response( + '登录 · WishForge

连接你的工作空间

此部署尚未配置组织登录。请联系管理员配置 OIDC 身份服务。

WishForge 不提供默认公开账户或密码。

返回工作空间
', + { + status: 503, + headers: { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-store", + }, + }, + ); + try { + const metadata = await discovery(); + const state = randomToken(); + const nonce = randomToken(); + const verifier = randomToken(); + const url = new URL(metadata.authorization_endpoint); + url.search = new URLSearchParams({ + client_id: process.env.OIDC_CLIENT_ID!, + response_type: "code", + scope: "openid profile email", + redirect_uri: `${publicOrigin(request)}/login/callback`, + state, + nonce, + code_challenge: pkceChallenge(verifier), + code_challenge_method: "S256", + }).toString(); + const response = NextResponse.redirect(url); + response.cookies.set( + OAUTH_COOKIE, + await seal( + { + state, + nonce, + verifier, + returnTo: safeReturnTo(request.nextUrl.searchParams.get("returnTo")), + }, + 600, + ), + { ...cookieOptions(request), maxAge: 600 }, + ); + return response; + } catch { + return NextResponse.json( + { + error: { + code: "OIDC_UNAVAILABLE", + message: "身份服务暂时不可用,请稍后重试。", + }, + }, + { status: 503 }, + ); + } +} diff --git a/apps/web/src/app/logout/route.ts b/apps/web/src/app/logout/route.ts new file mode 100644 index 0000000..71fa440 --- /dev/null +++ b/apps/web/src/app/logout/route.ts @@ -0,0 +1,13 @@ +import { NextRequest, NextResponse } from "next/server"; +import { clearAuth, publicOrigin } from "@/lib/auth"; +export async function POST(request: NextRequest) { + const origin = request.headers.get("origin"); + if (origin && origin !== publicOrigin(request)) + return new Response("Forbidden", { status: 403 }); + const response = NextResponse.redirect( + new URL("/", publicOrigin(request)), + 303, + ); + clearAuth(response, request); + return response; +} diff --git a/apps/web/src/components/console-shell.tsx b/apps/web/src/components/console-shell.tsx new file mode 100644 index 0000000..42db992 --- /dev/null +++ b/apps/web/src/components/console-shell.tsx @@ -0,0 +1,155 @@ +"use client"; +import { + Activity, + ArrowUpRight, + BarChart3, + Box, + ChevronRight, + FlaskConical, + Folder, + Home, + Laptop, + Menu, + RefreshCw, + Settings2, + Sparkle, + X, +} from "lucide-react"; +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { useState } from "react"; +import { useSWRConfig } from "swr"; +import type { ReactNode } from "react"; +import { useResource } from "@/lib/api"; + +const navigation = [ + ["/", "工作概览", Home], + ["/projects", "项目空间", Folder], + ["/runs", "运行记录", Activity], + ["/releases", "部署与审批", Box], + ["/providers", "执行器", Settings2], + ["/evolution", "演进实验", FlaskConical], + ["/usage", "用量", BarChart3], +] as const; +export function ConsoleShell({ children }: { children: ReactNode }) { + const pathname = usePathname(); + const [open, setOpen] = useState(false); + const { mutate } = useSWRConfig(); + const session = useResource<{ + authenticated: boolean; + mode: string; + name?: string; + }>("/session"); + const current = navigation.find(([href]) => + href === "/" ? pathname === "/" : pathname.startsWith(href), + ); + return ( +
+ + 跳转到主要内容 + + {open ? ( + + +
+ + + + {session.data?.mode === "development" + ? "LOCAL WORKSPACE" + : "WORKSPACE"} + + + {session.data?.mode === "development" + ? "本地开发" + : (session.data?.name ?? "开发与交付")} + + + +
+ +
+
+
+ + 工作空间 + / + {current?.[1] ?? "WishForge"} +
+
+ {session.data?.mode === "development" ? ( + + + 本地模式 + + ) : session.data?.authenticated ? ( +
+ +
+ ) : ( + + 登录 + + + )} + + +
+
+
+ {children} +
+
+
+ ); +} diff --git a/apps/web/src/components/run-table.tsx b/apps/web/src/components/run-table.tsx new file mode 100644 index 0000000..2bedb26 --- /dev/null +++ b/apps/web/src/components/run-table.tsx @@ -0,0 +1,103 @@ +"use client"; +import Link from "next/link"; +import { ArrowRight, Layers3 } from "lucide-react"; +import { formatTime } from "@/lib/api"; +import type { Project, Run } from "@/lib/types"; +import { EmptyState, Status } from "./ui"; +export const stages: Record = { + clarify: "澄清", + plan: "规划", + implement: "实现", + verify: "验证", + integrate: "整合", + build: "构建", + preview: "预览", + release: "发布", + accept: "验收", +}; +export const providerNames: Record = { + codex: "Codex", + codebuddy: "CodeBuddy", + workbuddy_cloud: "WorkBuddy Cloud", +}; +export function RunTable({ + runs, + projects = [], + compact = false, +}: { + runs: Run[]; + projects?: Project[]; + compact?: boolean; +}) { + const names = new Map(projects.map((project) => [project.id, project.name])); + return ( +
+ + + + + + + {compact ? null : } + + + + + + {runs.map((run) => ( + + + + + {compact ? null : ( + + )} + + + + ))} + +
愿望项目阶段执行器更新时间 + 详情 +
+ + {run.goal} + +
+ + {run.id.slice(0, 8)} +
+
+ {names.get(run.projectId) ?? run.projectId.slice(0, 8)} + + + {stages[run.stage] ?? run.stage} + + + {providerNames[run.provider] ?? run.provider} + + {formatTime(run.updatedAt)} + + + + +
+ {runs.length === 0 ? ( + } + title="暂无运行记录" + description="完成项目连接后,提交第一个愿望。" + action={ + + 创建项目 + + } + /> + ) : null} +
+ ); +} diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx new file mode 100644 index 0000000..4794d80 --- /dev/null +++ b/apps/web/src/components/ui.tsx @@ -0,0 +1,355 @@ +"use client"; +import { + AlertCircle, + ArrowUpRight, + Check, + ChevronRight, + Inbox, + LoaderCircle, + X, +} from "lucide-react"; +import Link from "next/link"; +import { + cloneElement, + isValidElement, + useEffect, + useId, + useRef, + type ReactNode, +} from "react"; +import { ApiError } from "@/lib/api"; + +export function Button({ + children, + variant = "primary", + busy, + ...props +}: React.ButtonHTMLAttributes & { + variant?: "primary" | "secondary" | "ghost" | "danger"; + busy?: boolean; +}) { + return ( + + ); +} +export function ButtonLink({ + href, + children, + secondary = false, +}: { + href: string; + children: ReactNode; + secondary?: boolean; +}) { + return ( + + {children} + + ); +} +export function PageHeader({ + title, + description, + action, + back, +}: { + title: string; + description: string; + action?: ReactNode; + back?: { href: string; label: string }; +}) { + return ( + <> +
+ {back ? ( + + {back.label} + + + ) : null} +
+
+

{title}

+

{description}

+
+ {action} +
+
+ + ); +} +export function Panel({ + title, + aside, + children, + className = "", +}: { + title?: string; + aside?: ReactNode; + children: ReactNode; + className?: string; +}) { + return ( +
+ {title ? ( +
+

{title}

+ {aside} +
+ ) : null} + {children} +
+ ); +} +export function EmptyState({ + title, + description, + action, + compact = false, + icon, +}: { + title: string; + description: string; + action?: ReactNode; + compact?: boolean; + icon?: ReactNode; +}) { + return ( +
+
+ {icon ?? } +
+

{title}

+

{description}

+ {action} +
+ ); +} +export function ErrorNotice({ + error, + retry, +}: { + error: unknown; + retry?: () => void; +}) { + const unauthorized = error instanceof ApiError && error.status === 401; + return ( +
+ +
+ + {unauthorized ? "请登录工作空间" : "暂时无法连接控制面"} + +

{error instanceof Error ? error.message : "请检查连接后重试。"}

+
+ {unauthorized ? ( + + 登录 + + + ) : retry ? ( + + ) : null} +
+ ); +} +export function Notice({ + children, + tone = "info", +}: { + children: ReactNode; + tone?: "info" | "warning" | "success"; +}) { + return ( +
+ +
{children}
+
+ ); +} +export function Loading() { + return ( +
+ + 正在读取控制面数据… +
+ ); +} +const statuses: Record = { + healthy: ["健康", "green"], + deploying: ["部署中", "teal"], + rolled_back: ["已回滚", "amber"], + unknown: ["待确认", "amber"], + requested: ["准备中", "teal"], + suspended: ["已挂起", "neutral"], + unconfigured: ["未配置", "amber"], + proposed: ["待评估", "neutral"], + shadowing: ["影子运行", "teal"], + canary: ["灰度中", "teal"], + queued: ["排队中", "neutral"], + running: ["运行中", "teal"], + waiting: ["等待处理", "amber"], + paused: ["已暂停", "amber"], + succeeded: ["已完成", "green"], + failed: ["失败", "red"], + canceled: ["已取消", "neutral"], + approved: ["已批准", "green"], + rejected: ["已拒绝", "red"], + pending: ["待审批", "amber"], + pending_approval: ["待审批", "amber"], + awaiting_approval: ["待审批", "amber"], + deployed: ["已部署", "green"], + ready: ["就绪", "green"], + connected: ["已连接", "green"], + online: ["在线", "green"], + offline: ["离线", "neutral"], + draft: ["草案", "neutral"], + disabled: ["未启用", "neutral"], + evaluating: ["评估中", "teal"], + promoted: ["已晋级", "green"], +}; +export function Status({ value, label }: { value: string; label?: string }) { + const [text, tone] = statuses[value] ?? [value, "neutral"]; + return ( + + + {label ?? text} + + ); +} +export function Field({ + label, + hint, + children, +}: { + label: string; + hint?: string; + children: ReactNode; +}) { + const id = useId(); + return ( +
+ + {isValidElement(children) + ? cloneElement( + children as React.ReactElement<{ + id?: string; + "aria-describedby"?: string; + }>, + { id, "aria-describedby": hint ? `${id}-hint` : undefined }, + ) + : children} + {hint ? ( + + {hint} + + ) : null} +
+ ); +} +export function Modal({ + title, + description, + children, + onClose, +}: { + title: string; + description?: string; + children: ReactNode; + onClose: () => void; +}) { + const ref = useRef(null); + useEffect(() => { + const dialog = ref.current; + dialog?.showModal(); + return () => { + dialog?.close(); + }; + }, []); + return ( + { + event.preventDefault(); + onClose(); + }} + onClick={(event) => { + if (event.target === event.currentTarget) onClose(); + }} + > +
+
+

{title}

+ {description ?

{description}

: null} +
+ +
+ {children} +
+ ); +} +export function KeyValue({ + label, + children, +}: { + label: string; + children: ReactNode; +}) { + return ( +
+
{label}
+
{children}
+
+ ); +} +export function JsonDetails({ + value, + label = "查看原始记录", +}: { + value: unknown; + label?: string; +}) { + return ( +
+ {label} +
{JSON.stringify(value, null, 2)}
+
+ ); +} +export function FormError({ message }: { message?: string }) { + return message ? ( +
+ + {message} +
+ ) : null; +} +export function Success({ children }: { children: ReactNode }) { + return ( +
+ + {children} +
+ ); +} diff --git a/apps/web/src/features/dashboard.tsx b/apps/web/src/features/dashboard.tsx new file mode 100644 index 0000000..df942d7 --- /dev/null +++ b/apps/web/src/features/dashboard.tsx @@ -0,0 +1,179 @@ +"use client"; +import Link from "next/link"; +import { + ArrowRight, + CircleAlert, + GitBranch, + Laptop, + Plus, + Settings2, +} from "lucide-react"; +import { formatNumber, useResource } from "@/lib/api"; +import type { Dashboard } from "@/lib/types"; +import { + ButtonLink, + EmptyState, + ErrorNotice, + Loading, + PageHeader, + Panel, +} from "@/components/ui"; +import { RunTable } from "@/components/run-table"; +const journey = [ + ["许愿与澄清", "将想法转化为可执行的任务,与 Agent 一起澄清细节。"], + ["隔离执行", "在隔离的环境中完成构建、测试与验证。"], + ["证据验证", "收集执行结果与证据,确认符合预期。"], + ["发布审批", "绑定确切的代码与制品,完成发布评审。"], + ["部署与观察", "部署到目标环境,并持续观察运行状态。"], +]; +export function DashboardView() { + const { data, error, isLoading, mutate } = useResource( + "/dashboard", + 10000, + ); + const metrics = [ + { + title: "进行中的运行", + value: data?.runs.filter((run) => + ["running", "queued"].includes(run.status), + ).length, + note: "正在推进的愿望", + }, + { + title: "待确认", + value: data + ? data.runs.filter((run) => run.status === "waiting").length + + data.releases.filter( + (release) => + release.approvalId && + ["pending", "pending_approval", "awaiting_approval"].includes( + release.status, + ), + ).length + : undefined, + note: "需要你的判断", + }, + { + title: "已连接执行器", + value: data?.providers.filter( + (provider) => provider.configured && provider.enabled, + ).length, + note: "可用于新的运行", + }, + ]; + return ( + <> + + + 提交愿望 + + } + /> + {error ? void mutate()} /> : null} +
+ {metrics.map((metric) => ( +
+

{metric.title}

+ {formatNumber(metric.value)} +

{data ? metric.note : "等待控制面数据"}

+
+ ))} +
+
+ + 全部运行 + + + } + className="recent-panel" + > + {isLoading ? ( + + ) : data ? ( + + ) : ( + + )} + + +
    + {journey.map(([title, description], index) => ( +
  1. + {index + 1} +
    +

    {title}

    +

    {description}

    +
    +
  2. + ))} +
+
+ +
+ {data ? "控制面已连接" : "控制面尚未连接"} +

+ {data + ? `${data.system.region} · ${data.system.authMode}` + : "请完成工作空间配置以启用完整功能。"} +

+
+ + + +
+
+
+ +
+ {[ + { + number: "01", + Icon: GitBranch, + title: "连接代码仓库", + text: "关联代码仓库,让 WishForge 了解你的项目。", + href: "/projects/new", + }, + { + number: "02", + Icon: Settings2, + title: "配置执行器", + text: "选择可用的执行器,连接你的模型凭据。", + href: "/providers", + }, + { + number: "03", + Icon: Laptop, + title: "打开云 IDE", + text: "在云端开发环境中构建与协作。", + href: "/projects", + }, + ].map(({ number, Icon, title, text, href }) => ( + + {number} + +
+

{title}

+

{text}

+
+ + + ))} +
+
+ + ); +} diff --git a/apps/web/src/features/environments.tsx b/apps/web/src/features/environments.tsx new file mode 100644 index 0000000..8e9d513 --- /dev/null +++ b/apps/web/src/features/environments.tsx @@ -0,0 +1,377 @@ +"use client"; +import { useState } from "react"; +import { Cloud, Plus, Server } from "lucide-react"; +import { messageOf, mutateApi, useResource } from "@/lib/api"; +import type { Environment, Project } from "@/lib/types"; +import { + Button, + EmptyState, + ErrorNotice, + Field, + FormError, + JsonDetails, + Loading, + Modal, + Notice, + PageHeader, + Panel, +} from "@/components/ui"; +import { RunnerRegistration } from "./runner-registration"; +const labels: Record = { + managed_kubernetes: "平台托管 Kubernetes", + kubernetes: "自带 Kubernetes", + compose: "自带 Docker Compose", +}; +export function EnvironmentsView() { + const { data, error, isLoading, mutate } = useResource( + "/environments", + 15000, + ); + const [show, setShow] = useState(false); + const [runner, setRunner] = useState(null); + const [access, setAccess] = useState(null); + const [secrets, setSecrets] = useState(null); + return ( + <> + setShow(true)}> + + 添加环境 + + } + /> + {error ? void mutate()} /> : null} + + 登记环境不会自动购买云资源。自带环境须由已授权的 Runner + 连接,部署结果以实际健康检查为准。 + + + {isLoading ? ( + + ) : data?.length ? ( +
+ {data.map((environment) => ( +
+
+ {environment.type === "managed_kubernetes" ? ( + + ) : ( + + )} +
+

{environment.name}

+

+ {labels[environment.type ?? ""] ?? environment.type} ·{" "} + {String(environment.architecture ?? "未指定架构")} +

+
+ + {environment.production ? "生产环境" : "非生产环境"} + +
+

+ {environment.runnerId + ? `Runner: ${environment.runnerId}` + : "尚未指定 Runner。运行环境由控制面确认可用性。"} +

+

+ 访问范围:{environment.visibility === "public" ? "公开" : "私有(默认)"} ·{" "} + {environment.accessStatus === "configured" ? environment.visibility === "private" ? "身份网关已配置,成果以运行验收为准" : "地址已登记,尚不代表可访问" : "访问待配置"} +

+

成果地址:{environment.applicationUrl ?? "未配置"}

+ {environment.accessReason ?

{environment.accessReason}

: environment.visibility !== "public" && environment.accessStatus !== "configured" ?

此环境的身份网关待配置;当前不能生成私有成果链接。

: null} +

部署密钥引用:{environment.secretVersionRefs?.length ?? 0} 项{environment.secretVersionRefs?.length ? environment.deploymentSecretPolicyDigest ? " · 已绑定策略摘要" : " · 策略摘要待配置" : ""}

+ +
+ + + +
+
+ ))} +
+ ) : ( + } + action={ + + } + /> + )} +
+ {show ? ( + setShow(false)} + onSaved={() => void mutate()} + /> + ) : null} + {runner ? ( + setRunner(null)} + onSaved={() => void mutate()} + /> + ) : null} + {access ? setAccess(null)} onSaved={() => void mutate()} /> : null} + {secrets ? setSecrets(null)} onSaved={() => void mutate()} /> : null} + + ); +} +function CreateEnvironment({ + onClose, + onSaved, +}: { + onClose: () => void; + onSaved: () => void; +}) { + const projects = useResource("/projects"); + const [name, setName] = useState(""); + const [projectId, setProject] = useState(""); + const [type, setType] = useState("compose"); + const [architecture, setArchitecture] = useState("linux/amd64"); + const [runnerId, setRunner] = useState(""); + const [production, setProduction] = useState(false); + const [autoDeploy, setAutoDeploy] = useState(false); + const [applicationUrl, setApplicationUrl] = useState(""); + const [visibility, setVisibility] = useState<"private" | "public">("private"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + async function submit(event: React.FormEvent) { + event.preventDefault(); + setBusy(true); + setError(""); + try { + await mutateApi("/environments", { + name, + projectId: projectId || projects.data?.[0]?.id, + type, + architecture, + production, + autoDeploy, + runnerId: runnerId.trim() || undefined, + configVersion: "1", + secretVersionRefs: [], + applicationUrl: validateApplicationUrl(applicationUrl), + visibility, + }); + onSaved(); + onClose(); + } catch (error) { + setError(messageOf(error)); + } finally { + setBusy(false); + } + } + return ( + +
+ + setName(event.target.value)} + placeholder="例如:预发布环境" + /> + + + + +
+ + + + + + +
+ + setRunner(event.target.value)} + placeholder="已注册的 Runner ID" + /> + + + + + + {projects.error ? : null} +
+ + +
+ +
+ ); +} + +function validateApplicationUrl(value: string) { + const trimmed = value.trim(); + if (!trimmed) return undefined; + let url: URL; + try { url = new URL(trimmed); } catch { throw new Error("请输入有效的成果地址。"); } + const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + if (url.username || url.password || url.search || url.hash || (url.protocol !== "https:" && !(url.protocol === "http:" && loopback))) { + throw new Error("成果地址须使用 HTTPS,且不能包含账号、查询参数或片段;开发环境仅允许回环 HTTP。"); + } + return url.href; +} +function AccessFields({ applicationUrl, setApplicationUrl, visibility, setVisibility }: { + applicationUrl: string; + setApplicationUrl: (value: string) => void; + visibility: "private" | "public"; + setVisibility: (value: "private" | "public") => void; +}) { + return <> + + setApplicationUrl(event.target.value)} placeholder="https://app.example.com" /> + + + + + + {visibility === "private" ? "私有访问需要管理员为此环境配置真实身份网关。保存地址不等于完成访问授权,具体接入状态由控制面确认;打开成果时仍会校验身份与项目权限。" : "此环境的成果将公开访问。只有运行验收通过后,平台才会提供可访问成果链接。"} + + ; +} +function EnvironmentAccessSettings({ environment, onClose, onSaved }: { + environment: Environment; + onClose: () => void; + onSaved: () => void; +}) { + const [applicationUrl, setApplicationUrl] = useState(environment.applicationUrl ?? ""); + const [visibility, setVisibility] = useState<"private" | "public">(environment.visibility ?? "private"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + async function submit(event: React.FormEvent) { + event.preventDefault(); setBusy(true); setError(""); + try { + await mutateApi(`/environments/${environment.id}/access`, { applicationUrl: validateApplicationUrl(applicationUrl) ?? null, visibility }, "PATCH"); + onSaved(); onClose(); + } catch (error) { setError(messageOf(error)); } + finally { setBusy(false); } + } + return +
+ + 当前访问配置:{environment.accessStatus === "configured" ? "已配置" : "待配置"}。 + {environment.accessReason ?? "成果可访问性仍以运行验收结果为准。"} 修改后由控制面重新确认。 + + +

清空地址会移除访问配置;修改访问绑定后,未交付版本与旧审批需要重新验证。

+ {environment.activeReleaseId ? 此环境已有活动发布,服务器不允许修改其访问绑定。 : null} + +
+ +
; +} + +function DeploymentSecretSettings({ environment, onClose, onSaved }: { + environment: Environment; + onClose: () => void; + onSaved: () => void; +}) { + const [references, setReferences] = useState(environment.secretVersionRefs?.join("\n") ?? ""); + const [policyDigest, setPolicyDigest] = useState(environment.deploymentSecretPolicyDigest ?? ""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + async function submit(event: React.FormEvent) { + event.preventDefault(); setBusy(true); setError(""); + try { + const secretVersionRefs = references.split(/\r?\n/).map(value => value.trim()).filter(Boolean); + if (new Set(secretVersionRefs).size !== secretVersionRefs.length) throw new Error("密钥版本引用不能重复。"); + const deploymentSecretPolicyDigest = secretVersionRefs.length ? policyDigest.trim() : null; + if (secretVersionRefs.length && !/^sha256:[a-f0-9]{64}$/.test(deploymentSecretPolicyDigest ?? "")) { + throw new Error("非空密钥引用必须绑定运营提供的 sha256: 加 64 位小写十六进制策略摘要。"); + } + await mutateApi(`/environments/${environment.id}/deployment-secrets`, { secretVersionRefs, deploymentSecretPolicyDigest }, "PATCH"); + onSaved(); onClose(); + } catch (error) { setError(messageOf(error)); } + finally { setBusy(false); } + } + return +
+ 这里只登记运营提供的密钥版本引用和策略摘要,请勿输入真实密钥值。部署进程按受控策略取得应用密钥,编码 Agent 不会从此表单获得密钥。 + +