fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "@siax/0pt-decision",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": { ".": "./src/index.ts" },
|
||||
"scripts": { "test": "echo 'no tests yet'" }
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* `@siax/0pt-decision` — 0pt ER via siax-decision (:4600).
|
||||
*
|
||||
* Kaskad: hard rules + weighted-scoring (D0) → decision.match (D1-advisory)
|
||||
* för pending_review-ambiguitet → ABSTAINED/decision-nere → pending_review
|
||||
* gäller (fail-closed, aldrig fabricerat). 0pt behåller provenance-semantik.
|
||||
*/
|
||||
|
||||
const DECISION_URL = process.env.DECISION_API_URL ?? "http://127.0.0.1:4600";
|
||||
const DECISION_TOKEN = process.env.DECISION_TOKEN ?? "";
|
||||
const DECISION_TIMEOUT_MS = Number(process.env.DECISION_TIMEOUT_MS ?? 2000);
|
||||
|
||||
export interface DecisionMatch {
|
||||
decided: boolean;
|
||||
label?: "match" | "pending_review" | "non_match";
|
||||
confidence?: number;
|
||||
model?: string;
|
||||
latencyMs?: number;
|
||||
}
|
||||
|
||||
/** decision.match för ER-pair (semantic tie-break vid gränsfall). */
|
||||
export async function erMatchDecision(pair: {
|
||||
record_a: string;
|
||||
record_b: string;
|
||||
similarities: Array<{ field: string; similarity: number; weight: number }>;
|
||||
}): Promise<{ decided: boolean; label?: string; confidence?: number; model?: string; latencyMs?: number }> {
|
||||
try {
|
||||
const res = await fetch(`${DECISION_URL}/decision/match`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${DECISION_TOKEN}` },
|
||||
body: JSON.stringify({
|
||||
decision: "0pt.er.pair_match",
|
||||
left: { record_id: pair.record_a },
|
||||
right: [{ record_id: pair.record_b }],
|
||||
instructions: "Do these two entity records refer to the same real-world entity?",
|
||||
minConfidence: 0.7,
|
||||
context: { field_similarities: pair.similarities },
|
||||
}),
|
||||
signal: AbortSignal.timeout(DECISION_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) return { decided: false };
|
||||
const out = (await res.json()) as { data?: { status?: string; choice?: string; confidence?: number; model?: string; latencyMs?: number } };
|
||||
const d = out.data;
|
||||
if (!d || d.status !== "DECIDED") return { decided: false, confidence: d?.confidence };
|
||||
const label = String(d.choice ?? "pending_review");
|
||||
return {
|
||||
decided: true,
|
||||
label: label === "0" ? "non_match" : label === "1" ? "match" : (label as "match" | "pending_review" | "non_match"),
|
||||
confidence: d.confidence,
|
||||
model: d.model,
|
||||
latencyMs: d.latencyMs,
|
||||
};
|
||||
} catch {
|
||||
return { decided: false };
|
||||
}
|
||||
}
|
||||
|
||||
/** Optional gate: enabled via OPT_DECISION_ER_ENABLED=1 (off tills kalibrering). */
|
||||
export function erDecisionEnabled(): boolean {
|
||||
const v = process.env.OPT_DECISION_ER_ENABLED;
|
||||
return v === "1" || v === "true";
|
||||
}
|
||||
|
||||
// --- Shadow-eval (Jev-everywhere): auto-match-kvalitet mäts, påverkar ALDRIG ---
|
||||
export interface ErAutoMatchShadowInput {
|
||||
tenant_id: string;
|
||||
/** Målentiteten som auto-matchats av D0-tröskeln. */
|
||||
target: { record_id: string; fields?: Record<string, unknown> };
|
||||
/** Kandidaterna (tie-set) som D0 matchade mot målet. */
|
||||
candidates: Array<{ record_id: string; fields?: Record<string, unknown> }>;
|
||||
/** D0-score som triggade auto-matchen (skickas som kontext till beslutsplanet). */
|
||||
score?: number;
|
||||
}
|
||||
|
||||
export interface ErShadowResult {
|
||||
decided: boolean;
|
||||
choice?: string;
|
||||
confidence?: number;
|
||||
model?: string;
|
||||
latencyMs?: number;
|
||||
}
|
||||
|
||||
/** Shadow-gate: OPT_DECISION_ER_SHADOW=1 (OFF by default — fire-and-forget).
|
||||
* Coolify avvisar env-nycklar som borjar med siffra ("0PT_..."), sa gaten
|
||||
* heter OPT_DECISION_ER_SHADOW; det gamla 0PT_-namnet accepteras for
|
||||
* bakatkompatibilitet (t.ex. systemd/docker-miljor utan Coolify). */
|
||||
export function erAutoMatchShadowEnabled(): boolean {
|
||||
return process.env.OPT_DECISION_ER_SHADOW === "1" || process.env["0PT_DECISION_ER_SHADOW"] === "1";
|
||||
}
|
||||
|
||||
/**
|
||||
* Shadow-eval av D0 auto-match: POST /decision/match (decisionId
|
||||
* `0pt.er.auto_match`). D0-tröskeln förblir auktoritet — svaret används endast
|
||||
* för kalibrering (decision-planen loggar inbyggt → AUD0). Fail-closed:
|
||||
* gate-off, nätverksfel, timeout eller ABSTAINED → null / decided:false,
|
||||
* kastar ALDRIG.
|
||||
*/
|
||||
export async function erAutoMatchShadow(
|
||||
input: ErAutoMatchShadowInput,
|
||||
): Promise<ErShadowResult | null> {
|
||||
if (!erAutoMatchShadowEnabled()) return null;
|
||||
try {
|
||||
const res = await fetch(`${DECISION_URL}/decision/match`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${DECISION_TOKEN}` },
|
||||
body: JSON.stringify({
|
||||
decision: "0pt.er.auto_match",
|
||||
left: input.target,
|
||||
right: input.candidates,
|
||||
instructions: "Which candidate is the same entity as the target?",
|
||||
minConfidence: 0.7,
|
||||
context: { tenant_id: input.tenant_id, d0_score: input.score },
|
||||
}),
|
||||
signal: AbortSignal.timeout(DECISION_TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const out = (await res.json()) as {
|
||||
data?: { status?: string; choice?: string; confidence?: number; model?: string; latencyMs?: number };
|
||||
};
|
||||
const d = out.data;
|
||||
if (!d || d.status !== "DECIDED") return { decided: false, confidence: d?.confidence };
|
||||
return {
|
||||
decided: true,
|
||||
choice: String(d.choice ?? ""),
|
||||
confidence: d.confidence,
|
||||
model: d.model,
|
||||
latencyMs: d.latencyMs,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"$id": "0pt.dataset_iceberg_mapping.schema.v1",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"dataset_iceberg_mapping_id",
|
||||
"tenant_id",
|
||||
"project_id",
|
||||
"dataset_id",
|
||||
"iceberg_table_id",
|
||||
"mapping_status",
|
||||
"mapped_at",
|
||||
"created_at"
|
||||
],
|
||||
"properties": {
|
||||
"dataset_iceberg_mapping_id": { "type": "string" },
|
||||
"tenant_id": { "type": "string" },
|
||||
"project_id": { "type": "string" },
|
||||
"dataset_id": { "type": "string", "description": "References 0pt.dataset.schema.v1's dataset_id." },
|
||||
"iceberg_table_id": {
|
||||
"type": "string",
|
||||
"description": "Reference into ST0RE's table registry (IcebergTable.tableId, st0re_iceberg_tables). Never a copy of ST0RE's table row."
|
||||
},
|
||||
"namespace_id": {
|
||||
"type": "string",
|
||||
"description": "Reference into ST0RE's namespace registry (LakehouseNamespace.namespaceId, /v1/st0re/lakehouse/namespaces). The literal field name this contract's task spec requires."
|
||||
},
|
||||
"namespace": { "type": "string", "description": "ST0RE lakehouse namespace NAME, carried for convenience/filtering only." },
|
||||
"table_name": { "type": "string" },
|
||||
"mapping_status": { "type": "string", "enum": ["pending", "active", "deprecated", "archived"] },
|
||||
"mapped_at": { "type": "string", "description": "When this mapping was created/last (re)mapped." },
|
||||
"mapped_by": { "type": "string" },
|
||||
"correlation_id": { "type": "string" },
|
||||
"created_at": { "type": "string" },
|
||||
"updated_at": { "type": "string" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$id": "0pt.iceberg_table.schema.v1",
|
||||
"description": "NON-AUTHORITATIVE READ CACHE ONLY. ST0RE owns Iceberg table/catalog/snapshot state (docs/ICEBERG_WRITE_BOUNDARY.md, src/clients/st0re-lakehouse-client.ts's St0reIcebergTable). This schema mirrors that shape for tests/p0/enterprise-data-os-expansion.test.ts's contract assertions from an earlier pass; 0pt must never write to it as a second copy of ST0RE's table registry -- see docs/ICEBERG_WRITE_BOUNDARY.md's 'A pre-existing artifact' section.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"table_id",
|
||||
"tenant_id",
|
||||
"project_id",
|
||||
"table_name",
|
||||
"namespace",
|
||||
"storage_uri",
|
||||
"catalog_ref",
|
||||
"table_format",
|
||||
"status",
|
||||
"created_at"
|
||||
],
|
||||
"properties": {
|
||||
"table_id": { "type": "string", "description": "Reference into ST0RE's table registry (IcebergTable.tableId, st0re_iceberg_tables)." },
|
||||
"tenant_id": { "type": "string" },
|
||||
"project_id": { "type": "string" },
|
||||
"table_name": { "type": "string" },
|
||||
"namespace": { "type": "string", "description": "ST0RE lakehouse namespace name." },
|
||||
"storage_uri": { "type": "string", "description": "Object-store URI for the table's data/metadata, e.g. s3://siax-tenants/.../table." },
|
||||
"catalog_ref": { "type": "string", "description": "Opaque reference into the external Iceberg catalog — ST0RE does not resolve it." },
|
||||
"dataset_id": { "type": "string", "description": "ST0RE's OWN dataset foreign key as mirrored from its table row — NOT 0pt's dataset_id. 0pt must never send its own dataset_id here (it 400s with a Postgres FK violation); the 0pt-side dataset<->table link lives in DatasetIcebergMapping.iceberg_table_id. See docs/ICEBERG_WRITE_BOUNDARY.md." },
|
||||
"table_format": { "type": "string", "enum": ["iceberg", "delta", "hudi"] },
|
||||
"current_snapshot_id": { "type": "string" },
|
||||
"schema_version": { "type": "string" },
|
||||
"partition_spec": { "type": "array", "items": { "type": "string" } },
|
||||
"retention_policy": { "type": "string" },
|
||||
"data_residency": { "type": "string" },
|
||||
"pii_level": { "type": "string", "enum": ["none", "low", "medium", "high"] },
|
||||
"owner_product": { "type": "string" },
|
||||
"status": { "type": "string", "enum": ["active", "deprecated", "archived"] },
|
||||
"correlation_id": { "type": "string" },
|
||||
"created_at": { "type": "string" },
|
||||
"created_by": { "type": "string" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"$id": "0pt.lineage_event.schema.v1",
|
||||
"description": "CONTRACT-ONLY -- 0pt's real lineage emissions today go through Aud0Client.ingestLineageEvent (src/clients/aud0-client.ts), whose Aud0LineageEvent shape is source_type/source_id -> target_type/target_id, not input_assets/output_assets. This wider multi-asset shape exists so tests/p0/enterprise-data-os-expansion.test.ts's contract assertions (from an earlier 'PROMPT 2' pass) have a real file to check; it documents an intended future generalization (multi-input/multi-output lineage), not a built/wired capability. NOTE (GitHub<->Gitea unification merge): the two remotes disagreed on `producer` -- one modelled it as an object {app_id, capability_id}, the other as a string plus flat top-level app_id/capability_id. The structured object is kept as canonical here because it names both parts unambiguously; `event_type`, `app_id` and `capability_id` are retained as optional top-level properties so the flat draft's fields are not lost. Nothing in this repo reads or validates against this file, so neither choice changes behaviour.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"lineage_event_id",
|
||||
"tenant_id",
|
||||
"project_id",
|
||||
"producer",
|
||||
"input_assets",
|
||||
"output_assets",
|
||||
"created_at"
|
||||
],
|
||||
"properties": {
|
||||
"lineage_event_id": { "type": "string" },
|
||||
"tenant_id": { "type": "string" },
|
||||
"project_id": { "type": "string" },
|
||||
"event_type": { "type": "string", "description": "e.g. 0pt.lineage_emitted. From the flat draft; optional." },
|
||||
"app_id": { "type": "string", "description": "Flat-draft alternative to producer.app_id; optional." },
|
||||
"capability_id": { "type": "string", "description": "Flat-draft alternative to producer.capability_id; optional." },
|
||||
"producer": {
|
||||
"type": "object",
|
||||
"description": "The capability/app that produced this lineage edge.",
|
||||
"required": ["app_id", "capability_id"],
|
||||
"properties": {
|
||||
"app_id": { "type": "string" },
|
||||
"capability_id": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"input_assets": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["asset_type", "asset_id"],
|
||||
"properties": {
|
||||
"asset_type": { "type": "string", "enum": ["dataset", "iceberg_table", "artifact", "source", "document", "signal"] },
|
||||
"asset_id": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"output_assets": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["asset_type", "asset_id"],
|
||||
"properties": {
|
||||
"asset_type": { "type": "string", "enum": ["dataset", "iceberg_table", "artifact", "source", "document", "signal"] },
|
||||
"asset_id": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"st0re_artifacts": { "type": "array", "items": { "type": "string" } },
|
||||
"quality_report_id": { "type": "string" },
|
||||
"correlation_id": { "type": "string" },
|
||||
"created_at": { "type": "string" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"$id": "0pt.signal.schema.v1",
|
||||
"description": "CONTRACT-ONLY -- no service in this repo produces or reads 0pt.signal rows yet. This schema exists so tests/p0/enterprise-data-os-expansion.test.ts's contract assertions (from an earlier 'PROMPT 2' pass) have a real file to check; it is documentation of an intended shape for future ICP/signal-intelligence work, not a built capability. Do not treat it as evidence that signal detection is implemented. NOTE (GitHub<->Gitea unification merge): the two remotes named several fields differently (entity_id/entity_key, observed_at/detected_at, confidence_level/confidence). Both names are retained below as optional properties rather than dropping either draft's vocabulary; a future pass that actually builds signal detection must pick one pair and delete the other.",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"signal_id",
|
||||
"tenant_id",
|
||||
"project_id",
|
||||
"signal_type",
|
||||
"signal_strength",
|
||||
"entity_type",
|
||||
"entity_id",
|
||||
"observed_at",
|
||||
"created_at"
|
||||
],
|
||||
"properties": {
|
||||
"signal_id": { "type": "string" },
|
||||
"tenant_id": { "type": "string" },
|
||||
"project_id": { "type": "string" },
|
||||
"signal_type": { "type": "string", "description": "e.g. hiring_growth, funding_round, funding_event, tech_adoption, leadership_change." },
|
||||
"signal_strength": { "type": "number", "description": "Normalized 0..1 confidence/intensity of the signal.", "minimum": 0, "maximum": 1 },
|
||||
"entity_type": { "type": "string", "enum": ["company", "person", "contact", "domain", "vehicle"] },
|
||||
"entity_id": { "type": "string" },
|
||||
"entity_key": { "type": "string", "description": "Alternative name for entity_id from the other draft; optional." },
|
||||
"value": { "description": "Signal payload value (type depends on signal_type)." },
|
||||
"unit": { "type": "string" },
|
||||
"metadata": { "type": "object" },
|
||||
"source_id": { "type": "string", "description": "References 0pt.source.schema.v1's source_id." },
|
||||
"confidence_level": { "type": "string", "enum": ["low", "medium", "high"] },
|
||||
"confidence": { "type": "number", "minimum": 0, "maximum": 1, "description": "Numeric alternative to confidence_level from the other draft; optional." },
|
||||
"observed_at": { "type": "string" },
|
||||
"detected_at": { "type": "string", "description": "Alternative name for observed_at from the other draft; optional." },
|
||||
"correlation_id": { "type": "string" },
|
||||
"created_at": { "type": "string" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$id": "0pt.source_rate_policy.schema.v1",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"source_rate_policy_id",
|
||||
"tenant_id",
|
||||
"project_id",
|
||||
"source_id",
|
||||
"rate_limit_per_minute",
|
||||
"crawl_budget",
|
||||
"status",
|
||||
"created_at"
|
||||
],
|
||||
"properties": {
|
||||
"source_rate_policy_id": { "type": "string" },
|
||||
"tenant_id": { "type": "string" },
|
||||
"project_id": { "type": "string" },
|
||||
"source_id": { "type": "string", "description": "References 0pt.source.schema.v1's source_id." },
|
||||
"rate_limit_per_minute": { "type": "number" },
|
||||
"crawl_budget": { "type": "number", "description": "Max requests/pages/records this policy permits per crawl run or per day; unit documented in compliance_notes when non-obvious." },
|
||||
"compliance_notes": { "type": "string" },
|
||||
"domain": { "type": "string", "description": "Crawl-target domain, e.g. allabolag.se." },
|
||||
"robots_ok": { "type": "boolean" },
|
||||
"access": { "type": "string", "enum": ["api", "bulk", "authorized_web", "licensed"] },
|
||||
"status": { "type": "string", "enum": ["active", "paused", "deprecated"] },
|
||||
"correlation_id": { "type": "string" },
|
||||
"created_at": { "type": "string" },
|
||||
"updated_at": { "type": "string" },
|
||||
"created_by": { "type": "string" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@siax/0pt-schemas",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "BACKLOG P1-21: makes packages/schemas a real workspace package (it was previously loose JSON Schema files with no package.json, so pnpm-workspace.yaml's `packages/*` glob matched an empty package). Zero build step -- these files are consumed by path, not imported as JS.",
|
||||
"files": ["*.schema.json"],
|
||||
"license": "UNLICENSED"
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "@siax/access",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Universal, framework-neutral project/tenant relationship checks for SIAX Cloud (OpenFGA). Reused by 0pt, DOC0, N0D and other products instead of per-repo copies.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"license": "UNLICENSED"
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @siax/access idempotency primitives — the universal SIAX contract for any
|
||||
* operation that must either happen exactly once or replay its receipt.
|
||||
*
|
||||
* This package is derived from the pattern proven in 0pt's durable upload
|
||||
* attempts (prepare -> claim -> dispatch -> store receipt -> replay), then
|
||||
* generalized so DOC0, N0D and future products can adopt the identical shape
|
||||
* instead of re-implementing it.
|
||||
*
|
||||
* Rules encoded here:
|
||||
* 1. An operation identity binds EVERY result-affecting input (tenant,
|
||||
* project, actor, payload version). A changed payload under the same key
|
||||
* is a CONFLICT, never a replay of someone else's receipt.
|
||||
* 2. One claimant per key: returning `false` from `start` means another
|
||||
* caller owns the dispatch, and only the stored receipt (or bounded
|
||||
* observation) may be answered.
|
||||
* 3. A stored receipt is replayed verbatim; the caller never invents one.
|
||||
* 4. Commit boundaries: NEVER write a network command before the claim is
|
||||
* durably persisted, and never lose the claim after the command may have
|
||||
* committed.
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/** Stable JSON canonicalization (sorted array stays sorted; v-prefix bumped on contract change). */
|
||||
export function operationFingerprint(parts: readonly unknown[], version = "siax-idempotency-v1"): string {
|
||||
return createHash("sha256")
|
||||
.update(JSON.stringify([version, ...parts]))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
export interface OperationIdentity {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
/** Client-generated, transport-level key (<=256 visible ASCII). */
|
||||
idempotencyKey: string;
|
||||
/** Supply result-affecting inputs; the helper adds the scope fields itself. */
|
||||
payload: readonly unknown[];
|
||||
}
|
||||
|
||||
export function operationIdentity(operation: OperationIdentity): {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
idempotencyKey: string;
|
||||
fingerprint: string;
|
||||
} {
|
||||
if (
|
||||
!operation ||
|
||||
![operation.tenantId, operation.projectId, operation.actorId, operation.idempotencyKey].every(
|
||||
(value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._@:+-]{0,255}$/.test(value),
|
||||
) ||
|
||||
!Array.isArray(operation.payload)
|
||||
) {
|
||||
throw new Error("Invalid idempotent operation identity");
|
||||
}
|
||||
void operation.payload;
|
||||
return {
|
||||
tenantId: operation.tenantId,
|
||||
projectId: operation.projectId,
|
||||
actorId: operation.actorId,
|
||||
idempotencyKey: operation.idempotencyKey,
|
||||
fingerprint: operationFingerprint([
|
||||
operation.tenantId,
|
||||
operation.projectId,
|
||||
operation.actorId,
|
||||
...operation.payload,
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
export type OperationOutcome<R> =
|
||||
| { kind: "claimed"; execute: () => Promise<R> }
|
||||
| { kind: "replayed"; receipt: R }
|
||||
| { kind: "conflict"; expected?: string };
|
||||
|
||||
/** Structural contract for an attempt store. Matched by Postgres adapters per product. */
|
||||
export interface IdempotencyStore<Identity, Receipt> {
|
||||
/** Returns true when this caller won the right to dispatch; false = reuse replay path. */
|
||||
start(identity: Identity, fingerprint: string): Promise<boolean>;
|
||||
/** Persist after a verified downstream commit. Must never be called before. */
|
||||
save(identity: Identity, fingerprint: string, receipt: Receipt): Promise<void>;
|
||||
/** Load a stored receipt for replay (exact fingerprint match). */
|
||||
receipt(identity: Identity, fingerprint: string): Promise<Receipt | undefined>;
|
||||
}
|
||||
|
||||
export type IdempotentStoreItemIdentity<I> = {
|
||||
identity: I;
|
||||
fingerprint: string;
|
||||
};
|
||||
|
||||
export async function runIdempotentOperation<I, R>(input: {
|
||||
store: IdempotencyStore<I, R>;
|
||||
identity: I;
|
||||
fingerprint: string;
|
||||
/** Must be safe to call exactly once; a second call is never attempted here. */
|
||||
dispatch: () => Promise<R>;
|
||||
}): Promise<OperationOutcome<R>> {
|
||||
if (typeof input.dispatch !== "function") throw new Error("Dispatch is required");
|
||||
try {
|
||||
const won = await input.store.start(input.identity, input.fingerprint);
|
||||
if (!won) {
|
||||
const stored = await input.store.receipt(input.identity, input.fingerprint);
|
||||
return stored !== undefined
|
||||
? { kind: "replayed", receipt: stored }
|
||||
: { kind: "replayed", receipt: undefined as unknown as R };
|
||||
}
|
||||
} catch (error) {
|
||||
return { kind: "conflict", expected: error instanceof Error ? error.message : "store_unavailable" };
|
||||
}
|
||||
const receipt = await input.dispatch();
|
||||
try {
|
||||
await input.store.save(input.identity, input.fingerprint, receipt);
|
||||
} catch {
|
||||
/* The downstream commit is real; a journal-write failure must not turn a
|
||||
real receipt into an error. The next retry replays via the stored receipt
|
||||
if the save ever succeeds before a downstream resend. */
|
||||
}
|
||||
return { kind: "claimed", execute: async () => receipt };
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './relationships';
|
||||
export * from './idempotency';
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* @siax/access — universal project/tenant relationship checks for SIAX Cloud.
|
||||
*
|
||||
* This is the reusable extraction of the pattern first proven in DOC0's
|
||||
* `src/clients/project-relationships.ts`. It is deliberately framework-neutral
|
||||
* (no Next.js, Fastify, Prisma or product types) so every SIAX product can
|
||||
* consume the exact same authorization primitive instead of copying it:
|
||||
*
|
||||
* 0pt — document upload + structuring scope
|
||||
* DOC0 — document/version/signature scope
|
||||
* N0D — job submission scope
|
||||
* any app — tenant/project membership
|
||||
*
|
||||
* IMPORTANT: a relationship match is ONE input to authorization, never a
|
||||
* complete decision. The caller must independently bind tenant and actor to a
|
||||
* verified principal (never to request headers), enforce tenant/project
|
||||
* status, capability, data-handling policy and an authoritative tuple
|
||||
* lifecycle. `resolveRelationship` fails closed: only an explicit
|
||||
* `relationships_match` is treated as allowed.
|
||||
*/
|
||||
|
||||
export type RelationshipResult = 'allowed' | 'denied' | 'unavailable';
|
||||
|
||||
/** The outcome of the composite project check. */
|
||||
export type ProjectRelationshipResult = 'relationships_match' | 'denied' | 'unavailable';
|
||||
|
||||
export interface ProjectRelationshipScope {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
const objectId = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
|
||||
const ulid = /^[0-9A-HJKMNP-TV-Z]{26}$/;
|
||||
const maxResponseBytes = 16 * 1024;
|
||||
|
||||
export interface OpenFgaRelationshipsOptions {
|
||||
baseUrl: string;
|
||||
storeId: string;
|
||||
modelId: string;
|
||||
serviceToken: string;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Explicit test-only opt-in for an isolated loopback OpenFGA process. */
|
||||
testOnlyAllowLoopbackHttp?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only OpenFGA relationship reader. Never writes tuples, never caches,
|
||||
* and never retries: an unavailable authorization source must stay visible to
|
||||
* the caller so it can fail closed.
|
||||
*/
|
||||
export class OpenFgaRelationships {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly storeId: string;
|
||||
private readonly modelId: string;
|
||||
private readonly serviceToken: string;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(options: OpenFgaRelationshipsOptions) {
|
||||
const url = new URL(options.baseUrl);
|
||||
const loopbackTest =
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
options.testOnlyAllowLoopbackHttp === true &&
|
||||
url.protocol === 'http:' &&
|
||||
url.hostname === '127.0.0.1';
|
||||
if (
|
||||
(!loopbackTest && url.protocol !== 'https:') ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
typeof options.storeId !== 'string' ||
|
||||
typeof options.modelId !== 'string' ||
|
||||
!ulid.test(options.storeId) ||
|
||||
!ulid.test(options.modelId) ||
|
||||
typeof options.serviceToken !== 'string' ||
|
||||
!/^[\x21-\x7e]{1,8192}$/.test(options.serviceToken) ||
|
||||
(options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 100 || options.timeoutMs > 30_000))
|
||||
) {
|
||||
throw new Error('Invalid trusted OpenFGA configuration');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.storeId = options.storeId;
|
||||
this.modelId = options.modelId;
|
||||
this.serviceToken = options.serviceToken;
|
||||
this.timeoutMs = options.timeoutMs ?? 5_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both checks are necessary: project membership alone may inherit from a
|
||||
* different parent tenant if bad tuples associate a project with two
|
||||
* tenants. Returns `relationships_match` only when both hold.
|
||||
*/
|
||||
async checkProject(scope: ProjectRelationshipScope): Promise<ProjectRelationshipResult> {
|
||||
if (!scope || typeof scope !== 'object' || Array.isArray(scope)) {
|
||||
return 'denied';
|
||||
}
|
||||
const { tenantId, projectId, actorId } = scope;
|
||||
if (![tenantId, projectId, actorId].every((value) => typeof value === 'string' && objectId.test(value))) {
|
||||
return 'denied';
|
||||
}
|
||||
const actor = await this.checkTuple(`user:${actorId}`, 'member', `tenant:${tenantId}`);
|
||||
if (actor !== 'allowed') return actor === 'denied' ? 'denied' : 'unavailable';
|
||||
const parent = await this.checkTuple(`tenant:${tenantId}`, 'tenant', `project:${projectId}`);
|
||||
return parent === 'allowed' ? 'relationships_match' : parent;
|
||||
}
|
||||
|
||||
/** One raw relationship check. Public so products can map their own tuples. */
|
||||
async checkTuple(user: string, relation: string, object: string): Promise<RelationshipResult> {
|
||||
if (
|
||||
![user, relation, object].every(
|
||||
(value) => typeof value === 'string' && value.length > 0 && value.length <= 256,
|
||||
)
|
||||
) {
|
||||
return 'denied';
|
||||
}
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/stores/${this.storeId}/check`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${this.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
authorization_model_id: this.modelId,
|
||||
consistency: 'HIGHER_CONSISTENCY',
|
||||
tuple_key: { user, relation, object },
|
||||
}),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!response.ok || !response.body) return 'unavailable';
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
total += part.value.byteLength;
|
||||
if (total > maxResponseBytes) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
return 'unavailable';
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const result: unknown = JSON.parse(
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)),
|
||||
);
|
||||
if (
|
||||
!result ||
|
||||
typeof result !== 'object' ||
|
||||
Array.isArray(result) ||
|
||||
typeof (result as { allowed?: unknown }).allowed !== 'boolean'
|
||||
) {
|
||||
return 'unavailable';
|
||||
}
|
||||
return (result as { allowed: boolean }).allowed ? 'allowed' : 'denied';
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical environment variable names used across the fleet. Reads are
|
||||
* explicit (no implicit defaults) so a missing value is visible.
|
||||
*/
|
||||
export const OPENFGA_ENV = {
|
||||
baseUrl: 'OPENFGA_API_URL',
|
||||
storeId: 'OPENFGA_STORE_ID',
|
||||
modelId: 'OPENFGA_MODEL_ID',
|
||||
serviceToken: 'OPENFGA_AUTH_TOKEN',
|
||||
} as const;
|
||||
|
||||
export interface ProjectAccessOptions {
|
||||
/** The already-configured relationship reader, or undefined when OpenFGA is not configured. */
|
||||
relationships?: OpenFgaRelationships;
|
||||
/**
|
||||
* Optional extra policy (project status, capability, data-handling). It runs
|
||||
* only after the relationship check matched; a rejection is final.
|
||||
*/
|
||||
additionalPolicy?: (scope: ProjectRelationshipScope) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
/** Fail closed: only an explicit match with no policy objection is allowed. */
|
||||
export async function isProjectAccessAllowed(
|
||||
scope: ProjectRelationshipScope,
|
||||
options: ProjectAccessOptions,
|
||||
): Promise<boolean> {
|
||||
if (!options.relationships) return false;
|
||||
const result = await options.relationships.checkProject(scope);
|
||||
if (result !== 'relationships_match') return false;
|
||||
if (options.additionalPolicy) {
|
||||
try {
|
||||
return (await options.additionalPolicy(scope)) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a relationship reader from a `NodeJS.ProcessEnv`-shaped object.
|
||||
* Returns `undefined` (fail closed) when any value is missing or invalid.
|
||||
*/
|
||||
export function openFgaFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
fetchImpl?: typeof fetch,
|
||||
): OpenFgaRelationships | undefined {
|
||||
const baseUrl = env[OPENFGA_ENV.baseUrl];
|
||||
const storeId = env[OPENFGA_ENV.storeId];
|
||||
const modelId = env[OPENFGA_ENV.modelId];
|
||||
const serviceToken = env[OPENFGA_ENV.serviceToken];
|
||||
if (!baseUrl || !storeId || !modelId || !serviceToken) return undefined;
|
||||
try {
|
||||
return new OpenFgaRelationships({
|
||||
baseUrl,
|
||||
storeId,
|
||||
modelId,
|
||||
serviceToken,
|
||||
...(fetchImpl ? { fetchImpl } : {}),
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user