/** * The records a package's repository holds (docs/design/package-manager.md, * "Records"): one profile, a release per version, a retraction per retracted * version, and the maintainers record; the records of a scope and of an * organization; and the private membership entries their commitments are * to. Their lexicons are in `packages/package-manager/lexicons`. * * Each class reads its record from the data model with `fromValue`, which * checks it against the lexicon and throws `RecordError`, and writes it * back with `toValue`. Fields a lexicon does not define are ignored, so a * record written by a newer client still reads. */ import {HashSet} from 'zena:collections'; import {encodeCbor} from 'atproto/cbor'; import {sha256} from 'zena:crypto'; import {base32Lower} from 'zena:encoding'; import {CODEC_RAW, Cid} from 'atproto/cid'; import { BlobRef, BoolValue, BytesValue, IntValue, ListValue, MapValue, StringValue, Value, field, newMap } from 'atproto/data'; import {isValidCidSyntax, isValidDatetime, isValidDid} from 'atproto/syntax'; import {URL} from 'zena:url'; import {Range, Version, VersionError} from 'zena-lang:semver'; export let PROFILE_TYPE = 'dev.zena-lang.package.profile'; export let RELEASE_TYPE = 'dev.zena-lang.package.release'; export let RETRACTION_TYPE = 'dev.zena-lang.package.retraction'; export let MAINTAINERS_TYPE = 'dev.zena-lang.package.maintainers'; export let SCOPE_MAINTAINERS_TYPE = 'dev.zena-lang.scope.maintainers'; export let POLICY_TYPE = 'dev.zena-lang.scope.policy'; export let SCOPE_PROFILE_TYPE = 'dev.zena-lang.scope.profile'; export let SCOPE_ORGANIZATION_TYPE = 'dev.zena-lang.scope.organization'; export let MEMBERS_TYPE = 'dev.zena-lang.org.members'; export let TEAM_TYPE = 'dev.zena-lang.org.team'; export let ATTESTATION_TYPE = 'dev.zena-lang.package.attestation'; /** The record key of a package's profile. */ export let PROFILE_KEY = 'self'; /** Artifact kinds. A release may also list kinds a client does not know. */ export let SOURCE = 'source'; export let COMPONENT = 'component'; export let CORE_MODULE = 'core-module'; /** A record that does not follow its lexicon. */ export class RecordError extends Error { new(message: String) : super(message); } /** * Whether `name` can name a package: in imports, in lockfiles, and * as the first label of its handle. It is one DNS label: lowercase ASCII * letters, digits and `-`, starting with a letter, not ending with `-`, * without `--` as its third and fourth characters, which internationalized * domain names reserve (`xn--`), and at most 63 bytes. `zena` names the * standard library, so no package has it. */ export function isValidPackageName(name: String): boolean { return name != 'zena' && isValidScopeName(name); } /** * Whether `name` can be a local name, what a package's imports call a * dependency: a package name, or `:` for a package in a * scope (docs/design/import-names.md). `zena` is the standard library's, * as a name and as a scope. */ export function isValidLocalName(name: String): boolean { let parts = name.split(':'); if (parts.length == 1) { return isValidPackageName(name); } return parts.length == 2 && parts[0] != 'zena' && isValidScopeName(parts[0]) && isValidScopeName(parts[1]); } /** * Whether `text` is an SPDX license expression * (https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/): license * identifiers, each perhaps with `+` or `WITH` an exception, joined by `AND` * and `OR` and grouped by parentheses, such as `MIT` or * `(Apache-2.0 OR MIT) AND BSD-3-Clause`. `LicenseRef-` and `DocumentRef-` * identifiers name licenses SPDX does not list. Only the form is checked: * an identifier SPDX does not list, such as a misspelt one, still passes. */ export function isValidLicenseExpression(text: String): boolean { let tokens = new GrowableArray(); var start = -1; for (var i = 0; i < text.length; i += 1) { let b = text.getByteAt(i); if (b == 32 || b == 40 || b == 41) { if (start >= 0) { tokens.push(text.sliceBytes(start, i)); start = -1; } if (b != 32) { tokens.push(text.sliceBytes(i, i + 1)); } } else if (start < 0) { start = i; } } if (start >= 0) { tokens.push(text.sliceBytes(start, text.length)); } let parser = new LicenseParser(tokens); return parser.expression() && parser.done(); } /** A recursive-descent reader of an SPDX expression's tokens. */ final class LicenseParser { #tokens: Array; var #at = 0; new(tokens: Array) : #tokens = tokens; done(): boolean { return this.#at == this.#tokens.length; } #peek(): String { return if (this.#at < this.#tokens.length) this.#tokens[this.#at] else ''; } /** expression := term ((AND | OR) term)* */ expression(): boolean { if (!this.#term()) { return false; } while (this.#peek() == 'AND' || this.#peek() == 'OR') { this.#at += 1; if (!this.#term()) { return false; } } return true; } /** term := '(' expression ')' | license (WITH exception)? */ #term(): boolean { if (this.#peek() == '(') { this.#at += 1; if (!this.expression() || this.#peek() != ')') { return false; } this.#at += 1; return true; } if (!isLicenseId(this.#peek(), true)) { return false; } this.#at += 1; if (this.#peek() == 'WITH') { this.#at += 1; if (!isLicenseId(this.#peek(), false)) { return false; } this.#at += 1; } return true; } } /** * Whether `token` is a license or exception identifier: letters, digits, * `.` and `-`, perhaps ending in `+` for a license, or a `DocumentRef-…:` * before a `LicenseRef-`. The operators are not identifiers. */ function isLicenseId(token: String, license: boolean): boolean { if (token == '' || token == 'AND' || token == 'OR' || token == 'WITH' || token == '(' || token == ')') { return false; } var body = token; if (license && body.endsWith('+')) { body = body.sliceBytes(0, body.length - 1); } for (var i = 0; i < body.length; i += 1) { let b = body.getByteAt(i); let ok = (b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122) || b == 45 || b == 46 || (b == 58 && body.startsWith('DocumentRef-')); if (!ok) { return false; } } return body.length > 0; } /** * Whether `name` can name a scope: the first label of a scope's * handle on a package host. The same DNS label as a package name, but * `zena` is allowed, since the scope of first-party packages is not the * standard library. A host reserves `zena`, with others, for its operator * to create. */ export function isValidScopeName(name: String): boolean { if (name.length == 0 || name.length > 63) { return false; } for (var i = 0; i < name.length; i += 1) { let b = name.getByteAt(i); let letter = b >= 97 && b <= 122; if (!letter && (i == 0 || !((b >= 48 && b <= 57) || b == 45))) { return false; } } if (name.getByteAt(name.length - 1) == 45) { return false; } return !(name.length >= 4 && name.getByteAt(2) == 45 && name.getByteAt(3) == 45); } /** A package's profile, at record key `self`. */ export final class Profile { /** The local name the package suggests for itself. */ name: String; description: String | null; /** An SPDX license expression. */ license: String | null; homepage: String | null; /** Where the package's source is developed. */ source: String | null; new(name: String, description: String | null = null, license: String | null = null, homepage: String | null = null, source: String | null = null) : name = name, description = description, license = license, homepage = homepage, source = source; /** * The profile `value` holds. Its `homepage` and `source` are links, so * each must be an `http:` or `https:` URL: one that is not reads as * none, since a page must never link it, and with `writing`, as the * host checks a profile it is given, is refused. */ static fromValue(value: Value, writing: boolean = false): Profile { let map = recordMap(value, PROFILE_TYPE, 'profile'); let name = requiredString(map, 'name', 'profile'); if (!isValidPackageName(name)) { throw new RecordError(`profile: '${name}' is not a valid package name`); } return new Profile(name, optionalString(map, 'description', 'profile'), optionalString(map, 'license', 'profile'), webLink(map, 'homepage', writing), webLink(map, 'source', writing)); } toValue(): MapValue { let map = typedMap(PROFILE_TYPE); map.entries['name'] = new StringValue(this.name); putString(map, 'description', this.description); putString(map, 'license', this.license); putString(map, 'homepage', this.homepage); putString(map, 'source', this.source); return map; } } /** * One of a release's artifacts: the blob that holds it, or for a large * artifact the parts it was uploaded in, which concatenate to it. */ export final class Artifact { /** `source`, `component`, `core-module`, or a kind this client does not know. */ kind: String; /** The blob holding the whole artifact, or null when it is in parts. */ blob: BlobRef | null; /** The parts, in order, or null when the artifact is one blob. */ parts: FixedArray | null; /** The raw CID of the whole artifact. */ cid: Cid; /** The whole artifact's size in bytes. */ size: i64; /** The WIT world a component targets. */ world: String | null; /** A component's WIT text. */ wit: BlobRef | null; new(kind: String, blob: BlobRef | null, parts: FixedArray | null, cid: Cid, size: i64, world: String | null, wit: BlobRef | null) : kind = kind, blob = blob, parts = parts, cid = cid, size = size, world = world, wit = wit; /** An artifact held in one blob. */ static whole(kind: String, blob: BlobRef, world: String | null = null, wit: BlobRef | null = null): Artifact { return new Artifact(kind, blob, null, blob.cid, blob.size, world, wit); } /** A large artifact held in `parts`, whose concatenation has `cid` and `size`. */ static inParts(kind: String, parts: FixedArray, cid: Cid, size: i64, world: String | null = null, wit: BlobRef | null = null): Artifact { return new Artifact(kind, null, parts, cid, size, world, wit); } static fromValue(value: Value): Artifact { if (!(value is MapValue)) { throw new RecordError('release: an artifact is not an object'); } let map = value; let kind = requiredString(map, 'kind', 'release artifact'); if (kind.length == 0) { throw new RecordError('release: an artifact has an empty kind'); } let where = `release: '${kind}' artifact`; let world = optionalString(map, 'world', where); let witValue = field(map, 'wit'); let wit = if (witValue == null) null else readBlob(witValue, where); if (kind == COMPONENT && (world == null || wit == null)) { throw new RecordError(`${where} has no world or no WIT`); } let blobValue = field(map, 'blob'); let partsValue = field(map, 'parts'); if (blobValue != null) { if (partsValue != null || field(map, 'cid') != null || field(map, 'size') != null) { throw new RecordError(`${where} has a blob and also parts, a CID or a size`); } return Artifact.whole(kind, readBlob(blobValue, where), world, wit); } if (!(partsValue is ListValue)) { throw new RecordError(`${where} has no blob and no parts`); } let items = partsValue.items; if (items.length == 0) { throw new RecordError(`${where} has an empty list of parts`); } let first = readBlob(items[0], where); let parts = new FixedArray(items.length, first); var total: i64 = 0; for (var i = 0; i < items.length; i += 1) { parts[i] = readBlob(items[i], where); total += parts[i].size; } let cidText = requiredString(map, 'cid', where); if (!isValidCidSyntax(cidText)) { throw new RecordError(`${where}: '${cidText}' is not a CID`); } let cid = Cid.parse(cidText); if (cid.codec != CODEC_RAW) { throw new RecordError(`${where}: ${cidText} is not a raw CID`); } let size = field(map, 'size'); if (!(size is IntValue) || size.value != total) { throw new RecordError(`${where}: size is not the sum of its parts' sizes, ${total}`); } return Artifact.inParts(kind, parts, cid, total, world, wit); } /** The blobs that hold it: its blob or its parts, and its WIT. */ blobs(): GrowableArray { let all = new GrowableArray(); let blob = this.blob; if (blob != null) { all.push(blob); } let parts = this.parts; if (parts != null) { for (let part in parts) { all.push(part); } } let wit = this.wit; if (wit != null) { all.push(wit); } return all; } toValue(): MapValue { let map = newMap(); map.entries['kind'] = new StringValue(this.kind); putString(map, 'world', this.world); let blob = this.blob; if (blob != null) { map.entries['blob'] = blob.toValue(); } else { let parts = this.parts as FixedArray; let items = new FixedArray(parts.length, new IntValue(0 as i64)); for (var i = 0; i < parts.length; i += 1) { items[i] = parts[i].toValue(); } map.entries['parts'] = new ListValue(items); map.entries['size'] = new IntValue(this.size); map.entries['cid'] = new StringValue(this.cid.toString()); } let wit = this.wit; if (wit != null) { map.entries['wit'] = wit.toValue(); } return map; } } /** A package a release depends on. */ export final class Dependency { did: String; /** The versions the release works with, in npm's syntax: `^2.1.0`. */ range: Range; /** The local name the release's own imports use for the package. */ name: String; new(did: String, range: Range, name: String) : did = did, range = range, name = name; static fromValue(value: Value): Dependency { if (!(value is MapValue)) { throw new RecordError('release: a dependency is not an object'); } let map = value; let did = requiredString(map, 'did', 'release dependency'); if (!isValidDid(did)) { throw new RecordError(`release: dependency '${did}' is not a DID`); } let name = requiredString(map, 'name', 'release dependency'); if (!isValidLocalName(name)) { throw new RecordError(`release: dependency name '${name}' is not a valid local name`); } let range = readRange(requiredString(map, 'version', 'release dependency'), `release dependency '${name}'`); return new Dependency(did, range, name); } toValue(): MapValue { let map = newMap(); map.entries['did'] = new StringValue(this.did); map.entries['version'] = new StringValue(this.range.text); map.entries['name'] = new StringValue(this.name); return map; } } /** A release, at record key equal to its version. */ export final class Release { version: Version; /** When the release was published, an atproto datetime. */ createdAt: String; artifacts: FixedArray; dependencies: FixedArray; /** * The language version the release was published with, the record's * `zena`: the version of the compiler that published it, such as * `0.3.1` (docs/design/language-versions.md). A fact about how it was * published, which readers use for hints and known breaks, and never as * a claim about which versions it works with. It may be above any * compiler a reader knows of, since its publisher may have built a newer * `zena`. */ publishedWith: Version; new(version: Version, createdAt: String, artifacts: FixedArray, dependencies: FixedArray, publishedWith: Version) : version = version, createdAt = createdAt, artifacts = artifacts, dependencies = dependencies, publishedWith = publishedWith; /** * Reads a release record. Given the record key `key`, also checks that * the version repeats it. */ static fromValue(value: Value, key: String | null = null): Release { let map = recordMap(value, RELEASE_TYPE, 'release'); let versionText = requiredString(map, 'version', 'release'); let version = readVersion(versionText, 'release'); if (key != null && key != versionText) { throw new RecordError(`release: version ${versionText} is not its record key, '${key}'`); } let createdAt = requiredString(map, 'createdAt', 'release'); if (!isValidDatetime(createdAt)) { throw new RecordError(`release: createdAt '${createdAt}' is not a datetime`); } let artifactList = field(map, 'artifacts'); if (!(artifactList is ListValue)) { throw new RecordError('release: artifacts is not a list'); } let artifactItems = artifactList.items; if (artifactItems.length == 0) { throw new RecordError('release: artifacts is empty'); } let artifacts = new FixedArray(artifactItems.length, Artifact.fromValue(artifactItems[0])); for (var i = 1; i < artifactItems.length; i += 1) { artifacts[i] = Artifact.fromValue(artifactItems[i]); } var dependencies = new FixedArray(0, new Dependency('', Range.parse('*'), '')); let dependencyList = field(map, 'dependencies'); if (dependencyList != null) { if (!(dependencyList is ListValue)) { throw new RecordError('release: dependencies is not a list'); } let items = dependencyList.items; if (items.length > 0) { dependencies = new FixedArray(items.length, Dependency.fromValue(items[0])); for (var i = 1; i < items.length; i += 1) { dependencies[i] = Dependency.fromValue(items[i]); } } checkDependencies(dependencies); } let languageText = requiredString(map, 'zena', 'release'); let publishedWith = try { Version.parse(languageText) } catch (e) { throw new RecordError(`release: zena: ${e.message}`); }; return new Release(version, createdAt, artifacts, dependencies, publishedWith); } /** The first artifact of kind `kind`, or null when the release has none. */ artifact(kind: String): Artifact | null { for (let artifact in this.artifacts) { if (artifact.kind == kind) { return artifact; } } return null; } /** The bytes of the blobs that hold its artifacts, as their references give them. */ blobBytes(): i64 { var total: i64 = 0; for (let artifact in this.artifacts) { for (let blob in artifact.blobs()) { total += blob.size; } } return total; } toValue(): MapValue { let map = typedMap(RELEASE_TYPE); map.entries['version'] = new StringValue(this.version.toString()); map.entries['createdAt'] = new StringValue(this.createdAt); let artifacts = new FixedArray(this.artifacts.length, new IntValue(0 as i64)); for (var i = 0; i < artifacts.length; i += 1) { artifacts[i] = this.artifacts[i].toValue(); } map.entries['artifacts'] = new ListValue(artifacts); if (this.dependencies.length > 0) { let dependencies = new FixedArray(this.dependencies.length, new IntValue(0 as i64)); for (var i = 0; i < dependencies.length; i += 1) { dependencies[i] = this.dependencies[i].toValue(); } map.entries['dependencies'] = new ListValue(dependencies); } map.entries['zena'] = new StringValue(this.publishedWith.toString()); return map; } } /** A retracted version, at record key equal to the version. */ export final class Retraction { version: Version; /** Why the version was retracted. */ reason: String | null; new(version: Version, reason: String | null = null) : version = version, reason = reason; /** * Reads a retraction record. Given the record key `key`, also checks that the * version repeats it. */ static fromValue(value: Value, key: String | null = null): Retraction { let map = recordMap(value, RETRACTION_TYPE, 'retraction'); let versionText = requiredString(map, 'version', 'retraction'); let version = readVersion(versionText, 'retraction'); if (key != null && key != versionText) { throw new RecordError(`retraction: version ${versionText} is not its record key, '${key}'`); } return new Retraction(version, optionalString(map, 'reason', 'retraction')); } toValue(): MapValue { let map = typedMap(RETRACTION_TYPE); map.entries['version'] = new StringValue(this.version.toString()); putString(map, 'reason', this.reason); return map; } } /** * A release's dependencies give each local name once, and each package's * compatible line once (`Version.compatibleLine`: its major version, or * before 1.0 the first number that is not zero), the line of the lowest * version in the range. */ function checkDependencies(dependencies: FixedArray): void { let names = new HashSet(); let packages = new HashSet(); for (let dependency in dependencies) { if (names.has(dependency.name)) { throw new RecordError(`release: two dependencies are named '${dependency.name}'`); } names.add(dependency.name); let minimum = dependency.range.minimum(); if (minimum == null) { throw new RecordError(`release: no version is in dependency '${dependency.name}''s range, '${dependency.range.text}'`); } let key = `${dependency.did}@${minimum.compatibleLine()}`; if (packages.has(key)) { throw new RecordError(`release: ${key} is a dependency twice`); } packages.add(key); } } /** * The roles a package's or a scope's maintainers record gives: `publisher` * or `owner`. A package's publishers publish its releases; a scope's * publish new packages into it, starting as owners of each. */ export let PUBLISHER = 'publisher'; export let OWNER = 'owner'; /** The role of an organization's members, and of a team's: `member`, or a team's `maintainer`. */ export let MEMBER = 'member'; export let MAINTAINER = 'maintainer'; /** * One maintainer of a package or a scope: exactly one of a DID, a * commitment to a private `MemberEntry`, or an organization's team. */ export final class Maintainer { did: String | null; commitment: Cid | null; org: String | null; team: String | null; /** `publisher` or `owner`. */ role: String; automation: boolean; new(did: String | null, commitment: Cid | null, org: String | null, team: String | null, role: String, automation: boolean = false) : did = did, commitment = commitment, org = org, team = team, role = role, automation = automation; static ofDid(did: String, role: String): Maintainer { return new Maintainer(did, null, null, null, role); } } /** A package's maintainers record, at record key `self`. */ export final class Maintainers { maintainers: FixedArray; /** How many maintainers must attest a release. */ threshold: i64; /** How many owners must attest a change to this record. */ ownerThreshold: i64; /** How many of a release's attestations must come from maintainers that are not automation. */ var humans: i64 = 0 as i64; new(maintainers: FixedArray, threshold: i64 = 1 as i64, ownerThreshold: i64 = 1 as i64) : maintainers = maintainers, threshold = threshold, ownerThreshold = ownerThreshold; static fromValue(value: Value): Maintainers { let what = 'maintainers record'; let map = recordMap(value, MAINTAINERS_TYPE, what); let maintainers = maintainerList(map, what); let record = new Maintainers(maintainers, positive(map, 'threshold', what), positive(map, 'ownerThreshold', what)); let humans = field(map, 'humans'); if (humans != null) { if (!(humans is IntValue) || humans.value < (0 as i64)) { throw new RecordError(`${what}: 'humans' is not a count`); } record.humans = humans.value; } return record; } toValue(): MapValue { let map = typedMap(MAINTAINERS_TYPE); map.entries['maintainers'] = maintainerValues(this.maintainers); map.entries['threshold'] = new IntValue(this.threshold); map.entries['ownerThreshold'] = new IntValue(this.ownerThreshold); if (this.humans > (0 as i64)) { map.entries['humans'] = new IntValue(this.humans); } return map; } } /** * A scope's maintainers record, at record key `self`: its publishers, who * create packages in it, and its owners, who also change the scope and any * of its packages' maintainers, and how many owners must attest a change. */ export final class ScopeMaintainers { maintainers: FixedArray; ownerThreshold: i64; new(maintainers: FixedArray, ownerThreshold: i64 = 1 as i64) : maintainers = maintainers, ownerThreshold = ownerThreshold; static fromValue(value: Value): ScopeMaintainers { let what = 'scope maintainers record'; let map = recordMap(value, SCOPE_MAINTAINERS_TYPE, what); return new ScopeMaintainers(maintainerList(map, what), positive(map, 'ownerThreshold', what)); } toValue(): MapValue { let map = typedMap(SCOPE_MAINTAINERS_TYPE); map.entries['maintainers'] = maintainerValues(this.maintainers); map.entries['ownerThreshold'] = new IntValue(this.ownerThreshold); return map; } } /** The `maintainers` of a package's or a scope's maintainers record, each a `publisher` or an `owner`. */ function maintainerList(map: MapValue, what: String): FixedArray { let list = field(map, 'maintainers'); if (!(list is ListValue) || list.items.length == 0) { throw new RecordError(`${what}: 'maintainers' is not a list of at least one`); } let maintainers = new FixedArray(list.items.length, Maintainer.ofDid('', '')); for (var i = 0; i < list.items.length; i += 1) { let item = list.items[i]; if (!(item is MapValue)) { throw new RecordError(`${what}: maintainer ${i} is not an object`); } let entry = item; let did = optionalString(entry, 'did', what); let commitmentText = optionalString(entry, 'commitment', what); let org = optionalString(entry, 'org', what); let team = optionalString(entry, 'team', what); let role = requiredString(entry, 'role', what); let forms = (if (did != null) 1 else 0) + (if (commitmentText != null) 1 else 0) + (if (org != null) 1 else 0); if (forms != 1 || (org == null) != (team == null)) { throw new RecordError(`${what}: maintainer ${i} is not exactly one of a DID, a commitment, or an org with a team`); } if (did != null && !isValidDid(did)) { throw new RecordError(`${what}: '${did}' is not a DID`); } if (role != PUBLISHER && role != OWNER) { throw new RecordError(`${what}: '${role}' is not a role`); } let commitment: Cid | null = if (commitmentText != null) { readCid(commitmentText, what) } else { null }; let automation = field(entry, 'automation'); maintainers[i] = new Maintainer(did, commitment, org, team, role, automation is BoolValue && automation.value); } return maintainers; } /** `maintainers` as a record's `maintainers` list. */ function maintainerValues(maintainers: FixedArray): ListValue { let items = new FixedArray(maintainers.length, new StringValue('')); for (var i = 0; i < maintainers.length; i += 1) { let maintainer = maintainers[i]; let entry = newMap(); putString(entry, 'did', maintainer.did); let commitment = maintainer.commitment; if (commitment != null) { entry.entries['commitment'] = new StringValue(commitment.toString()); } putString(entry, 'org', maintainer.org); putString(entry, 'team', maintainer.team); entry.entries['role'] = new StringValue(maintainer.role); if (maintainer.automation) { entry.entries['automation'] = new BoolValue(true); } items[i] = entry; } return new ListValue(items); } /** * One member's private entry (`dev.zena-lang.org.defs#entry`). Records list * its commitment, the CID of the entry's DAG-CBOR encoding, so the salt * keeps anyone from finding a commitment by trying DIDs. */ export final class MemberEntry { did: String; /** The role the record that commits to the entry gives. */ role: String; /** 32 random bytes. */ salt: FixedArray; automation: boolean; /** The member's passkeys or security keys, as `did:key`s. */ var approvalKeys: Array = []; new(did: String, role: String, salt: FixedArray, automation: boolean = false) : did = did, role = role, salt = salt, automation = automation; static fromValue(value: Value): MemberEntry { let what = 'membership entry'; if (!(value is MapValue)) { throw new RecordError(`${what}: not an object`); } let map = value; let did = requiredString(map, 'did', what); if (!isValidDid(did)) { throw new RecordError(`${what}: '${did}' is not a DID`); } let salt = field(map, 'salt'); if (!(salt is BytesValue) || salt.value.length != 32) { throw new RecordError(`${what}: the salt is not 32 bytes`); } let automation = field(map, 'automation'); let entry = new MemberEntry(did, requiredString(map, 'role', what), salt.value, automation is BoolValue && automation.value); let keys = field(map, 'approvalKeys'); if (keys != null) { if (!(keys is ListValue)) { throw new RecordError(`${what}: 'approvalKeys' is not a list`); } let list = new GrowableArray(); for (let key in keys.items) { if (!(key is StringValue)) { throw new RecordError(`${what}: an approval key is not a string`); } list.push(key.value); } entry.approvalKeys = list; } return entry; } toValue(): MapValue { let map = newMap(); map.entries['did'] = new StringValue(this.did); map.entries['role'] = new StringValue(this.role); if (this.automation) { map.entries['automation'] = new BoolValue(true); } if (this.approvalKeys.length > 0) { let keys = new FixedArray(this.approvalKeys.length, new StringValue('')); for (var i = 0; i < this.approvalKeys.length; i += 1) { keys[i] = new StringValue(this.approvalKeys[i]); } map.entries['approvalKeys'] = new ListValue(keys); } map.entries['salt'] = new BytesValue(this.salt); return map; } /** The CID records list in place of the entry. */ commitment(): Cid { return Cid.forDagCbor(encodeCbor(this.toValue())); } } /** * An organization's members record, at record key `self`: commitments to * the entries of the people its teams are made of, each in the role * `member`. The owners of the organization's scope approve a change to it. * A scope with this record is an organization. */ export final class Members { members: FixedArray; new(members: FixedArray) : members = members; static fromValue(value: Value): Members { let what = 'members record'; let map = recordMap(value, MEMBERS_TYPE, what); let members = commitments(map, what); if (members.length == 0) { throw new RecordError(`${what}: 'members' is empty`); } return new Members(members); } toValue(): MapValue { let map = typedMap(MEMBERS_TYPE); let items = new FixedArray(this.members.length, new StringValue('')); for (var i = 0; i < this.members.length; i += 1) { items[i] = new StringValue(this.members[i].toString()); } map.entries['members'] = new ListValue(items); return map; } } /** * A team of an organization, at the record key equal to the team's name: * commitments to its members' entries, whose roles are `member` or * `maintainer`, and how many maintainers must attest a change, which the * owners of the organization's scope can approve instead. */ export final class Team { members: FixedArray; threshold: i64; new(members: FixedArray, threshold: i64 = 1 as i64) : members = members, threshold = threshold; static fromValue(value: Value): Team { let what = 'team record'; let map = recordMap(value, TEAM_TYPE, what); return new Team(commitments(map, what), positive(map, 'threshold', what)); } toValue(): MapValue { let map = typedMap(TEAM_TYPE); let items = new FixedArray(this.members.length, new StringValue('')); for (var i = 0; i < this.members.length; i += 1) { items[i] = new StringValue(this.members[i].toString()); } map.entries['members'] = new ListValue(items); map.entries['threshold'] = new IntValue(this.threshold); return map; } } /** A team, by its organization's DID and its name, and the role a package gives it. */ export final class TeamRole { org: String; team: String; role: String; new(this.org, this.team, this.role); } /** * A scope's policy for its packages, at record key `self`. What it asks of * releases, the host applies at once, to every package in the scope: a * release needs the larger of its maintainers record's `threshold` and * `minimumThreshold`, and of its `humans` and `minimumHumans`. What a new * package starts with, `zena` uses when it creates one: the default teams, * in their roles, beside its creator, and the default thresholds. */ export final class Policy { var minimumThreshold: i64 = 1 as i64; var minimumHumans: i64 = 0 as i64; var defaultTeams: Array = []; var defaultThreshold: i64 = 1 as i64; var defaultOwnerThreshold: i64 = 1 as i64; var defaultHumans: i64 = 0 as i64; static fromValue(value: Value): Policy { let what = 'policy record'; let map = recordMap(value, POLICY_TYPE, what); let policy = new Policy(); policy.minimumThreshold = countOr(map, 'minimumThreshold', 1, what); policy.minimumHumans = countOr(map, 'minimumHumans', 0, what); policy.defaultThreshold = countOr(map, 'defaultThreshold', 1, what); policy.defaultOwnerThreshold = countOr(map, 'defaultOwnerThreshold', 1, what); policy.defaultHumans = countOr(map, 'defaultHumans', 0, what); let teams = field(map, 'defaultTeams'); if (teams != null) { if (!(teams is ListValue)) { throw new RecordError(`${what}: 'defaultTeams' is not a list`); } let list = new GrowableArray(); for (let item in teams.items) { if (!(item is MapValue)) { throw new RecordError(`${what}: a default team is not an object`); } let org = requiredString(item, 'org', what); let team = requiredString(item, 'team', what); let role = requiredString(item, 'role', what); if (!isValidDid(org) || !isValidPackageName(team) || (role != PUBLISHER && role != OWNER)) { throw new RecordError(`${what}: the default team '${org} ${team}' as '${role}' is not a team as publisher or owner`); } list.push(new TeamRole(org, team, role)); } policy.defaultTeams = list; } return policy; } toValue(): MapValue { let map = typedMap(POLICY_TYPE); putCount(map, 'minimumThreshold', this.minimumThreshold, 1); putCount(map, 'minimumHumans', this.minimumHumans, 0); if (this.defaultTeams.length > 0) { let items = new FixedArray(this.defaultTeams.length, new StringValue('')); for (var i = 0; i < this.defaultTeams.length; i += 1) { let entry = newMap(); entry.entries['org'] = new StringValue(this.defaultTeams[i].org); entry.entries['team'] = new StringValue(this.defaultTeams[i].team); entry.entries['role'] = new StringValue(this.defaultTeams[i].role); items[i] = entry; } map.entries['defaultTeams'] = new ListValue(items); } putCount(map, 'defaultThreshold', this.defaultThreshold, 1); putCount(map, 'defaultOwnerThreshold', this.defaultOwnerThreshold, 1); putCount(map, 'defaultHumans', this.defaultHumans, 0); return map; } } /** * How a scope presents itself, at record key `self`: a display name, a * description and a website, each optional. It decides no one's role, so * the scope's owners write it at once. Lengths are in * UTF-8 bytes, as atproto's profiles limit them; the website is an * `http:` or `https:` URL. */ export final class ScopeProfile { var displayName: String | null = null; var description: String | null = null; var website: String | null = null; static fromValue(value: Value): ScopeProfile { let what = 'scope profile'; let map = recordMap(value, SCOPE_PROFILE_TYPE, what); let profile = new ScopeProfile(); profile.displayName = boundedString(map, 'displayName', 640, what); profile.description = boundedString(map, 'description', 2560, what); let website = boundedString(map, 'website', 512, what); if (website != null) { let parsed = URL.parse(website); if (parsed == null || (parsed.protocol != 'https:' && parsed.protocol != 'http:')) { throw new RecordError(`${what}: '${website}' is not an http: or https: URL`); } } profile.website = website; return profile; } toValue(): MapValue { let map = typedMap(SCOPE_PROFILE_TYPE); putString(map, 'displayName', this.displayName); putString(map, 'description', this.description); putString(map, 'website', this.website); return map; } } /** * The organization a scope belongs to, at record key `self`, by its DID. * It counts once the owners of both the scope and the organization have * attested it; belonging groups the scope with the organization's and * gives no one a role in it. */ export final class ScopeOrganization { organization: String; new(this.organization); static fromValue(value: Value): ScopeOrganization { let what = 'scope organization record'; let map = recordMap(value, SCOPE_ORGANIZATION_TYPE, what); let organization = requiredString(map, 'organization', what); if (!isValidDid(organization)) { throw new RecordError(`${what}: '${organization}' is not a DID`); } return new ScopeOrganization(organization); } toValue(): MapValue { let map = typedMap(SCOPE_ORGANIZATION_TYPE); map.entries['organization'] = new StringValue(this.organization); return map; } } /** The string at `key`, at most `most` bytes, or null when there is none. */ function boundedString(map: MapValue, key: String, most: i32, what: String): String | null { let value = optionalString(map, key, what); if (value != null && value.length > most) { throw new RecordError(`${what}: '${key}' is longer than ${most} bytes`); } return value; } /** The count at `key`, at least `least`, or `least` when there is none. */ function countOr(map: MapValue, key: String, least: i32, what: String): i64 { let value = field(map, key); if (value == null) { return least as i64; } if (!(value is IntValue) || value.value < (least as i64)) { throw new RecordError(`${what}: '${key}' is not a whole number of at least ${least}`); } return value.value; } /** Writes `n` at `key`, unless it is `fallback`, which leaving it out means. */ function putCount(map: MapValue, key: String, n: i64, fallback: i32): void { if (n != (fallback as i64)) { map.entries[key] = new IntValue(n); } } /** The commitments a members or team record lists under `members`. */ function commitments(map: MapValue, what: String): FixedArray { let list = field(map, 'members'); if (!(list is ListValue)) { throw new RecordError(`${what}: 'members' is not a list`); } let out = new FixedArray(list.items.length, Cid.forDagCbor(new FixedArray(0, 0 as u8))); for (var i = 0; i < list.items.length; i += 1) { let item = list.items[i]; if (!(item is StringValue)) { throw new RecordError(`${what}: member ${i} is not a CID`); } out[i] = readCid(item.value, what); } return out; } /** * A maintainer's approval of a record in a package's or an organization's * repository, written to the maintainer's own repository at * `attestationKey(subject)`. */ export final class Attestation { /** The AT-URI of the record approved. */ uri: String; /** Its CID: the version of the record approved. */ cid: Cid; createdAt: String; new(uri: String, cid: Cid, createdAt: String) : uri = uri, cid = cid, createdAt = createdAt; /** Its record key in the maintainer's repository. */ recordKey(): String { return attestationKey(this.uri, this.cid); } toValue(): MapValue { let map = typedMap(ATTESTATION_TYPE); let subject = newMap(); subject.entries['uri'] = new StringValue(this.uri); subject.entries['cid'] = new StringValue(this.cid.toString()); map.entries['subject'] = subject; map.entries['createdAt'] = new StringValue(this.createdAt); return map; } static fromValue(value: Value): Attestation { let what = 'attestation'; let map = recordMap(value, ATTESTATION_TYPE, what); let subject = field(map, 'subject'); if (!(subject is MapValue)) { throw new RecordError(`${what}: 'subject' is not an object`); } return new Attestation(requiredString(subject, 'uri', what), readCid(requiredString(subject, 'cid', what), what), requiredString(map, 'createdAt', what)); } } /** * The record key of an attestation of the record at `uri` whose CID is * `cid`: the SHA-256 hash of the AT-URI, a space and the CID, in lowercase * base32 without padding. Successive versions of one record share a URI, * and the CID keeps their attestations apart. */ export function attestationKey(uri: String, cid: Cid): String { return base32Lower.encode(sha256(`${uri} ${cid.toString()}`.toBytes()), false); } function readCid(text: String, what: String): Cid { try { return Cid.parse(text); } catch (e) { throw new RecordError(`${what}: '${text}' is not a CID`); } } function positive(map: MapValue, key: String, what: String): i64 { let value = field(map, key); if (!(value is IntValue) || value.value < 1) { throw new RecordError(`${what}: '${key}' is not a positive integer`); } return value.value; } /** `value` as a record map whose `$type` is `type`. */ function recordMap(value: Value, type: String, what: String): MapValue { if (!(value is MapValue)) { throw new RecordError(`${what}: the record is not an object`); } let map = value; let actual = field(map, '$type'); if (!(actual is StringValue) || actual.value != type) { throw new RecordError(`${what}: $type is not '${type}'`); } return map; } function typedMap(type: String): MapValue { let map = newMap(); map.entries['$type'] = new StringValue(type); return map; } function requiredString(map: MapValue, key: String, what: String): String { let value = optionalString(map, key, what); if (value == null) { throw new RecordError(`${what}: '${key}' is missing`); } return value; } function optionalString(map: MapValue, key: String, what: String): String | null { let value = field(map, key); if (value == null) { return null; } if (!(value is StringValue)) { throw new RecordError(`${what}: '${key}' is not a string`); } return value.value; } /** * The `http:` or `https:` URL at `key`, or null when there is none or, * unless `strict`, when it is not one. */ function webLink(map: MapValue, key: String, strict: boolean): String | null { let value = optionalString(map, key, 'profile'); if (value == null) { return null; } let parsed = URL.parse(value); if (parsed == null || (parsed.protocol != 'https:' && parsed.protocol != 'http:')) { if (strict) { throw new RecordError(`profile: '${key}' is not an http: or https: URL: '${value}'`); } return null; } return value; } function putString(map: MapValue, key: String, value: String | null): void { if (value != null) { map.entries[key] = new StringValue(value); } } function readBlob(value: Value, what: String): BlobRef { try { return BlobRef.fromValue(value); } catch (e) { throw new RecordError(`${what}: ${e.message}`); } } /** * Reads a package's version: a semantic version without build metadata, * since a release's version is its record key, and a record key cannot * contain `+`. */ export function parsePackageVersion(text: String): Version { let version = Version.parse(text); if (version.build.length > 0) { throw new VersionError(`'${text}' has build metadata, which a package version cannot have`); } return version; } /** Reads a range in npm's syntax, which must have a version in it. */ export function readRange(text: String, what: String): Range { var range: Range | null = null; try { range = Range.parse(text); } catch (e) { throw new RecordError(`${what}: ${e.message}`); } let read = range; if (read.minimum() == null) { throw new RecordError(`${what}: no version is in '${text}'`); } return read; } function readVersion(text: String, what: String): Version { try { return parsePackageVersion(text); } catch (e) { throw new RecordError(`${what}: ${e.message}`); } }