service-compris — standing up a host and installing onto it
The walkthrough for the repository: take a blank Firebase project, deploy this repo onto it, claim it, install a library, and give an agent its own identity. Nobody hands over a secret, and nobody deploys a function per feature.
As of 0.2.0 this runs in production: tosijs-virta's host and loewald.com. Every
flow below is verified end to end against a real deployed host on each change
(scripts/verify-*.js, six ceremonies, 94 assertions). Read
What is NOT ready before you design around something.
(The file keeps the name BETA.md because other projects link to it.)
1. Stand up a host
git clone https://github.com/tonioloewald/tosijs-platform
cd tosijs-platform && bun install
# Dry run first — it changes nothing and reports exactly what it would do.
bun scripts/provision-sandbox.js --alias mine --project <id> --profile platform
bun scripts/provision-sandbox.js --alias mine --profile platform --apply
--profile platform gives you the platform routes and nothing else — no
loewald.com functions, no LLM secrets, no seeded blog content. Your host
starts empty: roles arrive through the claim ceremony, collections through an
install. Drop the flag only if you want this repo's own site too.
This links billing, enables the APIs, creates Firestore and a web app, generates the client config, deploys, grants the public invoker bindings, and seeds. It is idempotent — re-running is safe.
One step it cannot do: enabling Google sign-in needs an OAuth client that Firebase only provisions through console flows. The script prints the exact URL and stops rather than pretending. Until you click it, nobody can sign in.
(bun run initial-deploy is the older path. It predates the invoker-binding
step below, so prefer the provisioner.)
Two operational things that will bite you otherwise, both learned the hard way:
Deploying afterwards: bun run deploy (or bun scripts/deploy.js --alias <yours>). It deploys the WHOLE set in the right order: Firestore rules and
indexes, then functions, storage rules and hosting. Then it checks from outside
that every endpoint runs our code, the bucket root can't be listed, and the
site serves. firebase deploy --only … still works, but it deploys only what
you name, and a release that changes rules and code together (0.3.0 did) must
ship both.
Deploy indexes before functions (bun run deploy does). getUserRoles resolves a first-time
sign-in by querying role.contacts, which needs a composite index. Without it
the query throws and every sign-in 500s for anyone not already in a role
document — including, notably, not you, because your own uid is in one.
firebase deploy --only firestore:indexes # first
firebase deploy --only functions # then
Every endpoint is publicly invocable, declared in code (0.4.0+:
invoker: 'public', see functions/src/endpoint-options.ts), so every
deploy re-applies it. There is no IAM step to remember, and one that was lost
(a Cloud Run 401/403 with an HTML body from Google, before our code runs) is
fixed by redeploying that function. The deploying account needs permission to
set IAM policy on Cloud Run services, which a project owner has.
"Publicly invocable" is not "publicly authorized" — the function's own RBAC
still runs. The tell that you are looking at our 401 rather than Google's:
ours carries access-control-allow-origin and x-ratelimit-* headers.
2. Claim it
A fresh host has nobody privileged. There is no first-run secret to leak, because the proof of ownership is being able to write the datastore — which, per DECISIONS D3, already outranks anything this system can enforce.
bun scripts/claim.js --alias mine
# → claim armed for you@example.com … and your browser opens the claim page
Sign in with Google on that page and click Claim. Your account is now the
host's configurator. That is the whole ceremony.
What the command did, with your operator credentials: it asked the host for its
claim nonce, wrote it into system:claim/current as the proof, and bound it
to your email (--for someone@else.com to arm it for another person). Only
that verified account can complete the claim, and only within the hour. The
nonce rotates on success, so the ceremony is not replayable, and it is
re-runnable as break-glass if the configurator loses their account.
By hand, if you would rather see every step (it is the same ceremony):
curl https://us-central1-<project>.cloudfunctions.net/claim
# → { "nonce": "…", "writeTo": { "collection": "system:claim", "document": "current", "field": "proof" } }
Write that nonce into the proof field of system:claim/current — Firebase
console, gcloud, or admin credentials (firestore.rules is deny-all, so no
API path reaches that document). Optionally add a for field with the one
email allowed to claim. Then, with a real Firebase ID token (sign in at
https://<your-project>.web.app, then await fb.auth.currentUser.getIdToken()
in the browser console; in Safari wrap it in copy(...)):
curl -X POST -H "Authorization: Bearer $ID_TOKEN" .../claim
# → { "ok": true, "granted": "configurator" }
Scripting the write yourself? A Firestore REST
PATCHwithoutupdateMaskreplaces the whole document and wipes the nonce you are trying to match. Use?updateMask.fieldPaths=proof(and&updateMask.fieldPaths=for).
3. Write a manifest
A manifest is plain JSON — collections, schemas, access rules. No builders, no closures, no deployment.
{
"manifest": 1,
"name": "virta",
"version": "1.0.0",
"collections": {
"virta:task": {
"schema": {
"type": "object",
"properties": { "title": { "type": "string" }, "state": { "type": "string" } },
"required": ["title"]
},
"unique": ["slug"],
"derive": [{ "op": "slug", "to": "slug", "from": "title", "when": "absent" }],
"access": [
{ "role": "public", "read": "ALL", "list": "ALL" },
{ "role": "author", "write": "ALL" }
]
}
}
}
Rules worth knowing before you write one:
- Collections must be namespaced
yourname:whatever. A bare name belongs to the platform, always.:is the namespace separator — not/, which already separates sub-collections. accessis an ARRAY, not a role-keyed object. Grants are joined as a lattice, so order is meaningless; the array makes that explicit. Holding more roles never grants less.- v1 is declarative only. A
functionskey is a hard failure, not an ignored field — silently dropping the executable half of your manifest and reporting success is the worst available outcome. Stored ajs is install v2. - Schemas are checked for keywords the validator silently ignores. If your schema uses one, the install is refused rather than accepted-and-unenforced.
- Which rows a role sees is a
visiblerule on itsreadorlist:{"field": "tags", "op": "includes", "value": "public"}, combined withall/any. Put"principal": "uid"in place ofvalueto compare a row to the caller:{"field": "owner", "op": "eq", "principal": "uid"}keeps each account to its own rows, and{"field": "readers", "op": "includes", "principal": "uid"}limits a row to the people it names. A signed-in caller without a role document holds no roles but still has a uid, so apublicgrant with that rule is enough for per-account data; anonymous matches nothing. A rule with a key the platform doesn't know, or a comparison with nothing to compare to, is refused at install. - Who may write which rows is a restricted
writegrant:{"visible": <rule>, "accept": <schema>}. A write passes when the rule holds on the stored row (if any) and on the row being stored, and the schema accepts the content, so{"visible": {"field": "owner", "op": "eq", "principal": "uid"}, "accept": …}onpubliclets each account write its own rows and nobody else's. Someone else's row answers 404, like a missing one. Don't use apublicwrite: "ALL"withderive: principalfor this: the derive fills only a missing field, so anyone could name someone else as the owner. Ids are first come, first served, so give rows fresh, unguessable ids (not the uid) and find an account's rows by listing; anduniquechecks every row, including ones the caller cannot see.
4. Install it
bun scripts/install-manifest.js virta.json --production
# → proposed virta@1.0.0. Confirmation code: MKQD-XMN5
# …your browser opens the approval page…
# → virta@1.0.0 → installed
Installing needs configurator, which is never carried by a token, so the
command line does not hold it. It proposes the manifest (no credentials),
and you approve it in the browser:
- Check the page's confirmation code matches your terminal. That is what stops a link someone sent you being approved by reflex.
- Read what the manifest declares: every collection, grant, limit and capability is listed.
- Sign in to review. The host answers with a dry run: new install or upgrade, from which version, or exactly why it would be refused. Nothing has changed yet.
- Install. The host installs the manifest it stored when you proposed it, as you. The command line prints the outcome.
A proposal lasts ten minutes and is single-use. Anyone can propose; only a configurator can approve, and denying needs no sign-in.
The API underneath, if you are building your own client:
POST /install?action=propose {manifest} → {requestId, code, url, expiresAt};
GET /install?action=status&request=<id> → {status, result?};
POST /install?action=preview|approve {requestId} with a configurator's ID token.
The direct form still works with an ID token:
curl -X POST -H "Authorization: Bearer $ID_TOKEN" -H 'Content-Type: application/json' \
-d "{\"manifest\": $(cat virta.json)}" .../install
# → { "status": "installed", "name": "virta", "version": "1.0.0", "unenforced": [] }
GET /install lists what is installed. DELETE /install?name=virta revokes.
Upgrades are additive-only. Adding a collection or an optional field is fine. Removing a collection, removing a field, newly requiring one, or changing a unique constraint are refused as migrations rather than guessed at — the newly-required case would make every already-stored document invalid.
A published version's content is immutable. Re-POSTing the same version is
normal (that is how an upgrade gets approved); re-POSTing different content
under the same version is a 409.
Revoking never drops rows. The collections become unreachable; the documents stay. A re-install restores the same library to the same data.
4b. Replicating a collection, and committing several documents at once
Two things an event log needs, both opt-in per collection:
"envelope": { "seq": true, "requireAttribution": true }
seq assigns a monotonic _seq at commit, so a replica can resume:
curl '.../docs?p=virta:event&since=42&c=100'
# → { "rows": [...], "cursor": 57, "more": true }
more is returned rather than left for you to infer — a server may cap c
below what you asked, so a short page is not the last page. Timestamps
cannot do this job: two writes in one millisecond are indistinguishable, and
the stamps come from the function instance's clock, which drifts between
instances.
The cost, so you can decide rather than discover it: a total order serialises writes to that collection, roughly one per second, through a single counter document. That is what a total order is — sharding the counter would restore throughput and destroy the ordering. An append-only log with one writer is comfortably inside it; a bulk import is not. Hence opt-in.
Declare seq before the first write. An upgrade that turns it on — or off —
for a collection that already exists is refused: documents written before it
would have no _seq, and since=0 would answer "nothing" while they sit there.
If you need it on an existing collection, install the log under a new name.
A log should also be immutable. seq promises an order; only immutable
promises the order is not rewritten:
"virta:event": { "schema": {...}, "immutable": true, "envelope": { "seq": true }, ... }
Re-writing a stored document with identical content is a no-op (so a retried
commit is safe); with different content it is refused — 409 {"error": "immutable"}, and in a batch nothing is written. Without it, an upsert over an
existing id replaces the document and gives it a new _seq: every replica
that already folded it now sees the same id at two positions in the order, and
nothing errors. A replica cannot survive re-sequencing, so a collection you
replicate should not allow it. Deletes are refused too (409 {"error": "immutable"}): delete-then-recreate would land the same id at a fresh
_seq, and a replica never hears about a delete through since= anyway.
Removing a document from a log (a legal takedown, say) is the host owner acting
on the datastore directly. immutable may be added by upgrade, never dropped — the
documents already stored were written under the promise.
A retry that must be a no-op should be a PUT or an upsert through POST /docs
— an explicit POST asserts "not yet" and is refused with exists when the
document is already there, identical or not.
Several documents, atomically:
curl -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"writes":[{"p":"virta:event/e1","data":{...}},{"p":"virta:event/e2","data":{...}}]}' \
.../docs
# → { "status": "committed", "written": 2, "results": [{"p":"…","seq":58}, …] }
All or nothing: one invalid document and nothing is written, not even the
valid ones beside it, and the sequence does not advance. Omit method and each
write is an upsert — create if absent, replace if present (refused, if the
collection is immutable), no-op if identical — which is an idempotent append
with no client bookkeeping. Naming
POST or PUT keeps the strict guard. Max 100 per commit; the same document
twice in one commit is refused.
5. Use it
# read (GET/DELETE take ?p=)
curl '.../doc?p=virta:task/abc'
curl '.../docs?p=virta:task&c=20'
# write (POST/PUT/PATCH take the path in the BODY)
curl -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"p":"virta:task/abc","data":{"title":"ship the thing"}}' .../doc
Your schema and access rules are enforced from the moment the install commits. Rule changes propagate to every warm instance within seconds, via an epoch counter — a revocation does not wait for a cache to expire.
Read this before you debug a 404
A 404 usually means "not allowed", not "not there". Denials are opaque to
non-privileged callers by design: a protected document and a missing one must
be indistinguishable, or the error code itself becomes a way to enumerate what
exists. Only admin/developer/owner see the real 403.
So if a request 404s and you are sure the document exists, check in this order:
- does your token's
collectionscaveat cover that path? - does the method fall inside its
methodscaveat? - does any
accessrule in your manifest grant that role that method? - is the collection actually installed —
GET /install?
Post-authorization errors are not opaque, because by then you have already
proved access: 403 document already exists, 403 cannot update non-existent document, and 400 with schema details all say what they mean.
The rest of the request surface
/docs?p=… |
c limit (default 10), f comma-separated fields, o order — o=date(desc) |
field=value lookups |
/doc?p=virta:task/slug=ship-it — only for fields in unique or tagFields |
| sub-collections | virta:task/abc/comment/xyz works; declaring one in a manifest does not yet |
| reserved fields | _id, _collection, _path are stripped from writes. _created, _modified, _seq, _by are endpoint-managed — stamped on the document and hidden from your schema, so additionalProperties: false works. You cannot set them. |
| provenance | every write carries _by: {uid, role, name, token?, label?}. Unforgeable. All of one person's agents share a uid — the token label is what tells them apart, and from their human. |
| errors | {"error": "<stable code>", "message": "<prose>", "details"?: […]}. Switch on error; the prose may be reworded. The codes are listed in Errors below. |
| rate limit | 100 requests/minute per IP: 429 {"error":"rate-limited"} with Retry-After. A bulk import needs to pace itself. |
| unchanged writes | a PUT whose content matches returns 200 unchanged … and does not re-stamp _modified |
Errors
Every error has the same shape, {"error": "<code>", "message": "<prose>", …}.
The codes below are the 0.2.x contract. Switch on error, never on
message. A new code is a minor release.
error |
HTTP | When | Retry? |
|---|---|---|---|
bad-request |
400 | The request is malformed: no p, a bad body, an unsupported method. |
No: fix the request |
unauthenticated |
401 | The endpoint needs a principal and none was presented (/install, /token, /claim, /authorize). |
After signing in |
forbidden |
403 | A privileged caller lacks this access. Non-privileged callers get not-found instead. |
No |
not-found |
404 | Missing, or not visible to you: opaque on purpose (see above). | No |
exists |
403 | POST to a document that exists. Use PUT, or an upsert through POST /docs. |
No |
missing |
403 | PUT/PATCH/DELETE on a document that does not exist. |
No |
schema |
400 | The body fails the collection's schema. details lists {path, message}. |
No: fix the body |
validate |
400 | The collection's transform refused the write. | No |
unique |
400 | A unique field is missing, not a string or number, or already used. |
No |
unattributed |
403 | The collection requires attribution (envelope.requireAttribution) and the caller has no principal. |
After signing in |
immutable |
409 | A changed rewrite, or a delete, of a document in an immutable collection. An identical rewrite is a no-op instead. |
No |
refused |
400 / 403 | An install, token, claim or batch decision refused the request. problems lists why. |
No: fix what it names |
conflict |
409 | Re-installing a published manifest version with different content. | No: bump the version |
not-sequenced |
400 | since= on a collection without envelope.seq. |
No |
rate-limited |
429 | More than 100 requests/minute from one IP. | Yes, after Retry-After |
too-large |
413 | A file exceeds its storage area's maxBytes, or the endpoint's upload limit. |
No |
unsupported-type |
415 | A file's content type isn't in its storage area's contentTypes. |
No |
internal |
500 | Something failed on the host. | Yes |
A POST /docs batch refuses with the same codes and statuses as /doc. It
names the document in p, and nothing in the batch is written.
5b. Store files
A storage area is a collection whose documents describe files. Declare one
in your manifest like any collection, with blob limits instead of a schema
(the schema defaults to the file-metadata schema):
"virta:files": {
"blob": { "maxBytes": 10485760, "contentTypes": ["image/*", "application/pdf"] },
"access": [
{ "role": "public", "read": "ALL", "list": "ALL" },
{ "role": "author", "write": "ALL" }
]
}
The area's access rules are the file's access rules: read to fetch a file,
list to list them, write to upload, replace, move or delete. Public vs
private is not a setting; it is derived. An area where public has
unconditional read is public; anything else is private.
# upload (or replace) — the body is the file; Content-Type is required
curl -X PUT -H "Authorization: Bearer $TOKEN" -H 'Content-Type: image/png' \
--data-binary @logo.png '.../blob/virta:files/brand/logo.png'
# → { "status": "stored", "path": "brand/logo.png", "bytes": 5120, "sha256": "…" }
curl '.../blob/virta:files/brand/logo.png' # fetch
curl -X DELETE -H "Authorization: Bearer $TOKEN" '.../blob/virta:files/brand/logo.png'
curl -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"op":"move","from":{"area":"virta:files","path":"a.png"},"to":{"area":"virta:files","path":"b.png"}}' \
.../blob
curl '.../docs?p=virta:files&c=50' # list: the metadata documents
# copy a file from a legacy folder (blog/, public/, users/) into an area, on the server
curl -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"op":"import","from":"blog/Character Sheet.pdf","to":{"area":"virta:files","path":"Character-Sheet.pdf"}}' \
.../blob
# → { "status": "imported", "path": "Character-Sheet.pdf", "bytes": 5120, "sha256": "…" }
What to know:
- Size and hash are measured by the server, never taken from the client.
Re-uploading identical bytes returns
unchanged; changed bytes returnreplaced. A move never overwrites: an occupied destination is403 exists. - Metadata is written only through
/blob. A/docor/docswrite to a storage area is403 refused, so a metadata document always means the file exists. Each one carries_byprovenance like any document. importcopies, on the server. The original stays where it is. Nothing is downloaded or re-uploaded, so only the area's own limits apply. It never overwrites, and repeating it with the same file answersunchanged.- Paths are
/-separated segments of letters, digits,.,_and-, each starting with a letter or digit, 512 characters at most. No spaces. - Limits:
413 too-largeover the area'smaxBytes, or over the endpoint's own 25 MB ceiling, which no area can raise.415 unsupported-typeoutsidecontentTypes. The type may be exact (application/pdf) or a family (image/*). OmitcontentTypesto allow any. - Delivery. A fetch is either a
302to a signed Cloud Storage URL or the bytes streamed by the function. Both are correct; which one you get depends on the host. Signing needs the functions service account to hold "Service Account Token Creator" on itself, and the bucket to allow cross-origin reads of the signed response;bun scripts/enable-signing.js --alias <host>sets up both (new hosts get them from the provisioner). Without signing the host streams, and logs once that it is doing so. A redirect is never cached (no-cache): it names one version of the file, which a replace deletes. Streamed public files cache for five minutes (public, max-age=300); private ones areprivate, no-store, and a signed link to one lives for five minutes. - A content type is exactly one type,
type/subtype(parameters like; charset=are dropped). A list such asimage/png, text/htmlis400. - Streamed files come from your site's origin, so they are sent
nosniffand served under a sandbox CSP: an uploaded SVG cannot run script as your site. Through Hosting, every streamed file is sandboxed (images, media and PDFs still display). Called directly, the function sandboxes all but inert media. - Files are reachable only through
/blob. Area objects share the default bucket with the legacy folders. Everything else that reads the bucket —storage.rulesfor direct client access, and/stored— reads only an allowlist of legacy folders (blog/,public/,users/), so an area is out of their reach by construction. Deploystorage.ruleswith the functions. - The sandbox comes from Hosting. Hosting's site-wide CSP replaces a CSP
set by a function, so
firebase.jsonhas a header rule sandboxing/blob/**and/stored/**, placed after the site-wide one. Keep it if you change your headers. - Denials are opaque, as everywhere: a private file you cannot read is a
404, the same as a missing one. - Hosting: a host serving
/blobfrom its own domain needs the rewrite{"source": "/blob/**", "function": "blob"}infirebase.json, before any catch-all rewrite.
An area can be immutable (files cannot be replaced, moved out or deleted:
409 immutable). Whether an area stores files is fixed at install: an upgrade
cannot turn a collection into a storage area or back.
6. Give an agent its own identity
bun scripts/cli-login.js --host https://us-central1-<project>.cloudfunctions.net \
--label "ci × virta" --roles author --collections virta:task
Opens a browser, you approve, the token lands in ~/local-secrets/ at 0600.
Add --poll on a machine with no browser — and read the warning it prints.
scripts/cli-login.js is a readable reference client, not a package, so you can
reimplement the protocol in whatever language your agent is written in.
What a token is: (principal, caveats). Effective authority is recomputed
on every request as rolesOf(principal) ∩ caveats.roles. So:
- a token never holds what its principal does not hold right now;
- revoking the human revokes every agent they authorised, instantly, with no revocation list and nothing to remember to do;
owner,configuratoranddevelopercan never be carried by a token — each is authority over the system itself, and belongs to a human at an interactive session, not to a secret in a file;- a token cannot mint another token;
DELETEis not in the default methods. Ask for it explicitly.methods: ['GET']is read-only, and the token recordsGETandLIST: a list (GET /docs, thesince=delta included) is checked asLIST. A token minted with onlyGETbefore this cannot list; mint a new one.
The token is the provenance. Its label — machine × repo — travels with every write it makes, so "which agent wrote this" is answerable from the record rather than from a field the writer chose to populate honestly.
The secret is shown once and is never stored — only a sha256. It is not recoverable by anyone, including whoever reads the datastore. A lost token is re-minted, never retrieved.
What is NOT ready
Said plainly, because a release that oversells itself wastes your time:
| Capability enforcement | The manifest shape for capabilities is settled and validated (blob, email, sms, outbound, turn), but nothing consults them yet. The install response reports unenforced: [...] so you are never told you have a power you do not. See #11. A blob capability is superseded: file storage is a storage area (see Store files), and the install response lists any blob capability under superseded with that pointer. |
| Large files | Uploads pass through a Cloud Function, so 25 MB is the ceiling. Signed direct uploads to Cloud Storage for larger files do not exist yet. |
| Sub-collections in manifests | A manifest declares one segment. virta:task/comment works at runtime but cannot be declared. |
| Composite (tuple) uniqueness | Not supported. unique: ["a", "b"] makes each field unique on its own; there is no "the pair is unique" constraint. That would need a composite index, which is a deployment. |
docs.ts query port |
/docs still queries Firestore directly; the substrate port (#7) covers writes only. |
| Stored ajs | Install v2. Grounded on tjs-lang, re-validated per ROADMAP before anything is built on it. |
| 10 of the 12 universal-endpoint invariants | Still test.todo (isWriteAllowed, procedures, capability VM enforcement, observability). They are acceptance criteria, not passing tests, so don't read a green suite as covering them. The no-op and server-written envelope invariants are real tests now. |
| The platform's own rules as data | A host can serve post, page, role and the rest from stored configs (PLATFORM_CONFIGS_FROM_REGISTRY=true; loewald.com does). It is off by default. Before turning it on, run scripts/seed-registry.js --alias <a> --apply and then --check: with the switch on and the registry unseeded, those collections are inaccessible. |
Where to push hardest
The manifest format is the thing most worth breaking. It was designed against three consumers at once and validated against one; if it cannot express something your design needs, that is the bug — say so rather than bending virta to fit it. A format weakness discovered now is a comment on an issue; the same weakness discovered after adoption is a migration.
Issues: https://github.com/tonioloewald/tosijs-platform/issues