> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dashlink.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# API DECISIONS

# Dashlink Public API — Phase 0 Decision Record

This document is the authoritative answer to the blockers identified before documentation work began. Every decision here is reflected in `api-reference/openapi.json`, `docs.json`, and the reference pages. If any of these change, the generator and the concept pages must change with them.

Status: Phase 0a complete. Items requiring production access are flagged as **NEEDS HUMAN VERIFICATION**.

***

## D1 — Base URL

**Decision: `https://api.dashlink.ai` is the production API base URL.**

Evidence is authoritative rather than inferred: the dashboard's own environment configuration at `dashlink-fe-app/.env.example` declares

```
REACT_APP_API_BASE_URL_PROD=https://api.dashlink.ai
REACT_APP_API_BASE_URL_STAGING=https://stagingapi.dashlink.ai
REACT_APP_WEBSITE_URL_PROD=https://dashlink.ai
```

`https://dashlink.ai` is the marketing website, not the API. The value previously published in `docs.json` (`api.baseUrl`) and in `overview/introduction.mdx` was the website URL and was wrong.

Staging base URL for testing: `https://stagingapi.dashlink.ai`.

***

## D2 — Canonical URL form

**Decision: `https://api.dashlink.ai/api/v1/<module>/<method>` is the single documented form.**

Four shapes currently resolve. `/api/v1/`, `/service/v1/`, and `/v1/` are dispatched by the same handler in `dashlink/api/__init__.py` and are strictly equivalent; `/api/method/dashlink.api.v1.<module>.<method>` is Frappe's native RPC form and reaches every whitelisted method.

`/api/v1/` is documented because it is the most conventional shape, it is what the REST router was built for, and it already matches the one endpoint published today. `/service/v1/` and `/v1/` remain working aliases but are not documented. `/api/method/` is not documented — it exposes the internal module path and is an implementation detail.

Consequence: every module backing a documented endpoint must appear in the `supported_modules` allowlist in `dashlink/api/__init__.py`. `app_association` was missing and is added in Phase 0b.

***

## D3 — Authentication transports

**Decision: `X-API-Key` is the documented transport. `Authorization: Bearer` and `Authorization: ApiKey` do not work and must not be documented.**

`get_api_key_from_request()` in `dashlink/api/v1/api_key_auth.py` appears to accept four transports, but two of them are unreachable. Frappe's `validate_auth()` runs before any Dashlink code, on both the REST path and the `/api/method/` path:

```python theme={null}
def validate_auth():
    authorization_header = frappe.get_request_header("Authorization", "").split(" ")

    if len(authorization_header) == 2:
        validate_oauth(authorization_header)
        validate_auth_via_api_keys(authorization_header)

    validate_auth_via_hooks()

    if len(authorization_header) == 2 and frappe.session.user in ("", "Guest"):
        raise frappe.AuthenticationError
```

A Dashlink key (`dlk_live_...`) is neither an `OAuth Bearer Token` record nor a Frappe `api_key:api_secret` pair, so neither validator authenticates it. `validate_auth_via_hooks()` is a no-op because `auth_hooks` is commented out in `dashlink/hooks.py` (line 666). The session therefore remains `Guest`, the header has two parts, and `frappe.AuthenticationError` is raised before the request reaches Dashlink.

`X-API-Key` and `?api_key=` never populate the `Authorization` header, so the split yields a single-element list, the guard does not fire, and `get_api_key_from_request()` picks the key up normally.

**Supported and documented:**

* `X-API-Key: dlk_live_...` — the documented transport.

**Works but documented only as a discouraged fallback:**

* `?api_key=dlk_live_...` — query strings land in access logs, proxy logs, browser history, and `Referer` headers.

**Does not work, removed from the docs:**

* `Authorization: Bearer` and `Authorization: ApiKey`.

**Follow-up (not Phase 0):** registering an `auth_hooks` entry that authenticates Dashlink keys would make `Authorization: Bearer` work and match what developers expect. That is a global change to request authentication and carries real risk, so it is deliberately out of Phase 0 scope. The dead branches in `get_api_key_from_request()` are annotated rather than deleted so the function still works if an auth hook is added later.

**NEEDS HUMAN VERIFICATION:** this conclusion is from code inspection. Outbound requests from the development machine are blocked by a corporate proxy, so the four transports could not be curled against staging. Re-run the check in `scripts/smoke_test.sh` from an unproxied network before publishing.

***

## D4 — API key permission modules

**Decision: `valid_modules` is replaced with the `API Key Permission` doctype's option list.**

The doctype offered 11 modules; `api_keys.py` validated against `["shortlinks", "app_dynamic_link", "campaign", "analytics"]`. Of those four, `app_dynamic_link` and `campaign` match no string any endpoint authorizes against, so a restricted key granted either was denied on every call.

The documented module list is the eight the public API actually authorizes against:

`shortlinks`, `qrcode`, `campaigns`, `analytics`, `domains`, `utm_templates`, `tags`, `organization`

App dynamic links are Shortlink records and are covered by the `shortlinks` grant. `plans` and `search` remain valid doctype options but back no documented endpoint.

**`permission_level`:** `read` and `write` are documented. `none` is accepted by the doctype but is equivalent to omitting the row, so it is not documented. `all` is checked by `validate_api_key_permission` but was never creatable; it is now accepted at creation so the authorizer's hierarchy (`read < write < all`) is reachable.

***

## D5 — Response envelope

**Decision: one success envelope and one error envelope, on every documented endpoint.**

Success:

```json theme={null}
{ "data": { } }
```

Error:

```json theme={null}
{
  "error": {
    "message": "Human-readable description.",
    "status_code": 404,
    "code": "NOT_FOUND",
    "details": {}
  }
}
```

`code` and `details` are optional; `message` and `status_code` are always present. The HTTP status matches `status_code`.

Two deviations existed and are corrected in Phase 0b.

Four channel endpoints returned a value instead of assigning `frappe.response["data"]`, which made the envelope key depend on which URL form was called — `data` on `/api/v1/`, `message` on `/api/method/`: `campaigns.update_channel`, `campaigns.delete_channel`, `campaigns.add_shortlinks_to_channel`, and `campaigns.remove_shortlinks_from_channel`. A `create_success_response` helper now makes the idiom explicit rather than conventional. (`domains.verify_domain` was also suspected but proved already correct — every one of its exit paths routes through `_verification_success_response`, which sets the envelope.)

Separately, any `frappe.throw` reaching the client produced Frappe's native `{"exc_type", "_server_messages"}` body, with `ValidationError` mapping to HTTP 417 Expectation Failed — a status that tells an API client nothing. Rather than rewrite every call site, `rest_router.py` now catches Frappe's exceptions at the point of dispatch and re-expresses them in the documented envelope:

| Frappe exception | HTTP | `code` |
| - | - | - |
| `AuthenticationError` | 401 | `AUTHENTICATION_REQUIRED` |
| `PermissionError` | 403 | `PERMISSION_DENIED` |
| `DoesNotExistError` | 404 | `NOT_FOUND` |
| `DuplicateEntryError` | 409 | `DUPLICATE_ENTRY` |
| `LinkExistsError` | 409 | `LINK_EXISTS` |
| `MandatoryError` | 400 | `MISSING_PARAMETER` |
| `ValidationError` | 400 | `VALIDATION_ERROR` |

Order matters: `DoesNotExistError`, `MandatoryError`, and `LinkExistsError` all subclass `ValidationError`, so the general case is tested last. Anything unrecognised keeps propagating, so a genuine fault still produces a 500 and a traceback in the error log rather than a tidy message that hides it. The handler also strips desk markup from the message, clears the queued message log, and rolls back, so a half-written transaction cannot survive a thrown error.

***

## D6 — Pagination and sorting

**Decision: `page` / `per_page` on request, flat metadata on response.**

Request: `page` (1-based, default 1) and `per_page` (default 10, maximum 100). Values above the maximum are clamped, not rejected, and the clamped value is echoed back.

Response, alongside a named collection key (`links`, `qrcodes`, `campaigns`, `tags`, `utm_templates`):

```
total_count, total_pages, current_page, per_page
```

`qrcode.get_qrcodes` echoed `page_size`; it now echoes `per_page` as well, with `page_size` retained as a deprecated alias so the dashboard does not break.

**Sorting:** `sort_by` is lowercase everywhere — `name`, `most_recent`, `last_modified` — and `order` is `asc` or `desc`. Three endpoints validated against `"Most Recent"` while two validated against `"most_recent"`, so the same parameter had two spellings depending on which list you were reading. `normalize_sort_by` in `utils.py` folds the title-cased spelling onto the lowercase one, so existing callers keep working; only the lowercase form is documented.

**`most_clicked` is removed, not fixed.** It was accepted by validation on four endpoints but was present in no `sort_field_map`, so it fell through to the default and silently sorted by title — a successful response in the wrong order, with nothing to indicate it. Click counts live in Tinybird, not on the Shortlink doctype, so there is no column to order by and no way to honour it without a different query path. Until that exists, rejecting the value with a 400 is the honest answer.

***

## D7 — Deletion is bulk-only

**Decision: no single-resource delete endpoints are added.**

Links, QR codes, and UTM templates are deleted only through bulk operations. Deleting one resource means passing a single-element array.

* Links: `bulk_delete_shortlinks`, or `shortlinks.bulk_edit` with `action="delete"`
* QR codes: `qrcode.bulk_edit` with `action="delete"`
* UTM templates: `bulk_delete_utm_templates`

`campaigns.delete_campaign` and `domains.delete_domain` already exist as single-resource deletes and are unchanged.

Because bulk is now the only delete path, the four bulk endpoints are aligned onto one result shape in Phase 0b:

```json theme={null}
{
  "status": "partial_success",
  "summary": { "total": 3, "succeeded": 1, "failed": 1, "skipped": 1 },
  "results": [
    { "index": 0, "outcome": "success", "name": "SHORT-0001", "error": null },
    { "index": 1, "outcome": "skipped", "name": "SHORT-0002",
      "error": { "message": "Not found.", "code": "NOT_FOUND" } },
    { "index": 2, "outcome": "error", "name": "SHORT-0003",
      "error": { "message": "Permission denied.", "code": "PERMISSION_DENIED" } }
  ]
}
```

The top-level `status` grades the whole operation and is `success`, `partial_success`, or `error`. Each item carries `outcome`, which is `success`, `error`, or `skipped`. The per-item key is named `outcome` rather than `status` because reusing one word for both scopes invites reading one as the other.

`summary.succeeded + summary.failed + summary.skipped` always equals `results.length`.

The four endpoints previously returned four different shapes — two returned `{"success": [...], "failed": [...]}`, one added `total_deleted`/`total_failed` beside those lists, and one returned an indexed `results` array. Those keys are retained as undocumented aliases because the dashboard reads them; `finalize_bulk_response` in `utils.py` derives the canonical trio from whichever shape it is handed.

One gap this exposed and fixed: `bulk_delete_shortlinks` recorded no identifier on a failed item, so a caller could only tell which id failed by counting array positions. Every item now echoes `name`.

***

## D8 — Retention truncation

**Decision: surface it. Silent truncation is not acceptable on a public API.**

Analytics windows are clamped to the plan's retention period at the Tinybird transport. A Free-plan caller requesting `date_from=2020-01-01` received roughly 30 days of data with no indication the window moved.

Analytics responses now include a `retention` block when a clamp occurred:

```json theme={null}
{
  "data": {
    "status": "success",
    "analytics": {},
    "retention": {
      "clamped": true,
      "earliest_date": "2026-08-26",
      "retention_months": 1
    }
  }
}
```

The key is absent when no clamp occurred.

***

## D9 — Four unknown analytics references

**Resolved: all four are dead or broken frontend code. The Analytics group is unaffected.**

`dashlink-fe-app/src/utils/api.js` calls four endpoints that do not exist anywhere in `dashlink/api/v1/`:

* `analytics.get_shortlink_analytics` (line 881) — wrapper `fetchAnalytics`, not imported anywhere
* `analytics.get_shortlink_analytics_metrics` (line 887) — wrapper `fetchAnalyticsMetrics`
* `analytics.get_shortlink_analytics_details` (line 933) — wrapper `fetchAnalyticsDetails`, not imported anywhere
* `analytics.get_users_over_time` (line 941) — wrapper `fetchUsersOverTimeAnalytics`, not imported anywhere

**Frontend bug to report separately:** `fetchAnalyticsMetrics` is not dead. It is imported and called at `src/components/LinkDetails/LinkDetails.js:1697`, so that call path requests a non-existent endpoint and fails. This is outside the documentation scope but should be raised with the dashboard team.

***

## D10 — Scope questions

**CSV import — OUT of the v1 public API.** `bulk_create_shortlinks` covers programmatic bulk link generation, which is the stated integration need. CSV import is a file-upload workflow built for the dashboard, involving async job polling, cancellation, and error-CSV download. It is a reasonable v2 addition; if added, `shortlinks_import` must also be added to the REST allowlist.

**QR create canonical form — `create_qr_code_v2` and `edit_qr_code_v2`.** Both are actively exercised by the dashboard, which is the selection principle applied to every other endpoint. The named-parameter `create_qrcode` has better ergonomics for an API and `edit_qrcode` is not called by the dashboard at all, making it the less-proven path. Revisit if a JSON-native QR create is worth building.

**`get_campaign_kpis` — made API-key capable.** It was session-only, leaving campaign KPI parity missing from the API while the organization equivalent (`get_org_kpis`) was available. Phase 0b swaps its `get_logged_in_user()` / `get_user_organization()` preamble for `resolve_request_principal`. This brings the documented surface to **80 endpoints** (see the count table at the end).

***

## D11 — Security fixes landed before documentation

Documenting an endpoint is an invitation to call it, so these were fixed first. All were found by reading the endpoints chosen for the public surface.

### Cross-tenant access (IDOR)

**`shortlinks.get_shortlink`** authenticated the caller and then discarded the principal — the code said so: *"we don't currently use user/organization here"*. Any valid key could read any link in any organization by naming it. The check had to go **before** the cache read, not after, because the cache key is `shortlink_details_{name}` with no tenant in it, so a check placed after the lookup would be skipped on every hit.

**`qrcode.download_qr_code_image`** had the same shape: principal resolved, document fetched without reference to it. A QR code image encodes the short link it points at, so this leaked link data too.

**`qrcode.bulk_edit`** was the most serious. With `action="delete"` it deleted any named QR code **and its associated short link**, both with `ignore_permissions=True`, with no ownership check at all. The request-level `org_write_denied_response` check that was present confirms the caller may write in *its own* organization, which says nothing about who owns the document being deleted. Ownership is now checked per item, inside the loop. (`shortlinks.bulk_edit` already did this correctly and needed no change.)

**`tags.add_tags` and `tags.remove_tags`** both did `organization = document.get("organization") or user_organization` — assigning the target document's organization *over* the caller's rather than comparing the two, so another tenant's document was simply accepted and modified. Both also passed the caller-supplied `doctype` straight into `frappe.get_doc`, making any doctype on the site reachable; that is now restricted to `Shortlink` and `QRCode`, the only two that carry an `organization` field.

These all answer **404, not 403**, on a document belonging to another organization. A 403 confirms the name exists, which turns any endpoint taking a document id into an enumeration oracle.

### `tags.remove_tags` — cross-tenant destruction via an omitted parameter

Called without `docname`, it ran `frappe.db.delete("Tag Link", {"tag": tag})` with no organization filter and then force-deleted the `Tag`. Deleting your own tag stripped that tag from **every other tenant's links**. Leaving out one optional parameter was the whole attack.

The plan called for requiring `docname`, but the dashboard genuinely uses the delete-entirely path (`deleteTag` in `api.js` sends no `docname`), so requiring it would have broken a real feature. Instead the deletion is scoped: only Tag Links whose linked document belongs to the caller's organization are removed, and the shared `Tag` record is deleted only when no links remain anywhere else.

This is a workaround for a deeper issue. `Tag` and `Tag Link` are Frappe **core** doctypes with no organization field, so tag names are global across all tenants — two organizations both using `campaign` share one `Tag` record. Ownership can only be inferred from the linked document. Giving tags a real tenant is worth doing properly.

### `organization.get_users` — leaked invitation tokens

The response included `invitation_token` for every pending invitation, annotated *"For frontend to generate acceptance link."* It is the bearer credential that accepts an invitation, so listing members handed every reader the means to join the organization as any pending invitee. No frontend code reads it from this response — the only consumer, `Signup.js`, takes it from the emailed URL. Removed from both the query and the payload.

### `files.serve` — unauthenticated arbitrary file read

`allow_guest=True`, with the caller-supplied `file` passed to `os.path.join` and read with no confinement. Two separate escapes: `../../` walked out of the directory, and an absolute path such as `/etc/passwd` made `os.path.join` discard the base entirely. Verified against the real behaviour — `file=../../site_config.json` returned the site config, database credentials included.

Now both paths are resolved with `os.path.realpath` and compared with `os.path.commonpath`, which is not fooled by symlinks, `..`, or a filename that merely starts with the right prefix. Traversal returns the same "File not found" as a genuinely missing file, so the response cannot be used to probe what exists outside the directory.

**Separate issue, not fixed:** this endpoint reflects any `Origin` back in `Access-Control-Allow-Origin` together with `Access-Control-Allow-Credentials: true`. The dashboard is on a different origin and needs CORS here, so changing it needs its own testing rather than being folded into a traversal fix.

### `domains.is_domain_in_use` — server-side request forgery

`allow_guest=True`, caller-controlled host interpolated into `https://{domain_name}`, with `allow_redirects=True`. An open proxy into anything the server could reach: cloud metadata at `169.254.169.254`, services on localhost, and the private network.

Three guards, each closing a different route:

1. The value must match a bare-hostname pattern, so nothing can be smuggled through a port, path, or embedded credentials (`evil.com:8000/admin`, `user:pass@internal.svc`).
2. Every address it resolves to must be publicly routable — all records, not just the first, since a name returning one public and one loopback address is still a way into loopback.
3. Redirects are no longer followed, so a public host cannot bounce the request to a private one after the check has passed.

Verified against the payload list: metadata IPs, `localhost`, RFC-1918 ranges, `0.0.0.0`, port and credential smuggling, and a split-DNS response are all rejected; ordinary domains still pass.

**Residual risk:** a gap remains between the resolution check and the request itself, so DNS rebinding is still theoretically possible. Closing it properly means pinning the resolved address for the connection. Given this endpoint only reports whether a domain serves content, and redirects are now disabled, the remaining exposure is a single unredirected HEAD request.

***

## D12 — Documentation infrastructure

Decisions taken while building the site, recorded because each one is a thing a
future maintainer would otherwise have to rediscover.

**Operation page URLs are pinned, not inferred.** Mintlify generates a page for
every `METHOD /path` entry in `docs.json` and derives a URL for it. The group
index pages link to those pages, and guessing the derivation would make every
link a hostage to an implementation detail. Each operation therefore carries
`x-mint.href` in the spec, set by `page_url()` in `scripts/build_manifest.py`,
which both the spec generator and the group page generator call. URLs are
`/api-reference/<group>/<method-name>`, such as
`/api-reference/links/create-shortlink`.

**`llms.txt` is custom, not the generated one.** Mintlify hosts an automatic
`llms.txt` listing every page alphabetically; a file at the project root
overrides it. The generated version is a flat page list, which does not tell a
model that deletion is bulk-only, that `Authorization: Bearer` fails, or that
analytics can return sample data flagged `locked`. `scripts/generate_llms_txt.py`
writes a curated file whose preamble carries those facts and whose page lists
come from `docs.json` and the spec, so only the preamble is hand-written.

**Per-page `.md` variants need no work.** Mintlify serves a Markdown version of
every page at `<url>.md` automatically. `llms.txt` links to those URLs.

**Everything generated is drift-checked.** `.github/workflows/docs-drift.yml`
runs the spec, navigation, group page and `llms.txt` generators in `--check`
mode against a checkout of the backend, lints the spec with Redocly, and runs
`scripts/check_links.py`. A parameter renamed in Python without regenerating
fails CI rather than quietly making the reference wrong.

**Internal links are checked, external ones are not.** Mintlify renders a broken
internal link as plain text with no build error, so `check_links.py` verifies
every `/path` link resolves to a page that exists and that every page is
reachable from the navigation. External links would need the network and fail
for reasons unrelated to the change under review.

## Endpoint count

| Group | Endpoints |
| - | - |
| Links | 12 |
| App Dynamic Links | 5 |
| QR Codes | 8 |
| Campaigns | 12 |
| Analytics | 22 |
| Branded Links / Domains | 11 |
| Tags | 3 |
| UTM Templates | 4 |
| Users | 2 |
| Account Limits | 1 |
| **Total** | **80** |

Campaigns is 12 rather than 11 because `get_campaign_kpis` joins the group under D10.

Analytics is 22 rather than the 20 originally scoped: `get_campaign_users_over_time`
and `get_org_metrics_batch` were added once D9 resolved which analytics references
were real.

These counts are generated, not maintained — `python scripts/build_manifest.py`
prints them per group.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.