# KeyLockr Delegated SSO Go Example

The recommended mobile flow keeps KeyLockr completely out of the third-party App and backend
network path:

1. The App calls its own backend `POST /kl/login/start`.
2. The App opens the returned `keylockr://sso-request?...` deep link and waits for its registered
   Universal Link/App Link callback (recommended) or an exact allowlisted custom scheme such as
   `cing://sso/callback`.
3. The App sends the opaque backend assertion and its private `finish_secret` to its own backend
   `POST /kl/login/finish`.

The third-party backend does not call KeyLockr during finish. It verifies the KeyLockr seal and
authenticated box offline. The public `delegated.go` helper implements the signed request, strict
callback parser, assertion verification, finish-secret check, time bounds, and atomic completion
store contract. `testdata/delegated_sso_v1.json` is the canonical cross-language fixture.

## Backend Start

Use Go 1.23 or newer. Persist the signing and encryption private keys in backend secret storage;
register only their public keys and exact return URLs in MyDeveloper.

```go
start, err := StartDelegatedSSO(DelegatedStartOptions{
    AppTag:       "your-app-tag",
    ReturnURL:    "https://login.example.com/keylockr/callback",
    Capabilities: []string{"sso"},
    // 由受信任代理位址解析器取得 /start 的瀏覽器來源，不能讀 JSON body 的自稱 IP。
    ReqIP:        browserIP,
    ReqTS:        time.Now().Unix(),
}, serviceSigningPrivateKey)
if err != nil {
    return err
}

// Store start.Pending in Redis for 720 seconds. Never log the response body.
// Return Cache-Control: no-store plus these fields to the App:
// start.DeepLink, start.FinishSecret, start.RequestDigest, start.ExpiresAt.
```

`challenge` and `finish_secret` are independent 32-byte CSPRNG values. The challenge is public;
the finish secret is private caller proof. Both deadlines come from one wall-clock snapshot:
approval expires after 600 seconds and pending retention after 720 seconds.

The optional `ReqIP` and `ReqTS` pair is signed into a 13-field v1 claim. Use the browser's
address from the `/start` request after applying your reverse proxy trust policy; do not accept
an IP from the request body or substitute the Safe's address. The timestamp must be within
60 seconds of the SDK start snapshot and before the request expiry. Invalid or incomplete
pairs are rejected before signing. Omit both fields only when the service cannot provide the
source: the original 11-field claim remains valid and the Safe explicitly displays that the
service did not provide the request source. Country differences are informational; source
metadata never grants approval or proves the person operating the requesting device.

## App Callback

Keep the finish secret and request digest in sensitive local pending state. Never place the finish
secret in a QR code, deep link, callback URL, log, crash report, or analytics event.

```go
callback, err := ParseDelegatedCallbackURL(callbackURL, pending.RequestDigest)
if err != nil {
    return err
}
if callback.Cancelled {
    // Delete only the App's local pending state. Do not call finish.
    return nil
}
// Send callback.BackendAssertion and the original finish_secret to your backend.
```

The parser rejects duplicate/unknown callback fields, digest mismatch, non-canonical base64url,
and every size-limit violation before finish. A callback alone never creates a session.
Custom schemes can be claimed by another App, so treat the callback as an untrusted carrier. The
interceptor cannot finish without the backend private key and original finish secret, but the real
receiver must still fail closed on any seal, box, claim, digest, secret, or canonical-URL failure.

## Backend Finish

`CompleteDelegatedSSO` verifies the assertion offline and then calls the supplied completion store.
The store implementation must atomically move the Redis transaction from pending to completed,
return the same session for the same secret/assertion replay, and reject every mismatch. Do not
create a SQL approval/transaction table or call `/app_verify`.

```go
session, err := CompleteDelegatedSSO(
    ctx,
    redisCompletionStore,
    pending,
    finishSecret,
    backendAssertion,
    keyLockrSigningPublicKey,
    keyLockrEncryptionPublicKey,
    serviceEncryptionPrivateKey,
    time.Now(),
)
if err != nil {
    // Externally expose only a generic authentication failure.
    return err
}
```

Before activating `session`, every login client must show the verified nickname and full Safe ID
and require explicit confirmation. Use Safe ID as the stable external identity; nickname is display
text only. Keep an expected Safe ID baseline on the client and warn before switching accounts.

## Logout and Binding Cleanup

An SSO binding uses `(safe_id, app_tag, enc_pk)` as its persistent identity. The `sign_pk` is only
the current login credential. For normal logout, call `Client.LogoutSSO(appID)`: after the server
confirms `app_logout`, the helper replaces the local signing keypair while retaining the encryption
keypair. The server keeps the same `app_id`, capabilities, and AppData file. A later Safe approval
with that retained `enc_pk` and the new `sign_pk` reactivates the same binding.

If the response is lost or invalid, the helper still replaces the local signing keypair and returns
an error stating that server logout is unconfirmed. Do not report remote revocation as successful;
the next trusted authorization with the retained `enc_pk` atomically replaces any old server
credential. `LogoutSSO` is SSO-only and must never be used for a persistent AP pairing.

Delegated and alias responses do not prove whether a binding was created by this transaction or an
existing SSO encryption identity was reused. Never call `app_logout` or `app_del` automatically after
a callback, finish, session-persistence, or AppData failure. Delete only local pending/session state.
Use `app_del` only for explicit permanent disconnection after a fully verified success; deleting the
last binding that references an AppData file also deletes that shared file.

## AppData CAS Conflicts

After an initial `file_ver_conflict`, read and decrypt at most once and send at most one more CAS
write. For a single-slot value such as a recovery key, an authoritative value exactly equal to the
intended value is idempotent completion: adopt the latest version without writing. If the values
differ, stop and require explicit resolution; never overwrite, concatenate, or choose by timestamp.
Only payloads with a defined deterministic field-level merge may merge once and retry once. A
second conflict always terminates.

General KPS outer, `kps`, inner, and header maps are closed core schemas. Reject unknown or duplicate
core fields, trailing values, invalid UTF-8, wrong types, and malformed raw placeholders before
materialization. General action bodies are extension boundaries: validate `_res` and documented
required fields, then ignore unknown fields unless that action is explicitly documented as closed.

`Client.PostKPS` treats `app_credential_pending` as a persistent invalidation barrier and performs
only three bounded exponential-backoff retries. It never bypasses the barrier with an old cache or
session. Long-lived callers should use `Client.PostKPSContext` so cancellation stops both the HTTP
request and any pending backoff. `app_credential_stale` has the opposite recovery: close the old
KPS/WebSocket session and reconnect with the current `app_id` and keypair. Long-lived integrations
can detect it with `IsAppCredentialStale(err)`. Do not log out, clear the encryption keypair, or
retry on the old socket.

`server_error` is a temporary database or backend dependency failure. The sample waits 500 ms and
retries only twice, with the same caller cancellation covering both backoff and HTTP. Exhaustion
returns the `APIError`; it never logs out or clears either keypair.

## Legacy Advanced Example

`main.go`, `kps.go`, `kps_decode.go`, and `appdata.go` retain the existing direct-client handshake for
compatibility with installed integrations. That legacy path uses KeyLockr HTTP, a temporary
WebSocket, native completion callbacks, optional AppData/AP access, `app_logout`, and `/app_verify`
where applicable. Delegated SSO must never silently fall back to it.

```bash
env GOWORK=off go test ./...
go run . -app-tag YOUR_APP_TAG
```

Never log or upload private keys, finish secrets, assertions, complete callback URLs, the AP Account
Key, AppData filekeys, decrypted AppData, or plaintext credentials.
# WebSocket overload

`WaitForAuth` distinguishes HTTP 503 / `Retry-After` and the existing JSON
`try_later_auto … milliseconds` handshake response. It closes failed response bodies,
retries at most twice with a fresh signature, and counts dialing and retry waits within
the caller's authorization timeout. Other JSON API errors remain inspectable through
`errors.As(err, *APIError)`; overload never discards local keys or pairing state.
