forked from mtusi2026/mtusi2026lab7
89 lines
2.4 KiB
TypeScript
89 lines
2.4 KiB
TypeScript
import { requireThat } from "./runtime";
|
|
export type Role = "api" | "worker";
|
|
export type ServiceSecrets = {
|
|
database_url: string;
|
|
cache_url: string;
|
|
s3_json: string;
|
|
publisher_url?: string;
|
|
};
|
|
function roleURL(
|
|
value: string,
|
|
protocol: string,
|
|
port: string,
|
|
identity: string,
|
|
) {
|
|
let url: URL;
|
|
try {
|
|
url = new URL(value);
|
|
} catch {
|
|
throw new Error("BAO_ROLE_MISMATCH");
|
|
}
|
|
requireThat(
|
|
url.protocol === protocol &&
|
|
url.hostname === "127.0.0.1" &&
|
|
url.port === port &&
|
|
url.username === identity,
|
|
"BAO_ROLE_MISMATCH",
|
|
);
|
|
}
|
|
export function parseKV(
|
|
response: { status: number; data: any },
|
|
role: Role,
|
|
): { secrets: ServiceSecrets; version: number } {
|
|
requireThat(response.status === 200, "BAO_KV_HTTP_NOT_SUCCESS");
|
|
const envelope = response.data?.data,
|
|
payload = envelope?.data,
|
|
version = envelope?.metadata?.version;
|
|
requireThat(
|
|
payload && typeof payload === "object" && !Array.isArray(payload),
|
|
"BAO_KV_V2_ENVELOPE_INVALID",
|
|
);
|
|
const keys = [
|
|
"database_url",
|
|
"cache_url",
|
|
"s3_json",
|
|
...(role === "worker" ? ["publisher_url"] : []),
|
|
];
|
|
for (const key of keys)
|
|
requireThat(
|
|
typeof payload[key] === "string" &&
|
|
payload[key].length > 0 &&
|
|
payload[key].length <= 8192,
|
|
"BAO_MISSING_ROLE_SECRETS",
|
|
);
|
|
requireThat(
|
|
Number.isSafeInteger(version) && version >= 1,
|
|
"BAO_KV_VERSION_INVALID",
|
|
);
|
|
roleURL(payload.database_url, "postgresql:", "15432", role);
|
|
roleURL(payload.cache_url, "redis:", "16379", role);
|
|
if (role === "worker")
|
|
roleURL(payload.publisher_url, "redis:", "16379", "publisher");
|
|
else requireThat(payload.publisher_url === undefined, "BAO_ROLE_MISMATCH");
|
|
let s3: any;
|
|
try {
|
|
s3 = JSON.parse(payload.s3_json);
|
|
} catch {
|
|
throw new Error("BAO_S3_JSON_INVALID");
|
|
}
|
|
requireThat(
|
|
s3.Endpoint === "127.0.0.1:19000" &&
|
|
s3.Access === "vp7" + role &&
|
|
s3.Bucket === "messenger-attachments",
|
|
"BAO_ROLE_MISMATCH",
|
|
);
|
|
requireThat(
|
|
typeof s3.Secret === "string" &&
|
|
s3.Secret.length > 0 &&
|
|
s3.Secret.length <= 4096,
|
|
"BAO_MISSING_ROLE_SECRETS",
|
|
);
|
|
const secrets: ServiceSecrets = {
|
|
database_url: payload.database_url,
|
|
cache_url: payload.cache_url,
|
|
s3_json: payload.s3_json,
|
|
};
|
|
if (role === "worker") secrets.publisher_url = payload.publisher_url;
|
|
return { secrets, version };
|
|
}
|