Compare commits

..
2 Commits
9 changed files with 493 additions and 29 deletions
+41
View File
@@ -0,0 +1,41 @@
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import worker
class CadFormatTests(unittest.TestCase):
def test_source_format_variants(self) -> None:
self.assertEqual(worker.source_format_for_path(Path("model.STEP")), "step")
self.assertEqual(worker.source_format_for_path(Path("model.stp")), "step")
self.assertEqual(worker.source_format_for_path(Path("model.IGES")), "iges")
self.assertEqual(worker.source_format_for_path(Path("model.igs")), "iges")
self.assertIsNone(worker.source_format_for_path(Path("model.glb")))
def test_process_one_dispatches_iges_converter(self) -> None:
with tempfile.TemporaryDirectory() as directory:
worker.UPLOADS_DIR = Path(directory).resolve()
source_path = worker.UPLOADS_DIR / "model.igs"
source_path.write_bytes(b"IGES")
metadata = {
"artifact": "uploads/model.xkt",
"artifactType": "xkt",
"componentCount": 1,
}
with (
patch.object(worker, "find_ready_conversion_with_same_hash", return_value=None),
patch.object(worker, "convert_iges_assets", return_value=metadata) as convert_iges,
):
self.assertTrue(worker.process_one(source_path))
convert_iges.assert_called_once()
manifest = worker.read_json(worker.manifest_path(source_path))
self.assertEqual(manifest["sourceFormat"], "iges")
self.assertEqual(manifest["status"], "ready")
if __name__ == "__main__":
unittest.main()
+82 -20
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from typing import Any
from OCP.BRepMesh import BRepMesh_IncrementalMesh
from OCP.IGESCAFControl import IGESCAFControl_Reader
from OCP.Message import Message_ProgressRange
from OCP.RWGltf import RWGltf_CafWriter
from OCP.STEPCAFControl import STEPCAFControl_Reader
@@ -25,7 +26,7 @@ from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ShapeTool
CONVERTER_NAME = "NodeDcBimConverter"
CONVERTER_VERSION = "0.4.9"
CONVERTER_VERSION = "0.5.0"
UPLOADS_DIR = Path(os.environ.get("NODEDC_BIM_CONVERTER_UPLOADS_DIR", "/beam/uploads")).resolve()
POLL_INTERVAL_SECONDS = float(os.environ.get("NODEDC_BIM_CONVERTER_INTERVAL_SECONDS", "10"))
PROCESS_ONCE = os.environ.get("NODEDC_BIM_CONVERTER_ONCE", "").lower() in {"1", "true", "yes"}
@@ -73,6 +74,11 @@ CADQUERY_TIMEOUT_SECONDS = float(
os.environ.get("NODEDC_BIM_CONVERTER_CADQUERY_TIMEOUT_SECONDS", str(CONVERSION_TIMEOUT_SECONDS))
)
STEP_EXTENSIONS = {".step", ".stp"}
IGES_EXTENSIONS = {".iges", ".igs"}
CAD_SOURCE_FORMAT_BY_EXTENSION = {
**{extension: "step" for extension in STEP_EXTENSIONS},
**{extension: "iges" for extension in IGES_EXTENSIONS},
}
GLB_EXTENSIONS = {".glb"}
GLB_LOD_PROFILES = [
{
@@ -351,6 +357,9 @@ def find_ready_conversion_with_same_hash(source_path: Path, manifest: dict[str,
sha256 = manifest.get("sha256") or calculate_file_sha256(source_path)
if not sha256:
return None
source_format = source_format_for_path(source_path)
if not source_format:
return None
version_id = manifest.get("versionId")
version_number = manifest.get("version")
source_manifest_path = manifest_path(source_path).resolve()
@@ -373,7 +382,7 @@ def find_ready_conversion_with_same_hash(source_path: Path, manifest: dict[str,
update_asset_manifest_version(candidate_source_path, candidate)
if candidate_sha256 != sha256:
continue
if candidate.get("sourceFormat") != "step":
if candidate.get("sourceFormat") != source_format:
continue
if candidate.get("artifactType") != "xkt" and candidate.get("targetFormat") != "xkt":
continue
@@ -659,27 +668,43 @@ def gltf_component_tree(gltf_json: dict[str, Any], fallback_name: str) -> dict[s
}
def convert_step_xcaf_to_glb(source_path: Path, glb_path: Path) -> tuple[dict[str, Any], dict[str, Any]]:
def source_format_for_path(source_path: Path) -> str | None:
return CAD_SOURCE_FORMAT_BY_EXTENSION.get(source_path.suffix.lower())
def convert_cad_xcaf_to_glb(
source_path: Path,
glb_path: Path,
source_format: str,
) -> tuple[dict[str, Any], dict[str, Any]]:
app = XCAFApp_Application.GetApplication_s()
doc = TDocStd_Document(TCollection_ExtendedString("MDTV-XCAF"))
app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc)
print(f"[{CONVERTER_NAME}] STEPCAF read {source_path.name}", flush=True)
reader = STEPCAFControl_Reader()
if source_format == "step":
reader = STEPCAFControl_Reader()
reader_name = "STEPCAF"
elif source_format == "iges":
reader = IGESCAFControl_Reader()
reader_name = "IGESCAF"
else:
raise ValueError(f"Unsupported CAD source format: {source_format}")
print(f"[{CONVERTER_NAME}] {reader_name} read {source_path.name}", flush=True)
reader.SetNameMode(True)
reader.SetColorMode(True)
reader.SetLayerMode(True)
read_status = reader.ReadFile(str(source_path))
if "RetDone" not in str(read_status):
raise ValueError(f"STEPCAF read failed: {read_status}")
raise ValueError(f"{reader_name} read failed: {read_status}")
if not reader.Transfer(doc):
raise ValueError("STEPCAF transfer failed.")
raise ValueError(f"{reader_name} transfer failed.")
shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
labels = TDF_LabelSequence()
shape_tool.GetFreeShapes(labels)
if labels.Length() == 0:
raise ValueError("STEPCAF document has no free shapes.")
raise ValueError(f"{reader_name} document has no free shapes.")
print(
f"[{CONVERTER_NAME}] meshing {source_path.name}: "
@@ -710,6 +735,7 @@ def convert_step_xcaf_to_glb(source_path: Path, glb_path: Path) -> tuple[dict[st
gltf_json, renamed_nodes = normalize_glb_node_names(glb_path)
tree = gltf_component_tree(gltf_json, source_path.stem)
stats = {
"sourceFormat": source_format,
"freeShapeCount": labels.Length(),
"gltfNodeCount": len(gltf_json.get("nodes", [])),
"gltfMeshCount": len(gltf_json.get("meshes", [])),
@@ -841,7 +867,7 @@ def convert_glb_to_xkt(glb_path: Path, xkt_path: Path) -> dict[str, Any]:
}
def build_step_metadata(
def build_cad_metadata(
source_path: Path,
glb_path: Path,
xkt_path: Path,
@@ -850,6 +876,7 @@ def build_step_metadata(
tree: dict[str, Any],
stats: dict[str, Any],
import_strategy: str,
source_format: str,
) -> dict[str, Any]:
xkt_stats = convert_glb_to_xkt(glb_path, xkt_path)
has_xkt = bool(xkt_stats.get("enabled") and xkt_path.exists())
@@ -862,7 +889,7 @@ def build_step_metadata(
"artifactType": preferred_artifact_type,
"glbArtifact": src_from_path(glb_path),
"xktArtifact": src_from_path(xkt_path) if has_xkt else None,
"format": "step",
"format": source_format,
"targetFormat": "xkt" if has_xkt else "glb",
"importStrategy": import_strategy,
"componentTree": tree,
@@ -881,9 +908,14 @@ def build_step_metadata(
return metadata
def convert_step_xcaf_to_glb_process(source_path: str, glb_path: str, result_path: str) -> None:
def convert_cad_xcaf_to_glb_process(
source_path: str,
glb_path: str,
source_format: str,
result_path: str,
) -> None:
try:
tree, stats = convert_step_xcaf_to_glb(Path(source_path), Path(glb_path))
tree, stats = convert_cad_xcaf_to_glb(Path(source_path), Path(glb_path), source_format)
write_json_atomic(Path(result_path), {"ok": True, "tree": tree, "stats": stats})
except Exception as exc:
write_json_atomic(Path(result_path), {"ok": False, "error": str(exc)})
@@ -960,7 +992,7 @@ def run_cadquery_stage_with_timeout(result_path: Path, source_path: Path, glb_pa
return result
def run_step_glb_stage_with_timeout(
def run_cad_glb_stage_with_timeout(
stage_name: str,
timeout_seconds: float,
target: Any,
@@ -1031,7 +1063,7 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
"renamedNodeCount": (previous_stats.get("renamedNodeCount") or 0) + renamed_nodes,
"reusedExistingGlb": True,
}
return build_step_metadata(
return build_cad_metadata(
source_path,
glb_path,
xkt_path,
@@ -1039,18 +1071,20 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
tree=previous_metadata["componentTree"],
stats=stats,
import_strategy=previous_metadata.get("importStrategy") or "existing-glb",
source_format="step",
)
import_strategy = "occt-xcaf-gltf"
result_path = metadata_path.with_name(f"{metadata_path.name}.stage-result.json")
try:
result = run_step_glb_stage_with_timeout(
result = run_cad_glb_stage_with_timeout(
"OCCT/XCAF",
XCAF_TIMEOUT_SECONDS,
convert_step_xcaf_to_glb_process,
convert_cad_xcaf_to_glb_process,
result_path,
str(source_path),
str(glb_path),
"step",
)
tree = result["tree"]
stats = result["stats"]
@@ -1072,7 +1106,7 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
"fallbackReason": str(exc),
}
return build_step_metadata(
return build_cad_metadata(
source_path,
glb_path,
xkt_path,
@@ -1080,6 +1114,30 @@ def convert_step_assets(source_path: Path, glb_path: Path, xkt_path: Path, metad
tree=tree,
stats=stats,
import_strategy=import_strategy,
source_format="step",
)
def convert_iges_assets(source_path: Path, glb_path: Path, xkt_path: Path, metadata_path: Path) -> dict[str, Any]:
result_path = metadata_path.with_name(f"{metadata_path.name}.stage-result.json")
result = run_cad_glb_stage_with_timeout(
"IGES OCCT/XCAF",
XCAF_TIMEOUT_SECONDS,
convert_cad_xcaf_to_glb_process,
result_path,
str(source_path),
str(glb_path),
"iges",
)
return build_cad_metadata(
source_path,
glb_path,
xkt_path,
metadata_path,
tree=result["tree"],
stats=result["stats"],
import_strategy="occt-xcaf-gltf",
source_format="iges",
)
@@ -1113,6 +1171,9 @@ def process_one(source_path: Path) -> bool:
xkt_path = source_path.with_name(f"{stem}.xkt")
metadata_path = source_path.with_name(f"{stem}.metadata.json")
manifest = read_json(manifest_file)
source_format = source_format_for_path(source_path)
if not source_format:
return False
if not should_process(source_path, manifest, glb_path, xkt_path):
return False
@@ -1140,7 +1201,7 @@ def process_one(source_path: Path) -> bool:
"componentTreeRequired": True,
"converterName": CONVERTER_NAME,
"converterVersion": CONVERTER_VERSION,
"sourceFormat": "step",
"sourceFormat": source_format,
"sourceSrc": src_from_path(source_path),
"targetFormat": "xkt" if XKT_ENABLED else "glb",
}
@@ -1215,7 +1276,8 @@ def process_one(source_path: Path) -> bool:
print(f"[{CONVERTER_NAME}] converting {source_path}", flush=True)
try:
metadata = convert_step_assets(source_path, glb_path, xkt_path, metadata_path)
converter = convert_step_assets if source_format == "step" else convert_iges_assets
metadata = converter(source_path, glb_path, xkt_path, metadata_path)
artifact_src = metadata.get("artifact") or src_from_path(xkt_path if xkt_path.exists() else glb_path)
artifact_type = metadata.get("artifactType") or ("xkt" if xkt_path.exists() else "gltf")
ready_manifest = {
@@ -1943,7 +2005,7 @@ def scan_once() -> int:
continue
suffix = source_path.suffix.lower()
did_process = False
if suffix in STEP_EXTENSIONS:
if suffix in CAD_SOURCE_FORMAT_BY_EXTENSION:
did_process = process_one(source_path)
elif suffix in GLB_EXTENSIONS:
did_process = convert_glb_to_xkt_one(source_path)
+16 -2
View File
@@ -686,6 +686,7 @@ const hasModelSettingsTarget = () => !!getModelSettingsSrc(getPrimaryModelEntry(
const isGuestMode = () => viewerMode === "guest";
const isGuestToolbarAction = (action) => GUEST_TOOLBAR_ACTIONS.has(action);
const isTaskerEmbedMode = () => window.location.pathname === "/embed/tasker";
const getShareTokenFromPath = () => {
const match = window.location.pathname.match(/^\/share\/([^/?#]+)/);
@@ -2253,6 +2254,17 @@ const applyRuntimeMode = () => {
};
const initializeRuntimeMode = async () => {
if (isTaskerEmbedMode()) {
viewerMode = "guest";
runtimeSessionInfo = {
authRequired: true,
authenticated: false,
canShare: false,
user: null,
};
applyRuntimeMode();
return;
}
const shareToken = getShareTokenFromPath();
const shareGuestAuthMarker = hasShareGuestAuthMarker();
if (shareToken) {
@@ -5984,8 +5996,10 @@ const applyViewerState = (state) => {
const initViewer = async () => {
await initializeRuntimeMode();
setupNodeDCSessionSync();
setupNodeDCSessionWatcher();
if (!isTaskerEmbedMode()) {
setupNodeDCSessionSync();
setupNodeDCSessionWatcher();
}
const sdk = await import(SDK_URL);
sdkRef = sdk;
+10
View File
@@ -0,0 +1,10 @@
export const CONVERTIBLE_MODEL_FORMATS = new Map([
[".step", "step"],
[".stp", "step"],
[".iges", "iges"],
[".igs", "iges"]
]);
export const conversionQueuedMessage = (sourceFormat) =>
`Оригинальный ${String(sourceFormat || "CAD").toUpperCase()} загружен. ` +
"Просмотр появится после подготовки модели и дерева компонентов.";
+21
View File
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import {CONVERTIBLE_MODEL_FORMATS, conversionQueuedMessage} from "./cad-formats.js";
test("routes STEP and IGES filename variants to canonical converter formats", () => {
assert.deepEqual(
Object.fromEntries(CONVERTIBLE_MODEL_FORMATS),
{
".step": "step",
".stp": "step",
".iges": "iges",
".igs": "iges"
}
);
});
test("conversion message names the canonical source format", () => {
assert.match(conversionQueuedMessage("iges"), /IGES/);
assert.match(conversionQueuedMessage("step"), /STEP/);
});
+55 -6
View File
@@ -5,6 +5,13 @@ import path from "path";
import {fileURLToPath} from "url";
import crypto from "crypto";
import {pipeline} from "stream/promises";
import {CONVERTIBLE_MODEL_FORMATS, conversionQueuedMessage} from "./cad-formats.js";
import {
getTaskerGatewayUser,
isAuthorizedTaskerGatewayRequest,
taskerEmbedQueryMatchesClaims,
verifyTaskerEmbedToken
} from "./tasker-gateway-auth.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -52,6 +59,7 @@ const INTERNAL_ACCESS_TOKEN =
process.env.NODEDC_INTERNAL_ACCESS_TOKEN ||
process.env.NODEDC_PLATFORM_SERVICE_TOKEN ||
"";
const BIM_EMBED_SECRET = process.env.NODEDC_BIM_EMBED_SECRET || INTERNAL_ACCESS_TOKEN;
const BIM_SESSION_COOKIE = process.env.NODEDC_BIM_SESSION_COOKIE || "nodedc_bim_session";
const BIM_HANDOFF_COOKIE = process.env.NODEDC_BIM_HANDOFF_COOKIE || "nodedc_bim_handoff";
const BIM_SESSION_TTL_MS = Number(process.env.NODEDC_BIM_SESSION_TTL_MS || 12 * 60 * 60 * 1000);
@@ -87,14 +95,12 @@ const MIME_TYPES = {
".bim": "application/octet-stream",
".step": "application/octet-stream",
".stp": "application/octet-stream",
".iges": "application/octet-stream",
".igs": "application/octet-stream",
".wasm": "application/wasm",
".txt": "text/plain"
};
const CONVERTIBLE_MODEL_FORMATS = new Map([
[".step", "step"],
[".stp", "step"]
]);
const GLB_DRACO_OPTIMIZABLE_FORMATS = new Set(["glb"]);
const GLB_XKT_CONVERTIBLE_FORMATS = new Set(["glb"]);
const GLB_LOD_SOURCE_FORMATS = new Set(["glb"]);
@@ -262,6 +268,10 @@ const localDevRegistryUser = () => ({
});
const getRequestRegistryUser = (req) => {
const taskerUser = normalizeRegistryUser(getTaskerGatewayUser(req, INTERNAL_ACCESS_TOKEN));
if (taskerUser) {
return taskerUser;
}
const sessionUser = normalizeRegistryUser(getCurrentBimSession(req)?.user);
if (sessionUser) {
return sessionUser;
@@ -998,6 +1008,9 @@ const handleLauncherOwnedNavigation = (req, res, url) => {
if (!BIM_AUTH_REQUIRED || !INTERNAL_ACCESS_TOKEN || !isHtmlNavigation(req, url)) {
return false;
}
if (req.__taskerEmbedClaims) {
return false;
}
if (isPublicSharePath(url) && url.searchParams.get(SHARE_AUTH_GUEST_PARAM) === "1") {
destroyCurrentBimSession(req, res);
clearBimHandoffCookie(res);
@@ -1052,10 +1065,27 @@ const isHtmlNavigation = (req, url) => {
const isPublicSharePath = (url) => /^\/share\/[^/]+\/?$/.test(url.pathname);
const isTaskerGatewayApiRequest = (req, url) => {
if (!isAuthorizedTaskerGatewayRequest(req, INTERNAL_ACCESS_TOKEN)) {
return false;
}
const routeKey = `${req.method || "GET"} ${url.pathname}`;
return new Set([
"POST /api/uploads",
"DELETE /api/uploads/asset",
"DELETE /api/uploads/version",
"GET /api/uploads/versions",
"GET /api/conversions/status"
]).has(routeKey);
};
const requestNeedsBimSession = (req, url) => {
if (!BIM_AUTH_REQUIRED) {
return false;
}
if (req.__taskerEmbedClaims || isTaskerGatewayApiRequest(req, url)) {
return false;
}
if (url.pathname.startsWith("/auth/") || url.pathname === "/api/auth/session") {
return false;
}
@@ -1362,6 +1392,9 @@ const serveStatic = async (req, res, url) => {
const mime = MIME_TYPES[ext] || "application/octet-stream";
res.statusCode = 200;
res.setHeader("Content-Type", mime);
if (req.__taskerEmbedClaims) {
res.setHeader("Cache-Control", "no-store");
}
createReadStream(targetPath).pipe(res).on("error", (err) => {
console.error("[server] failed to stream file", err);
if (!res.headersSent) {
@@ -2854,7 +2887,7 @@ const handleRawUpload = async (req, res, url) => {
const conversion = {
...versionRecord,
componentTreeRequired: true,
message: "Оригинальный STEP загружен. Просмотр появится после подготовки модели и дерева компонентов.",
message: conversionQueuedMessage(sourceFormat),
sourceFormat,
status: "conversion_required",
targetFormat: "xkt",
@@ -3275,7 +3308,7 @@ const handleConversionStatus = async (res, searchParams) => {
if (!manifest) {
sendJSON(res, 200, {
componentTreeRequired: true,
message: "Оригинальный STEP загружен. Просмотр появится после подготовки модели и дерева компонентов.",
message: conversionQueuedMessage(sourceFormat),
sourceFormat,
sourceSrc: srcFromUploadPath(sourcePath),
status: "conversion_required",
@@ -3804,6 +3837,22 @@ const requestHandler = async (req, res) => {
return handleAuthSession(req, res);
}
if (url.pathname === "/embed/tasker") {
if (req.method !== "GET" && req.method !== "HEAD") {
sendText(res, 405, "Method Not Allowed");
return;
}
const verification = verifyTaskerEmbedToken(url.searchParams.get("token") || "", BIM_EMBED_SECRET);
if (!verification.ok || !taskerEmbedQueryMatchesClaims(url, verification.claims)) {
sendJSON(res, 401, {
ok: false,
error: verification.error || "tasker_embed_query_invalid"
});
return;
}
req.__taskerEmbedClaims = verification.claims;
}
if (req.method === "GET" && url.pathname === "/auth/nodedc/handoff") {
return handleLauncherHandoff(req, res, url);
}
+2 -1
View File
@@ -5,6 +5,7 @@
"version": "0.1.0",
"description": "Lightweight file-based API for xeokit BIM viewer projects",
"scripts": {
"start": "node index.js"
"start": "node index.js",
"test": "node --test cad-formats.test.js tasker-gateway-auth.test.js"
}
}
+164
View File
@@ -0,0 +1,164 @@
import crypto from "crypto";
export const TASKER_EMBED_AUDIENCE = "nodedc-bim-tasker-embed";
export const TASKER_EMBED_ISSUER = "nodedc-tasker";
const stringOrNull = (value) => {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed || null;
};
const constantTimeEqual = (first, second) => {
if (!first || !second) {
return false;
}
const firstBuffer = Buffer.from(String(first), "utf8");
const secondBuffer = Buffer.from(String(second), "utf8");
return firstBuffer.length === secondBuffer.length && crypto.timingSafeEqual(firstBuffer, secondBuffer);
};
const bearerTokenFromRequest = (req) => {
const authorization = Array.isArray(req?.headers?.authorization)
? req.headers.authorization[0]
: req?.headers?.authorization;
if (typeof authorization !== "string" || !authorization.toLowerCase().startsWith("bearer ")) {
return "";
}
return authorization.slice(7).trim();
};
export const isAuthorizedTaskerGatewayRequest = (req, internalAccessToken) => {
const service = Array.isArray(req?.headers?.["x-nodedc-service"])
? req.headers["x-nodedc-service"][0]
: req?.headers?.["x-nodedc-service"];
return service === "tasker" && constantTimeEqual(bearerTokenFromRequest(req), internalAccessToken);
};
export const getTaskerGatewayUser = (req, internalAccessToken) => {
if (!isAuthorizedTaskerGatewayRequest(req, internalAccessToken)) {
return null;
}
const headerValue = (name) => {
const value = req?.headers?.[name];
return stringOrNull(Array.isArray(value) ? value[0] : value);
};
const id = headerValue("x-nodedc-user-id");
if (!id) {
return null;
}
return {
id,
email: headerValue("x-nodedc-user-email"),
name: "NODE.DC Ops attachment",
subject: null,
authentikUserId: null,
groups: []
};
};
const decodeBase64Url = (value) => {
if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) {
throw new Error("invalid_base64url");
}
const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
return Buffer.from(padded, "base64");
};
const isManagedAssetSrc = (value) => {
if (typeof value !== "string" || !value.startsWith("/")) {
return false;
}
let parsed;
try {
parsed = new URL(value, "http://tasker-embed.local");
} catch (_) {
return false;
}
return parsed.origin === "http://tasker-embed.local" &&
(parsed.pathname.startsWith("/uploads/") || parsed.pathname.startsWith("/data/"));
};
const normalizeEmbedModel = (value) => {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return null;
}
const model = {
url: stringOrNull(value.url),
settingsSrc: stringOrNull(value.settingsSrc),
type: stringOrNull(value.type),
name: stringOrNull(value.name)
};
if (!isManagedAssetSrc(model.url) || !isManagedAssetSrc(model.settingsSrc) || !model.type || !model.name) {
return null;
}
return model;
};
export const verifyTaskerEmbedToken = (token, secret, {nowSeconds = Math.floor(Date.now() / 1000)} = {}) => {
if (!secret || typeof token !== "string" || token.length > 8192) {
return {ok: false, error: "tasker_embed_token_invalid"};
}
const parts = token.split(".");
if (parts.length !== 2) {
return {ok: false, error: "tasker_embed_token_invalid"};
}
const [encodedPayload, encodedSignature] = parts;
let providedSignature;
try {
providedSignature = decodeBase64Url(encodedSignature);
} catch (_) {
return {ok: false, error: "tasker_embed_token_invalid"};
}
const expectedSignature = crypto.createHmac("sha256", secret).update(encodedPayload, "ascii").digest();
if (
providedSignature.length !== expectedSignature.length ||
!crypto.timingSafeEqual(providedSignature, expectedSignature)
) {
return {ok: false, error: "tasker_embed_signature_invalid"};
}
let claims;
try {
claims = JSON.parse(decodeBase64Url(encodedPayload).toString("utf8"));
} catch (_) {
return {ok: false, error: "tasker_embed_token_invalid"};
}
const model = normalizeEmbedModel(claims?.model);
const requiredStrings = ["sub", "workspace", "project", "issue", "attachment"];
if (
claims?.v !== 1 ||
claims?.aud !== TASKER_EMBED_AUDIENCE ||
claims?.iss !== TASKER_EMBED_ISSUER ||
!Number.isInteger(claims?.iat) ||
!Number.isInteger(claims?.exp) ||
claims.iat > nowSeconds + 60 ||
claims.exp <= nowSeconds ||
claims.exp - claims.iat > 600 ||
requiredStrings.some((key) => !stringOrNull(claims?.[key])) ||
!model
) {
return {ok: false, error: "tasker_embed_claims_invalid"};
}
return {
ok: true,
claims: {
...claims,
model
}
};
};
export const taskerEmbedQueryMatchesClaims = (url, claims) => {
if (!url || !claims?.model) {
return false;
}
const expected = claims.model;
return url.searchParams.get("url") === expected.url &&
url.searchParams.get("settingsSrc") === expected.settingsSrc &&
url.searchParams.get("type") === expected.type &&
url.searchParams.get("name") === expected.name;
};
+102
View File
@@ -0,0 +1,102 @@
import assert from "node:assert/strict";
import crypto from "node:crypto";
import test from "node:test";
import {
getTaskerGatewayUser,
isAuthorizedTaskerGatewayRequest,
taskerEmbedQueryMatchesClaims,
verifyTaskerEmbedToken
} from "./tasker-gateway-auth.js";
const encode = (value) => Buffer.from(value).toString("base64url");
const sign = (payload, secret = "test-secret") => {
const encodedPayload = encode(JSON.stringify(payload));
const signature = crypto.createHmac("sha256", secret).update(encodedPayload, "ascii").digest("base64url");
return `${encodedPayload}.${signature}`;
};
const claims = (overrides = {}) => ({
v: 1,
aud: "nodedc-bim-tasker-embed",
iss: "nodedc-tasker",
iat: 1000,
exp: 1180,
sub: "user-1",
workspace: "workspace",
project: "project-1",
issue: "issue-1",
attachment: "attachment-1",
model: {
url: "/uploads/project/asset/ver_0001/model.xkt",
settingsSrc: "/uploads/project/asset/ver_0001/model.step",
type: "xkt",
name: "model.step"
},
...overrides
});
test("Tasker service bearer is accepted only with the Tasker service marker", () => {
const request = {
headers: {
authorization: "Bearer internal-token",
"x-nodedc-service": "tasker",
"x-nodedc-user-id": "tasker-attachment:123",
"x-nodedc-user-email": "user@example.com"
}
};
assert.equal(isAuthorizedTaskerGatewayRequest(request, "internal-token"), true);
assert.deepEqual(getTaskerGatewayUser(request, "internal-token"), {
id: "tasker-attachment:123",
email: "user@example.com",
name: "NODE.DC Ops attachment",
subject: null,
authentikUserId: null,
groups: []
});
assert.equal(isAuthorizedTaskerGatewayRequest(request, "wrong-token"), false);
assert.equal(
isAuthorizedTaskerGatewayRequest(
{headers: {...request.headers, "x-nodedc-service": "another-service"}},
"internal-token"
),
false
);
});
test("valid short-lived Tasker embed token and matching model query are accepted", () => {
const result = verifyTaskerEmbedToken(sign(claims()), "test-secret", {nowSeconds: 1050});
assert.equal(result.ok, true);
const url = new URL("https://bim.example/embed/tasker");
Object.entries(result.claims.model).forEach(([key, value]) => url.searchParams.set(key, value));
assert.equal(taskerEmbedQueryMatchesClaims(url, result.claims), true);
});
test("tampered, expired, and overlong Tasker embed grants are rejected", () => {
const valid = sign(claims());
assert.equal(
verifyTaskerEmbedToken(`${valid.slice(0, -1)}x`, "test-secret", {nowSeconds: 1050}).ok,
false
);
assert.equal(verifyTaskerEmbedToken(sign(claims({exp: 1049})), "test-secret", {nowSeconds: 1050}).ok, false);
assert.equal(
verifyTaskerEmbedToken(sign(claims({exp: 1700})), "test-secret", {nowSeconds: 1050}).ok,
false
);
});
test("embed grant cannot point the viewer at an external or substituted model", () => {
const external = verifyTaskerEmbedToken(
sign(claims({model: {...claims().model, url: "https://attacker.example/model.xkt"}})),
"test-secret",
{nowSeconds: 1050}
);
assert.equal(external.ok, false);
const valid = verifyTaskerEmbedToken(sign(claims()), "test-secret", {nowSeconds: 1050});
const url = new URL("https://bim.example/embed/tasker");
Object.entries(valid.claims.model).forEach(([key, value]) => url.searchParams.set(key, value));
url.searchParams.set("url", "/uploads/another/model.xkt");
assert.equal(taskerEmbedQueryMatchesClaims(url, valid.claims), false);
});