From fe21a8b2451364e9f59568279a20a508938afe98 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 06:35:32 +0530 Subject: [PATCH 1/9] feat(kin): native approval key module (APPR-6) Co-Authored-By: Claude Opus 5.5 --- apps/mobile/.swiftlint.yml | 1 + apps/mobile/app.config.ts | 1 + .../mobile/modules/kin-approval-key/README.md | 160 +++++ .../kin-approval-key/android/build.gradle | 21 + .../android/src/main/AndroidManifest.xml | 3 + .../kinapprovalkey/ApprovalKeyStore.kt | 160 +++++ .../kinapprovalkey/KinApprovalKeyModule.kt | 215 +++++++ .../expo/modules/kinapprovalkey/KinGrant.java | 425 +++++++++++++ .../kin-approval-key/expo-module.config.json | 10 + .../fixtures/grant-vectors.json | 586 ++++++++++++++++++ .../modules/kin-approval-key/index.test.ts | 86 +++ apps/mobile/modules/kin-approval-key/index.ts | 111 ++++ .../ios/ConfirmationSheet.swift | 176 ++++++ .../ios/KinApprovalKey.podspec | 13 + .../ios/KinApprovalKeyModule.swift | 339 ++++++++++ .../kin-approval-key/ios/KinGrant.swift | 430 +++++++++++++ .../kin-approval-key/src/derSignature.test.ts | 216 +++++++ .../kin-approval-key/src/derSignature.ts | 74 +++ .../kin-approval-key/src/grantVectors.test.ts | 23 + .../kin-approval-key/src/publicJwk.test.ts | 83 +++ .../modules/kin-approval-key/src/publicJwk.ts | 57 ++ .../test/native/java/KinGrantVectors.java | 32 + .../kin-approval-key/test/native/run.sh | 23 + .../test/native/swift/main.swift | 22 + apps/mobile/plugins/withKinApprovalKey.cjs | 12 + docs/kin/specs/approvals.md | 30 +- docs/kin/specs/mobile.md | 2 +- knip.jsonc | 2 + 28 files changed, 3302 insertions(+), 11 deletions(-) create mode 100644 apps/mobile/modules/kin-approval-key/README.md create mode 100644 apps/mobile/modules/kin-approval-key/android/build.gradle create mode 100644 apps/mobile/modules/kin-approval-key/android/src/main/AndroidManifest.xml create mode 100644 apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/ApprovalKeyStore.kt create mode 100644 apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinApprovalKeyModule.kt create mode 100644 apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java create mode 100644 apps/mobile/modules/kin-approval-key/expo-module.config.json create mode 100644 apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json create mode 100644 apps/mobile/modules/kin-approval-key/index.test.ts create mode 100644 apps/mobile/modules/kin-approval-key/index.ts create mode 100644 apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift create mode 100644 apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec create mode 100644 apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift create mode 100644 apps/mobile/modules/kin-approval-key/ios/KinGrant.swift create mode 100644 apps/mobile/modules/kin-approval-key/src/derSignature.test.ts create mode 100644 apps/mobile/modules/kin-approval-key/src/derSignature.ts create mode 100644 apps/mobile/modules/kin-approval-key/src/grantVectors.test.ts create mode 100644 apps/mobile/modules/kin-approval-key/src/publicJwk.test.ts create mode 100644 apps/mobile/modules/kin-approval-key/src/publicJwk.ts create mode 100644 apps/mobile/modules/kin-approval-key/test/native/java/KinGrantVectors.java create mode 100755 apps/mobile/modules/kin-approval-key/test/native/run.sh create mode 100644 apps/mobile/modules/kin-approval-key/test/native/swift/main.swift create mode 100644 apps/mobile/plugins/withKinApprovalKey.cjs diff --git a/apps/mobile/.swiftlint.yml b/apps/mobile/.swiftlint.yml index 2dd29c067dc48..2fa7dbb27cf68 100644 --- a/apps/mobile/.swiftlint.yml +++ b/apps/mobile/.swiftlint.yml @@ -5,6 +5,7 @@ included: - modules/t3-terminal/ios - modules/t3-review-diff/ios - modules/t3-voice-transcription/ios + - modules/kin-approval-key/ios excluded: - ios/Pods diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 97eb9b0cadcab..7b25a0daa54b0 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -454,6 +454,7 @@ const config: ExpoConfig = { "./plugins/withAndroidModernAlertDialog.cjs", "./plugins/withAndroidPredictiveBackCompat.cjs", "./plugins/withAndroidTabletOrientation.cjs", + "./plugins/withKinApprovalKey.cjs", ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []), ], extra: { diff --git a/apps/mobile/modules/kin-approval-key/README.md b/apps/mobile/modules/kin-approval-key/README.md new file mode 100644 index 0000000000000..b123bcb99a1e6 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/README.md @@ -0,0 +1,160 @@ +# kin-approval-key + +The owner's approval key: a P-256 key in the Secure Enclave (iOS) or Android Keystore that signs Kin grants (`docs/kin/specs/approvals.md`, sections 4 and 5). Every signature needs Face ID, Touch ID or a strong biometric. The private key never leaves the hardware, and there is no software fallback. + +This key only signs grants. It is separate from the relay DPoP key in `src/features/cloud/dpop.ts`. + +## API (`index.ts`) + +| Call | Result | +| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `createKey(attestationChallenge)` | `{ publicJwk, hardware, attestation? }`. `attestationChallenge` is the server's registration nonce, unpadded base64url of 16 to 128 bytes. On Android, `attestation.certificateChain` is the Keystore chain (leaf first, base64 DER) with the nonce bound in; iOS has no attestation. Fails with `E_KEY_EXISTS` if a key is already there. | +| `sign(signingInput)` | `signingInput` is a grant's JWS signing input, `b64url(header).b64url(payload)`. The module refuses it unless it is a well-formed grant, shows the user what it approves, takes a biometric, and signs the ASCII bytes with ES256. Returns the 64-byte low-S `r‖s` as base64url, the JWS's third part. | +| `hasKey()` | Whether a key exists. This never prompts. See the device tests for what it returns after invalidation. | +| `deleteKey()` | Removes the key. Does nothing if there isn't one. | + +### What the user sees + +The caller doesn't choose the approval text. `ios/KinGrant.swift` and `android/.../KinGrant.java` parse the signing input natively and accept only canonical `stableStringify` JSON with the exact `KinGrant` header and fields (spec section 5), `approver.kid` equal to the header `kid`, an `iat` within 300 seconds of the device clock, and a kind that has a template. The text comes from a fixed template per kind: + +| Kind | Text | +| ----------------------- | ---------------------------------------------------------------------------------------------- | +| `merge_pull_request` | Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing, then delete its branch | +| `delete_branch` | Delete branch "kin/fix-212" (a1b2c3d4e5f60718) in GLDRoger/t3code | +| `set_level` | Set lead "tech-lead" to L2 in chat "chat_7" (or "in all chats") | +| `change_rules` | Change rules to "rules.md" (sha256 9f86d081884c7d65) | +| `memory_purge` | Purge memory using "purge/item-4.json" (sha256 9f86d081884c7d65) | +| `register_approver_key` | Add approver key NzbLsXh8uDCcd-6M | + +Every hash shows its first 16 characters. A shown value is never cleaned or cut: the grant is refused (`E_NOT_A_GRANT`) unless each value is ASCII from its field's allowlist, so nothing invisible, look-alike or reordering reaches the prompt and no platform Unicode table is involved: + +- Repo: GitHub's `owner/name` rules (owner: letters, digits, `-`, up to 39; name: letters, digits, `. _ -`, up to 100). +- Branches (`base`, `ref`) and `path`: letters, digits and `. _ - / +`. That is a subset of what git allows, so a merge into a branch with other characters (non-ASCII, `@`, `#` and so on) can't be approved from the phone. +- `leadId`, `chatId`: letters, digits and `. _ -`. + +None of these allow a space or a quote, so the quotes around a value in the template can't be faked. A prompt over 200 characters is refused, so the merge method and ", then delete its branch" always show. + +A new action kind needs a template in both parsers and new rows in `fixtures/grant-vectors.json`. The two parsers must agree; `test/native/run.sh` checks both against the vectors on a Mac with the Xcode command line tools and a JDK (no simulator or Android SDK). `src/grantVectors.test.ts` checks in CI that the accepted vectors are exactly what `stableStringify` writes. + +The Android parser is Java rather than Kotlin so it compiles and runs with a plain JDK. + +### Errors + +The native side returns DER signatures. `src/derSignature.ts` converts them to compact low-S form and rejects anything that isn't canonical DER. + +Error codes on rejected promises: + +- `E_NOT_A_GRANT`: the signing input isn't a well-formed grant the module can describe. +- `E_BUSY`: another `sign` call hasn't settled yet. One signature at a time, on both platforms. +- `E_NO_SECURE_HARDWARE`: no Secure Enclave, or the Keystore says the key or its auth gate isn't in secure hardware. +- `E_UNSUPPORTED_OS`: Android before 11. Per-use `AUTH_BIOMETRIC_STRONG` keys need API 30. +- `E_BIOMETRY_UNAVAILABLE`: no strong biometric enrolled, or no passcode. +- `E_BIOMETRY_LOCKOUT`: too many failed attempts. +- `E_KEY_EXISTS`, `E_KEY_NOT_FOUND`. +- `E_KEY_INVALIDATED`: biometric enrolment changed since the key was made. See iOS below. +- `E_USER_CANCELED`: the user canceled, chose the fallback, or the app left the foreground mid-approval. +- `E_AUTH_FAILED`: the biometric didn't unlock the key. +- `E_NO_ACTIVITY`: the app isn't in the foreground or the device is locked, so nothing can be shown. +- `E_OBSCURED` (Face ID): Approve was tapped while something could cover the confirmation sheet: its window wasn't key, another window was at its level or above, or a view or screen was on top of it. Nothing is signed. +- `E_INVALID_INPUT`, `E_KEYCHAIN`, `E_KEYSTORE`. + +## Platform notes + +- **iOS:** the key is created with `SecKeyCreateRandomKey` and `kSecAttrTokenIDSecureEnclave`, gated by `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` with `[.privateKeyUsage, .biometryCurrentSet]`. It signs with `.ecdsaSignatureMessageX962SHA256` on the module's own `kin.approval-key` queue, so an open prompt never blocks Expo's shared queue. The queue is concurrent on purpose: `SecKeyCreateSignature` blocks its thread while Face ID is up, and a serial queue would hold a second call until the first finished and then show a second prompt, instead of rejecting it with `E_BUSY`. Each signature uses a fresh `LAContext` with `localizedFallbackTitle = ""`, so no earlier match is reused and there is no "Enter Password" button. `NSFaceIDUsageDescription` comes from `plugins/withKinApprovalKey.cjs`. +- **iOS confirmation sheet (Face ID, Optic ID):** `ios/ConfirmationSheet.swift` shows the grant text in a window the module owns, at `windowLevel = .alert + 1` in the foreground scene, so views the app's JS can add to its own window (a `FullWindowOverlay`, a modal) sit below it. It ends editing first, since a keyboard's input accessory view would sit above every app window. When Approve is tapped, it signs only if the sheet's window is key and visible, no other visible window in the scene is at its level or above, and nothing has been added or presented over the card; otherwise `E_OBSCURED`. The window is removed on every outcome. Cancel, the sheet disappearing without a choice, or the scene going to the background reject with `E_USER_CANCELED`. +- **iOS re-enrolment:** `createKey` stores `LAContext.domainState.biometry.stateHash` in the keychain (this device only, never exported). A failed signature reports `E_KEY_INVALIDATED` rather than `E_AUTH_FAILED` when the stored hash differs from the current one. A mismatch alone never blocks signing, because Apple warns the hash can change across major OS versions with no enrolment change; after a successful signature, the stored hash is refreshed. +- **Android:** an EC `secp256r1` key with `PURPOSE_SIGN` and `DIGEST_SHA256`, `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)` and `setInvalidatedByBiometricEnrollment(true)`. It tries StrongBox first and falls back to the TEE only on a `ProviderException` (which includes `StrongBoxUnavailableException`). After creation it checks `KeyInfo`: secure hardware, strong-biometric-only, per-use, invalidated by enrolment. Parsing and `Signature.initSign` run off the main thread; `BiometricPrompt` runs on it with a `CryptoObject(Signature)`, and the callback signs only if it gets back that exact `Signature`. The prompt is canceled if the activity stops, and after 300 seconds (the grant would be stale to the server by then). +- **Android limitation:** `androidx.biometric` keeps one callback per activity, so a second `BiometricPrompt` made on the same activity while ours is open (by other code in the app) replaces our callback, and there's no public API to notice. Our call then settles only when the activity stops or the 300-second timeout fires, and until then `sign` returns `E_BUSY`. It can never sign the other prompt's operation, because the callback signs only its own `Signature`. Canceling on timeout can close the other prompt too. The module depends on `androidx.biometric:biometric:1.1.0`, the latest stable release. + +## Device tests (security test 22) + +These can't run in a simulator or emulator, because neither has a Secure Enclave or a real biometric sensor. Run them on one iPhone with Face ID, one with Touch ID if available, and one Pixel with StrongBox, each on a development build of this checkout (`vp run mobile:install `). Drive the calls from a debug screen or the Metro console with `import * as ApprovalKey from "../modules/kin-approval-key"`. Before each run, call `deleteKey()` and set up biometrics. + +Build signing inputs with the server's encoder, from `packages/shared`: + +```sh +node --experimental-strip-types --input-type=module -e ' +import { stableStringify } from "./src/relaySigning.ts"; +const b = (o) => Buffer.from(stableStringify(o)).toString("base64url"); +const now = Math.floor(Date.now() / 1000); +const header = { alg: "ES256", kid: "test", typ: "kin-grant+jws" }; +const payload = { v: 1, orgId: "org", actionId: "act_test", revision: 0, nonce: "n", jti: crypto.randomUUID(), + kind: "merge_pull_request", targetDigest: "0".repeat(64), headSha: "a1b2c3d".padEnd(40, "0"), base: "main", + mergeMethod: "squash", target: { _tag: "pull_request", host: "github.com", repo: "GLDRoger/t3code", number: 212, + mergeMethod: "squash", deleteBranchAfter: false }, approver: { humanId: "h", kid: "test" }, decision: "approve", + iat: now, exp: now + 600 }; +console.log(`${b(header)}.${b(payload)}`); +' +``` + +`iat` must be within 300 seconds of the phone's clock, so make a fresh input for each run. + +### 1. Signing without biometrics fails + +1. Call `createKey()`. Check that `hardware` is `secure_enclave` on iOS and `strongbox` on the Pixel (`tee` if StrongBox is unavailable). On Android, check that `attestation.certificateChain` has at least 2 entries. +2. Call `sign()`. **The prompt shows `Merge GLDRoger/t3code #212 (a1b2c3d000000000) into "main" by squashing`**: in the confirmation sheet on Face ID, in the system prompt on Touch ID and Android. Pass the biometric check. It resolves to an 86-character base64url string (64 bytes). +3. Call `sign` again and **cancel** the prompt (and, on Face ID, the sheet). It rejects with `E_USER_CANCELED`. +4. Call `sign` again and fail the biometric 5 times (cover the camera, or use an unenrolled finger). It rejects with `E_AUTH_FAILED` or `E_BIOMETRY_LOCKOUT`, and never resolves. +5. While locked out, unlock the phone with the passcode or PIN, then call `sign` and fail the biometric once more. The passcode or PIN never produces a signature: there is no "Enter Password" or "Use PIN" option on the prompt. +6. Call `sign` twice in a row. **Each call shows a prompt.** A match from the first call is never reused. +7. With biometrics turned off for the app (iOS: Settings → Face ID & Passcode → Other Apps; Android: remove all fingerprints), `sign` rejects with `E_BIOMETRY_UNAVAILABLE` or `E_AUTH_FAILED`. +8. On an Android phone whose only biometric is face unlock that isn't Class 3, `createKey` and `sign` reject with `E_BIOMETRY_UNAVAILABLE`. +9. Call `sign` with any other bytes, for example `b64url("test").b64url("{}")`, and with the input from step 2 with `typ` changed, a field added, or `base` set to `"ma\u00a0in"`. Each rejects with `E_NOT_A_GRANT` before any prompt. +10. Make an input whose prompt is exactly 200 characters (step 2 with `mergeMethod: "merge"`, `deleteBranchAfter: true` and `base` of 103 `x`). The whole text, ending ", then delete its branch", shows without truncation in the sheet, the Touch ID prompt and `BiometricPrompt`. With 104 `x`, it rejects with `E_NOT_A_GRANT`. + +### 2. One signature at a time + +1. Call `sign(inputA)` and, while its prompt is up, `sign(inputB)` with a different `number`. The second rejects at once with `E_BUSY`, and only one prompt is ever shown. Approve it: the first resolves, and its signature verifies for `inputA` only (section 4 below), never for `inputB`. +2. Call `sign` and send the app to the background while the prompt (or the Face ID sheet) is up. It rejects with `E_USER_CANCELED`. Bring the app back: no prompt is left, the promise never resolves later, and the next `sign` works (it doesn't get `E_BUSY`). +3. Call `sign` from a timer while the app is in the background, and again while the phone is locked. Both reject (`E_NO_ACTIVITY` expected) without showing a prompt or signing. +4. Android: call `sign` and, while its prompt is up, start a second `BiometricPrompt` on the activity (for example `expo-local-authentication`'s `authenticateAsync`). Pass that one. Our call doesn't resolve; it rejects with `E_USER_CANCELED` when the app goes to the background or 300 seconds after the prompt opened, and the next `sign` works. + +### 2a. An overlay over the sheet can't approve (Face ID) + +1. Render a `FullWindowOverlay` (react-native-screens) with `pointerEvents="none"` and an opaque box over the middle of the screen, then call `sign`. The sheet shows above the box, its text readable. Approve signs. +2. Mount the same overlay from a timer 2 seconds after calling `sign`, while the sheet is up. It still appears below the sheet. Approve signs. +3. While the sheet is up, focus a `TextInput` that has an `InputAccessoryView` with an opaque box, from a timer. If the keyboard or its accessory comes up over the sheet, Approve rejects with `E_OBSCURED` and nothing is signed. +4. While the sheet is up, call `Alert.alert` from a timer. Dismiss that alert, then tap Approve: it signs, and only the grant's text was ever on the sheet. +5. Type in a `TextInput` and leave the keyboard open, then call `sign`. The keyboard closes, the sheet shows, and Approve signs (no `E_OBSCURED`). Repeat after the keyboard has been dismissed. + +### 3. Re-enrolling biometrics invalidates the key + +1. Call `createKey`, then `sign` once to confirm it works. +2. iOS: add an alternate appearance (Face ID) or another finger (Touch ID). Android: add another fingerprint. +3. Call `hasKey()` and record the result. Then call `sign`. It **must reject**: `E_KEY_INVALIDATED` on both platforms. Record whether iOS showed Face ID first, and the exact error. +4. Remove the added enrolment and call `sign` again. It must still fail, because invalidation is permanent. +5. `deleteKey()`, then `createKey`, then `sign` works again. +6. Remove the device passcode (iOS) or screen lock (Android). iOS deletes the key: record what `hasKey()` and `sign` return. Android: `sign` rejects with `E_KEY_INVALIDATED`. Restore the lock, `deleteKey()`, `createKey`. + +### 4. DER signatures convert to compact and verify on the server + +1. Call `createKey` and copy `publicJwk`. +2. Make a signing input as above, call `sign(signingInput)` and copy the result. +3. On a computer, from `packages/shared` (it has both `@noble` packages): + + ```sh + node -e ' + const { p256 } = require("@noble/curves/nist"); + const { sha256 } = require("@noble/hashes/sha2"); + const [jwk, input, sig] = [JSON.parse(process.argv[1]), process.argv[2], process.argv[3]]; + const b = (s) => Buffer.from(s, "base64url"); + const key = Buffer.concat([Buffer.from([4]), b(jwk.x), b(jwk.y)]); + console.log(p256.verify(b(sig), sha256(Buffer.from(input)), key, { prehash: false, format: "compact", lowS: true })); + ' '' '' '' + ``` + + It prints `true`. Change one character of the signing input and it prints `false`. + +4. Repeat steps 2 and 3 twenty times on each device. Roughly half the raw signatures have a high-bit `r` or `s` (a 33-byte DER INTEGER) and half have a high `s`, so this covers the sign-byte and low-S paths on real hardware. + +### 5. Attestation (Android) + +1. Call `createKey()` with a recorded 32-byte nonce and save `attestation.certificateChain`. +2. Check it offline: the root is a Google hardware attestation root; the leaf's public key equals `publicJwk`; the KeyDescription's `attestationChallenge` is the nonce; the attestation and KeyMint security levels are `StrongBox` on the Pixel (`TrustedEnvironment` on TEE devices); `hardwareEnforced` has purpose `SIGN`, EC P-256, SHA-256, a biometric `userAuthType`, and no `authTimeout` or `noAuthRequired`. Record the tool and its output. + +### 6. Reinstall and restore + +1. iOS: with a key present, delete the app and reinstall it. Record what `hasKey()` returns and whether `createKey` fails with `E_KEY_EXISTS` (the keychain can outlive the app), and whether `sign` still works. +2. Restore a backup of a phone with a key onto a new device. `hasKey()` is `false` on both platforms (`ThisDeviceOnly`; Keystore keys aren't backed up), and `createKey` works. + +Record the date, device, OS version and result of each step in the APPR-6 PR. diff --git a/apps/mobile/modules/kin-approval-key/android/build.gradle b/apps/mobile/modules/kin-approval-key/android/build.gradle new file mode 100644 index 0000000000000..82d56e7b2e204 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/android/build.gradle @@ -0,0 +1,21 @@ +apply plugin: 'com.android.library' +apply plugin: 'org.jetbrains.kotlin.android' + +group = 'com.t3tools.kinapprovalkey' +version = '0.0.0' + +android { + namespace 'expo.modules.kinapprovalkey' + compileSdk rootProject.ext.compileSdkVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + } +} + +dependencies { + implementation project(':expo-modules-core') + // 1.1.0 is the latest stable release; 1.4.0 is still in beta. + implementation 'androidx.biometric:biometric:1.1.0' +} diff --git a/apps/mobile/modules/kin-approval-key/android/src/main/AndroidManifest.xml b/apps/mobile/modules/kin-approval-key/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000..a75be93d226b8 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/ApprovalKeyStore.kt b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/ApprovalKeyStore.kt new file mode 100644 index 0000000000000..09410702bfef8 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/ApprovalKeyStore.kt @@ -0,0 +1,160 @@ +package expo.modules.kinapprovalkey + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyInfo +import android.security.keystore.KeyPermanentlyInvalidatedException +import android.security.keystore.KeyProperties +import android.util.Base64 +import androidx.annotation.RequiresApi +import java.security.KeyFactory +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.PrivateKey +import java.security.ProviderException +import java.security.Signature +import java.security.spec.ECGenParameterSpec + +private const val KEYSTORE = "AndroidKeyStore" + +// One approval key per install. It only ever signs Kin grants, never connections. +private const val ALIAS = "kin.approval-key.v1" +private const val MIN_CHALLENGE_BYTES = 16 +private const val MAX_CHALLENGE_BYTES = 128 + +internal object ApprovalKeyStore { + private fun keyStore(): KeyStore = KeyStore.getInstance(KEYSTORE).apply { load(null) } + + fun has(): Boolean = keyStore().containsAlias(ALIAS) + + fun delete() { + val store = keyStore() + if (store.containsAlias(ALIAS)) store.deleteEntry(ALIAS) + } + + fun create(context: Context, attestationChallenge: ByteArray): Map { + // setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG) is API 30+; older devices get no key. + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { + throw ApprovalKeyException(E_UNSUPPORTED_OS, "Approval keys need Android 11 or later.") + } + // The server's registration nonce. KeyMint refuses challenges over 128 bytes. + if (attestationChallenge.size !in MIN_CHALLENGE_BYTES..MAX_CHALLENGE_BYTES) { + throw ApprovalKeyException(E_INVALID_INPUT, "attestationChallenge must be 16 to 128 bytes.") + } + return createOnR(context, attestationChallenge) + } + + @RequiresApi(Build.VERSION_CODES.R) + @Suppress("TooGenericExceptionCaught") // Never leave behind a key that failed its checks. + private fun createOnR(context: Context, challenge: ByteArray): Map { + if (has()) throw ApprovalKeyException(E_KEY_EXISTS, "An approval key already exists; delete it first.") + val hasStrongBox = context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE) + // StrongBoxUnavailableException is a ProviderException, and some StrongBox chips throw the plain + // one for keys they can't make. Only those fall back to the TEE; anything else fails closed. + val inStrongBox = hasStrongBox && try { + generate(challenge, strongBox = true) + true + } catch (_: ProviderException) { + delete() + false + } + if (!inStrongBox) generate(challenge, strongBox = false) + try { + return describe(inStrongBox) + } catch (error: Throwable) { + delete() + throw error + } + } + + @RequiresApi(Build.VERSION_CODES.R) + private fun describe(inStrongBox: Boolean): Map { + val store = keyStore() + val hardware = hardwareLevel(store.getKey(ALIAS, null) as PrivateKey, inStrongBox) + val chain = store.getCertificateChain(ALIAS) + ?: throw ApprovalKeyException(E_KEYSTORE, "The approval key has no attestation chain.") + return mapOf( + "publicKey" to encodeBase64Url(chain.first().publicKey.encoded), + "hardware" to hardware, + "attestationChain" to chain.map { Base64.encodeToString(it.encoded, Base64.NO_WRAP) } + ) + } + + fun initSignature(): Signature { + val key = keyStore().getKey(ALIAS, null) as? PrivateKey + ?: throw ApprovalKeyException(E_KEY_NOT_FOUND, "There is no approval key on this device.") + return try { + Signature.getInstance("SHA256withECDSA").apply { initSign(key) } + } catch (error: KeyPermanentlyInvalidatedException) { + throw ApprovalKeyException( + E_KEY_INVALIDATED, + "Biometric enrolment changed, so the approval key no longer works. Delete it and register a new one.", + error + ) + } + } + + @RequiresApi(Build.VERSION_CODES.R) + private fun generate(challenge: ByteArray, strongBox: Boolean) { + val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_SIGN) + .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1")) + .setDigests(KeyProperties.DIGEST_SHA256) + .setUserAuthenticationRequired(true) + .setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG) + .setInvalidatedByBiometricEnrollment(true) + .setAttestationChallenge(challenge) + .setIsStrongBoxBacked(strongBox) + .build() + KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE).apply { + initialize(spec) + generateKeyPair() + } + } + + // Refuses keys the OS reports as software-backed, or whose biometric gate isn't the per-use, + // strong-biometric-only, hardware-enforced one generate() asked for. + @RequiresApi(Build.VERSION_CODES.R) + private fun hardwareLevel(key: PrivateKey, inStrongBox: Boolean): String { + val info = KeyFactory.getInstance(key.algorithm, KEYSTORE).getKeySpec(key, KeyInfo::class.java) + // KeyInfo documents -1 for "every use"; 0 is what was requested. Either means per-use. + val gated = info.isUserAuthenticationRequired && + info.userAuthenticationType == KeyProperties.AUTH_BIOMETRIC_STRONG && + info.userAuthenticationValidityDurationSeconds <= 0 && + info.isInvalidatedByBiometricEnrollment + if (!gated) { + throw ApprovalKeyException(E_KEYSTORE, "The approval key's biometric gate isn't the one requested.") + } + val secure = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + info.securityLevel != KeyProperties.SECURITY_LEVEL_SOFTWARE && + info.securityLevel != KeyProperties.SECURITY_LEVEL_UNKNOWN + } else { + @Suppress("DEPRECATION") + info.isInsideSecureHardware + } + if (!secure || !info.isUserAuthenticationRequirementEnforcedBySecureHardware) { + throw ApprovalKeyException(E_NO_SECURE_HARDWARE, "This device can't keep the approval key in secure hardware.") + } + // Advisory only: the server takes `hardware` from the attestation (approvals spec, section 4). + val strongBoxLevel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX + } else { + inStrongBox + } + return if (strongBoxLevel) "strongbox" else "tee" + } +} + +internal fun decodeBase64Url(value: String): ByteArray { + val alphabet = value.all { (it in 'A'..'Z') || (it in 'a'..'z') || (it in '0'..'9') || it == '-' || it == '_' } + val decoded = if (value.isNotEmpty() && alphabet) { + runCatching { Base64.decode(value, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP) }.getOrNull() + } else { + null + } + return decoded ?: throw ApprovalKeyException(E_INVALID_INPUT, "Input is not base64url.") +} + +internal fun encodeBase64Url(bytes: ByteArray): String = + Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP) diff --git a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinApprovalKeyModule.kt b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinApprovalKeyModule.kt new file mode 100644 index 0000000000000..45f47f3eb23a3 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinApprovalKeyModule.kt @@ -0,0 +1,215 @@ +package expo.modules.kinapprovalkey + +import android.app.Activity +import android.os.Handler +import android.os.Looper +import androidx.biometric.BiometricManager +import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG +import androidx.biometric.BiometricPrompt +import androidx.core.content.ContextCompat +import androidx.fragment.app.FragmentActivity +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import expo.modules.kotlin.Promise +import expo.modules.kotlin.exception.CodedException +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition +import java.security.Signature +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean + +class KinApprovalKeyModule : Module() { + override fun definition() = ModuleDefinition { + Name("KinApprovalKey") + + AsyncFunction("createKey") { attestationChallenge: String -> + val context = appContext.reactContext ?: throw ApprovalKeyException(E_NO_ACTIVITY, "The app is not active.") + requireStrongBiometrics(BiometricManager.from(context)) + ApprovalKeyStore.create(context, decodeBase64Url(attestationChallenge)) + } + + // Runs on the modules queue, so parsing and Keystore work stay off the main thread. + AsyncFunction("signDer") { signingInput: String, promise: Promise -> + SignRequest.start(appContext.currentActivity, signingInput, promise) + } + + AsyncFunction("hasKey") { ApprovalKeyStore.has() } + + AsyncFunction("deleteKey") { ApprovalKeyStore.delete() } + } +} + +/** One `sign` call. Only one may be in flight; every path settles its promise exactly once. */ +private class SignRequest private constructor(private val promise: Promise) { + private val settled = AtomicBoolean(false) + + @Volatile private var cleanup: (() -> Unit)? = null + + companion object { + private val busy = AtomicBoolean(false) + private val signer = Executors.newSingleThreadExecutor() + + fun start(activity: Activity?, signingInput: String, promise: Promise) { + if (!busy.compareAndSet(false, true)) { + promise.reject(ApprovalKeyException(E_BUSY, "Another approval is already waiting for the user.")) + return + } + SignRequest(promise).prepare(activity, signingInput) + } + } + + @Suppress("TooGenericExceptionCaught") // Every failure must settle the promise and free the gate. + private fun prepare(activity: Activity?, signingInput: String) { + try { + val prompt = try { + KinGrant.prompt(signingInput, System.currentTimeMillis() / MILLIS_PER_SECOND) + } catch (error: KinGrant.NotAGrantException) { + throw ApprovalKeyException(E_NOT_A_GRANT, "Only Kin grants can be signed: ${error.message}.", error) + } + val host = activity as? FragmentActivity + ?: throw ApprovalKeyException(E_NO_ACTIVITY, "No foreground activity to show the prompt in.") + requireStrongBiometrics(BiometricManager.from(host)) + val signature = ApprovalKeyStore.initSignature() + // KinGrant accepted it, so it is two base64url segments: plain ASCII. + val message = signingInput.toByteArray(Charsets.US_ASCII) + ContextCompat.getMainExecutor(host).execute { show(host, prompt, signature, message) } + } catch (error: Throwable) { + reject(error) + } + } + + @Suppress("TooGenericExceptionCaught") + private fun show(activity: FragmentActivity, prompt: String, signature: Signature, message: ByteArray) { + try { + val foreground = activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED) + // BiometricPrompt.authenticate silently does nothing once state is saved. + if (!foreground || activity.supportFragmentManager.isStateSaved) { + throw ApprovalKeyException(E_NO_ACTIVITY, "Approvals need the app in the foreground.") + } + val biometricPrompt = + BiometricPrompt(activity, ContextCompat.getMainExecutor(activity), callback(signature, message)) + // The system prompt can outlive the screen; an approval must not. + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_STOP) { + reject(ApprovalKeyException(E_USER_CANCELED, "The app left the foreground during approval.")) + biometricPrompt.cancelAuthentication() + } + } + activity.lifecycle.addObserver(observer) + // androidx.biometric keeps one callback per activity, so a later BiometricPrompt replaces ours + // and we'd never hear back. The grant is stale to the server after 300 s anyway. + val handler = Handler(Looper.getMainLooper()) + val timeout = Runnable { + reject(ApprovalKeyException(E_USER_CANCELED, "The approval timed out.")) + biometricPrompt.cancelAuthentication() + } + handler.postDelayed(timeout, PROMPT_TIMEOUT_MILLIS) + cleanup = { + handler.removeCallbacks(timeout) + ContextCompat.getMainExecutor(activity).execute { activity.lifecycle.removeObserver(observer) } + } + val info = BiometricPrompt.PromptInfo.Builder() + .setTitle("Confirm approval") + .setDescription(prompt) + .setAllowedAuthenticators(BIOMETRIC_STRONG) + .setNegativeButtonText(activity.getString(android.R.string.cancel)) + .setConfirmationRequired(true) + .build() + biometricPrompt.authenticate(info, BiometricPrompt.CryptoObject(signature)) + } catch (error: Throwable) { + reject(error) + } + } + + private fun callback(signature: Signature, message: ByteArray) = object : BiometricPrompt.AuthenticationCallback() { + override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { + // androidx.biometric keeps one callback and one CryptoObject per activity, so a prompt from + // elsewhere could hand this callback an operation that isn't ours. Only sign our own. + if (result.cryptoObject?.signature !== signature) { + reject(ApprovalKeyException(E_AUTH_FAILED, "The prompt unlocked a different operation.")) + return + } + if (settled.get()) return + signer.execute { signUnlocked(signature, message) } + } + + override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { + reject(authenticationError(errorCode, errString.toString())) + } + + // A non-matching finger keeps the prompt open; only the terminal callbacks settle the promise. + override fun onAuthenticationFailed() = Unit + } + + @Suppress("TooGenericExceptionCaught") + private fun signUnlocked(signature: Signature, message: ByteArray) { + try { + signature.update(message) + resolve(encodeBase64Url(signature.sign())) + } catch (error: Throwable) { + reject(ApprovalKeyException(E_KEYSTORE, "Signing failed.", error)) + } + } + + private fun resolve(value: String) { + if (finish()) promise.resolve(value) + } + + private fun reject(error: Throwable) { + if (!finish()) return + promise.reject(error as? CodedException ?: ApprovalKeyException(E_KEYSTORE, "Approval failed.", error)) + } + + private fun finish(): Boolean { + if (!settled.compareAndSet(false, true)) return false + busy.set(false) + cleanup?.invoke() + return true + } +} + +private const val MILLIS_PER_SECOND = 1000L +private const val PROMPT_TIMEOUT_MILLIS = 300_000L + +private fun requireStrongBiometrics(manager: BiometricManager) { + when (manager.canAuthenticate(BIOMETRIC_STRONG)) { + BiometricManager.BIOMETRIC_SUCCESS -> Unit + else -> throw ApprovalKeyException( + E_BIOMETRY_UNAVAILABLE, + "A strong biometric (fingerprint or face) must be enrolled to use the approval key." + ) + } +} + +private fun authenticationError(errorCode: Int, message: String): ApprovalKeyException { + val code = when (errorCode) { + BiometricPrompt.ERROR_USER_CANCELED, + BiometricPrompt.ERROR_NEGATIVE_BUTTON, + BiometricPrompt.ERROR_CANCELED -> E_USER_CANCELED + BiometricPrompt.ERROR_LOCKOUT, + BiometricPrompt.ERROR_LOCKOUT_PERMANENT -> E_BIOMETRY_LOCKOUT + BiometricPrompt.ERROR_NO_BIOMETRICS, + BiometricPrompt.ERROR_HW_NOT_PRESENT, + BiometricPrompt.ERROR_HW_UNAVAILABLE -> E_BIOMETRY_UNAVAILABLE + else -> E_AUTH_FAILED + } + return ApprovalKeyException(code, "Biometric prompt ended: $message ($errorCode).") +} + +internal const val E_NO_SECURE_HARDWARE = "E_NO_SECURE_HARDWARE" +internal const val E_UNSUPPORTED_OS = "E_UNSUPPORTED_OS" +internal const val E_BIOMETRY_UNAVAILABLE = "E_BIOMETRY_UNAVAILABLE" +internal const val E_BIOMETRY_LOCKOUT = "E_BIOMETRY_LOCKOUT" +internal const val E_KEY_EXISTS = "E_KEY_EXISTS" +internal const val E_KEY_NOT_FOUND = "E_KEY_NOT_FOUND" +internal const val E_KEY_INVALIDATED = "E_KEY_INVALIDATED" +internal const val E_USER_CANCELED = "E_USER_CANCELED" +internal const val E_AUTH_FAILED = "E_AUTH_FAILED" +internal const val E_BUSY = "E_BUSY" +internal const val E_NOT_A_GRANT = "E_NOT_A_GRANT" +internal const val E_NO_ACTIVITY = "E_NO_ACTIVITY" +internal const val E_INVALID_INPUT = "E_INVALID_INPUT" +internal const val E_KEYSTORE = "E_KEYSTORE" + +internal class ApprovalKeyException(code: String, message: String, cause: Throwable? = null) : + CodedException(code, message, cause) diff --git a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java new file mode 100644 index 0000000000000..8d699de7a7de4 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java @@ -0,0 +1,425 @@ +package expo.modules.kinapprovalkey; + +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Parses a KinGrant JWS signing input (docs/kin/specs/approvals.md, section 5) and builds the + * approval prompt from it. Pure JDK so it compiles and runs without an Android SDK; it must + * accept and reject exactly what ios/KinGrant.swift does (fixtures/grant-vectors.json). + */ +final class KinGrant { + static final class NotAGrantException extends Exception { + NotAGrantException(String reason) { + super(reason); + } + } + + private static final int MAX_SIGNING_INPUT = 8192; + private static final int MAX_DEPTH = 3; + private static final int MAX_PROMPT_CHARS = 200; + private static final int SHOWN_HASH_LENGTH = 16; + private static final long MAX_SAFE_INTEGER = 9007199254740991L; + private static final long MAX_LIFETIME_SECONDS = 900; + private static final long MAX_CLOCK_SKEW_SECONDS = 300; + + private static final Pattern SHA40 = Pattern.compile("[0-9a-f]{40}"); + private static final Pattern HEX64 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern REPO = Pattern.compile("[A-Za-z0-9-]{1,39}/[A-Za-z0-9._-]{1,100}"); + // What a shown value may contain. ASCII only, so no platform Unicode table is consulted and + // nothing invisible, confusable or reordering can reach the prompt; a quote can't occur. + /** Branch names and paths: letters, digits and {@code . _ - / +} (a subset of what git allows). */ + private static final Pattern NAME = Pattern.compile("[A-Za-z0-9._/+-]+"); + /** Lead and chat ids: letters, digits and {@code . _ -}. */ + private static final Pattern ID = Pattern.compile("[A-Za-z0-9._-]+"); + private static final Pattern THUMBPRINT = Pattern.compile("[A-Za-z0-9_-]{43}"); + + private static final Set PAYLOAD_REQUIRED = setOf( + "v", "orgId", "actionId", "revision", "nonce", "jti", "kind", "targetDigest", "target", + "approver", "decision", "iat", "exp"); + + private KinGrant() {} + + /** Returns the prompt text for a valid grant signing input, or throws NotAGrantException. */ + static String prompt(String signingInput, long nowSeconds) throws NotAGrantException { + if (signingInput.isEmpty() || signingInput.length() > MAX_SIGNING_INPUT) { + throw new NotAGrantException("signing input is empty or too long"); + } + int dot = signingInput.indexOf('.'); + if (dot < 0 || signingInput.indexOf('.', dot + 1) >= 0) { + throw new NotAGrantException("signing input is not header.payload"); + } + Map header = object(signingInput.substring(0, dot), "header"); + Map payload = object(signingInput.substring(dot + 1), "payload"); + checkHeader(header); + return promptFor(payload, (String) header.get("kid"), nowSeconds); + } + + private static Map object(String segment, String label) throws NotAGrantException { + String json = utf8(base64UrlDecode(segment, label), label); + Object value = new Parser(json).parseDocument(); + if (!(value instanceof Map)) throw new NotAGrantException(label + " is not an object"); + @SuppressWarnings("unchecked") + Map map = (Map) value; + return map; + } + + private static void checkHeader(Map header) throws NotAGrantException { + exactKeys(header, setOf("alg", "kid", "typ"), setOf(), "header"); + if (!"ES256".equals(header.get("alg"))) throw new NotAGrantException("alg is not ES256"); + if (!"kin-grant+jws".equals(header.get("typ"))) throw new NotAGrantException("typ is not kin-grant+jws"); + nonEmpty(header, "kid"); + } + + private static String promptFor(Map p, String kid, long now) throws NotAGrantException { + exactKeys(p, PAYLOAD_REQUIRED, setOf("headSha", "base", "mergeMethod"), "payload"); + if (integer(p, "v") != 1) throw new NotAGrantException("v is not 1"); + if (!"approve".equals(p.get("decision"))) throw new NotAGrantException("decision is not approve"); + for (String key : new String[] {"orgId", "actionId", "nonce", "jti"}) nonEmpty(p, key); + if (integer(p, "revision") < 0) throw new NotAGrantException("revision is negative"); + matches(p, "targetDigest", HEX64); + Map approver = child(p, "approver"); + exactKeys(approver, setOf("humanId", "kid"), setOf(), "approver"); + nonEmpty(approver, "humanId"); + if (!string(approver, "kid").equals(kid)) throw new NotAGrantException("approver.kid is not the header kid"); + + long iat = integer(p, "iat"); + long exp = integer(p, "exp"); + if (exp <= iat || exp - iat > MAX_LIFETIME_SECONDS) throw new NotAGrantException("exp is outside iat + 900"); + if (Math.abs(now - iat) > MAX_CLOCK_SKEW_SECONDS) throw new NotAGrantException("iat is not now"); + + Map target = child(p, "target"); + String kind = string(p, "kind"); + String text; + switch (kind) { + case "merge_pull_request": { + only(p, "headSha", "base", "mergeMethod"); + pullRequestTarget(target); + String method = string(p, "mergeMethod"); + if (!method.equals(target.get("mergeMethod"))) throw new NotAGrantException("mergeMethod differs from target"); + text = "Merge " + target.get("repo") + " #" + target.get("number") + " (" + headSha(p) + ") into \"" + + shown(p, "base", NAME) + "\" " + methodWords(method) + + (Boolean.TRUE.equals(target.get("deleteBranchAfter")) ? ", then delete its branch" : ""); + break; + } + case "delete_branch": { + only(p, "headSha"); + exactKeys(target, setOf("_tag", "host", "repo", "ref"), setOf(), "target"); + tag(target, "branch"); + githubRepo(target); + text = "Delete branch \"" + shown(target, "ref", NAME) + "\" (" + headSha(p) + ") in " + target.get("repo"); + break; + } + case "set_level": { + only(p); + exactKeys(target, setOf("_tag", "leadId", "level"), setOf("chatId"), "target"); + tag(target, "level"); + String level = string(target, "level"); + if (!level.matches("L[0-3]")) throw new NotAGrantException("level is not L0-L3"); + String chat = + target.containsKey("chatId") ? " in chat \"" + shown(target, "chatId", ID) + "\"" : " in all chats"; + text = "Set lead \"" + shown(target, "leadId", ID) + "\" to " + level + chat; + break; + } + case "change_rules": + case "memory_purge": { + only(p); + exactKeys(target, setOf("_tag", "path", "sha256"), setOf(), "target"); + tag(target, "content"); + String hash = matches(target, "sha256", HEX64).substring(0, SHOWN_HASH_LENGTH); + String path = shown(target, "path", NAME); + text = kind.equals("change_rules") + ? "Change rules to \"" + path + "\" (sha256 " + hash + ")" + : "Purge memory using \"" + path + "\" (sha256 " + hash + ")"; + break; + } + case "register_approver_key": { + only(p); + exactKeys(target, setOf("_tag", "thumbprint"), setOf(), "target"); + tag(target, "device_key"); + text = "Add approver key " + matches(target, "thumbprint", THUMBPRINT).substring(0, SHOWN_HASH_LENGTH); + break; + } + default: + throw new NotAGrantException("kind has no prompt template"); + } + // Refused rather than cut, so the fixed words after a long value always show. + if (text.length() > MAX_PROMPT_CHARS) throw new NotAGrantException("the prompt is over 200 characters"); + return text; + } + + private static void pullRequestTarget(Map target) throws NotAGrantException { + exactKeys(target, setOf("_tag", "host", "repo", "number", "mergeMethod", "deleteBranchAfter"), setOf(), "target"); + tag(target, "pull_request"); + githubRepo(target); + if (integer(target, "number") < 1) throw new NotAGrantException("number is not positive"); + if (!(target.get("deleteBranchAfter") instanceof Boolean)) { + throw new NotAGrantException("deleteBranchAfter is not a boolean"); + } + } + + private static void githubRepo(Map target) throws NotAGrantException { + if (!"github.com".equals(target.get("host"))) throw new NotAGrantException("host is not github.com"); + matches(target, "repo", REPO); + } + + private static String methodWords(String method) throws NotAGrantException { + switch (method) { + case "merge": + return "with a merge commit"; + case "squash": + return "by squashing"; + case "rebase": + return "by rebasing"; + default: + throw new NotAGrantException("mergeMethod is unknown"); + } + } + + private static String headSha(Map p) throws NotAGrantException { + return matches(p, "headSha", SHA40).substring(0, SHOWN_HASH_LENGTH); + } + + /** The optional payload fields allowed for this kind; any other optional field is refused. */ + private static void only(Map p, String... allowed) throws NotAGrantException { + Set allow = setOf(allowed); + for (String key : new String[] {"headSha", "base", "mergeMethod"}) { + if (p.containsKey(key) && !allow.contains(key)) throw new NotAGrantException(key + " is not allowed here"); + } + for (String key : allow) { + if (!p.containsKey(key)) throw new NotAGrantException(key + " is required"); + } + } + + private static void tag(Map target, String expected) throws NotAGrantException { + if (!expected.equals(target.get("_tag"))) throw new NotAGrantException("target is not " + expected); + } + + private static void exactKeys(Map map, Set required, Set optional, String label) + throws NotAGrantException { + for (String key : required) { + if (!map.containsKey(key)) throw new NotAGrantException(label + "." + key + " is missing"); + } + for (String key : map.keySet()) { + if (!required.contains(key) && !optional.contains(key)) { + throw new NotAGrantException(label + "." + key + " is not allowed"); + } + } + } + + private static String string(Map map, String key) throws NotAGrantException { + Object value = map.get(key); + if (!(value instanceof String)) throw new NotAGrantException(key + " is not a string"); + return (String) value; + } + + private static void nonEmpty(Map map, String key) throws NotAGrantException { + if (string(map, key).isEmpty()) throw new NotAGrantException(key + " is empty"); + } + + private static String matches(Map map, String key, Pattern pattern) throws NotAGrantException { + String value = string(map, key); + if (!pattern.matcher(value).matches()) throw new NotAGrantException(key + " is malformed"); + return value; + } + + private static long integer(Map map, String key) throws NotAGrantException { + Object value = map.get(key); + if (!(value instanceof Long)) throw new NotAGrantException(key + " is not an integer"); + return (Long) value; + } + + private static Map child(Map map, String key) throws NotAGrantException { + Object value = map.get(key); + if (!(value instanceof Map)) throw new NotAGrantException(key + " is not an object"); + @SuppressWarnings("unchecked") + Map child = (Map) value; + return child; + } + + /** A shown value, refused (never cleaned) if it is empty or has a character outside its allowlist. */ + private static String shown(Map map, String key, Pattern allowed) throws NotAGrantException { + String value = string(map, key); + if (!allowed.matcher(value).matches()) throw new NotAGrantException(key + " has a character that can't be shown"); + return value; + } + + private static Set setOf(String... values) { + return new HashSet<>(Arrays.asList(values)); + } + + private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + + /** Unpadded base64url with zero trailing bits, so every byte string has exactly one encoding. */ + static byte[] base64UrlDecode(String value, String label) throws NotAGrantException { + if (value.isEmpty() || value.length() % 4 == 1) throw new NotAGrantException(label + " is not base64url"); + byte[] out = new byte[value.length() * 3 / 4]; + int buffer = 0; + int bits = 0; + int index = 0; + for (int i = 0; i < value.length(); i++) { + int digit = ALPHABET.indexOf(value.charAt(i)); + if (digit < 0) throw new NotAGrantException(label + " is not base64url"); + buffer = (buffer << 6) | digit; + bits += 6; + if (bits >= 8) { + bits -= 8; + out[index++] = (byte) (buffer >> bits); + buffer &= (1 << bits) - 1; + } + } + if (buffer != 0) throw new NotAGrantException(label + " has non-zero trailing bits"); + return out; + } + + private static String utf8(byte[] bytes, String label) throws NotAGrantException { + try { + return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); + } catch (CharacterCodingException error) { + throw new NotAGrantException(label + " is not UTF-8"); + } + } + + /** + * Accepts only the canonical form stableStringify (packages/shared/src/relaySigning.ts) writes: + * no whitespace, keys in strictly increasing UTF-16 order (so no duplicates), JSON.stringify's + * string escapes, safe integers. Only objects, strings, integers and booleans occur in a grant. + */ + private static final class Parser { + private final String text; + private int at; + + Parser(String text) { + this.text = text; + } + + Object parseDocument() throws NotAGrantException { + Object value = parseValue(0); + if (at != text.length()) fail("trailing characters"); + return value; + } + + private Object parseValue(int depth) throws NotAGrantException { + if (at >= text.length()) fail("unexpected end"); + char c = text.charAt(at); + if (c == '{') return parseObject(depth); + if (c == '"') return parseString(); + if (c == '-' || (c >= '0' && c <= '9')) return parseInteger(); + if (text.startsWith("true", at)) { + at += 4; + return Boolean.TRUE; + } + if (text.startsWith("false", at)) { + at += 5; + return Boolean.FALSE; + } + fail("unsupported value"); + return null; + } + + private Map parseObject(int depth) throws NotAGrantException { + if (depth >= MAX_DEPTH) fail("nested too deep"); + at++; + Map map = new LinkedHashMap<>(); + if (peek('}')) { + at++; + return map; + } + String previous = null; + while (true) { + if (!peek('"')) fail("expected a key"); + String key = parseString(); + if (previous != null && previous.compareTo(key) >= 0) fail("keys are not in canonical order"); + previous = key; + expect(':'); + map.put(key, parseValue(depth + 1)); + if (peek(',')) { + at++; + continue; + } + expect('}'); + return map; + } + } + + private String parseString() throws NotAGrantException { + at++; + StringBuilder out = new StringBuilder(); + while (true) { + if (at >= text.length()) fail("unterminated string"); + char c = text.charAt(at++); + if (c == '"') return out.toString(); + if (c < 0x20) fail("raw control character"); + if (c != '\\') { + out.append(c); + continue; + } + if (at >= text.length()) fail("unterminated escape"); + char e = text.charAt(at++); + switch (e) { + case '"': out.append('"'); break; + case '\\': out.append('\\'); break; + case 'b': out.append('\b'); break; + case 'f': out.append('\f'); break; + case 'n': out.append('\n'); break; + case 'r': out.append('\r'); break; + case 't': out.append('\t'); break; + case 'u': out.append(parseControlEscape()); break; + default: fail("non-canonical escape"); + } + } + } + + // JSON.stringify only writes \\u for control characters without a short escape (and lone + // surrogates, which a grant never contains), always as lowercase \\u00xx. + private char parseControlEscape() throws NotAGrantException { + if (at + 4 > text.length() || !text.startsWith("00", at)) fail("non-canonical \\u escape"); + String hex = text.substring(at + 2, at + 4); + if (!hex.matches("[01][0-9a-f]")) fail("non-canonical \\u escape"); + char c = (char) Integer.parseInt(hex, 16); + if (c == '\b' || c == '\t' || c == '\n' || c == '\f' || c == '\r') fail("non-canonical \\u escape"); + at += 4; + return c; + } + + private Long parseInteger() throws NotAGrantException { + int start = at; + if (peek('-')) at++; + if (peek('0')) { + at++; + } else { + if (at >= text.length() || text.charAt(at) < '1' || text.charAt(at) > '9') fail("bad number"); + while (at < text.length() && text.charAt(at) >= '0' && text.charAt(at) <= '9') at++; + } + if (at < text.length() && (text.charAt(at) == '.' || text.charAt(at) == 'e' || text.charAt(at) == 'E')) { + fail("not an integer"); + } + String digits = text.substring(start, at); + if (digits.equals("-0")) fail("negative zero"); + if (digits.length() > 17) fail("integer out of range"); + long value = Long.parseLong(digits); + if (Math.abs(value) > MAX_SAFE_INTEGER) fail("integer out of range"); + return value; + } + + private boolean peek(char c) { + return at < text.length() && text.charAt(at) == c; + } + + private void expect(char c) throws NotAGrantException { + if (!peek(c)) fail("expected " + c); + at++; + } + + private void fail(String reason) throws NotAGrantException { + throw new NotAGrantException("not canonical JSON: " + reason); + } + } +} diff --git a/apps/mobile/modules/kin-approval-key/expo-module.config.json b/apps/mobile/modules/kin-approval-key/expo-module.config.json new file mode 100644 index 0000000000000..bb8fee6c9cb2c --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/expo-module.config.json @@ -0,0 +1,10 @@ +{ + "platforms": ["apple", "android"], + "apple": { + "modules": ["KinApprovalKeyModule"], + "podspecPath": "ios/KinApprovalKey.podspec" + }, + "android": { + "modules": ["expo.modules.kinapprovalkey.KinApprovalKeyModule"] + } +} diff --git a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json new file mode 100644 index 0000000000000..32efb28ed0a61 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json @@ -0,0 +1,586 @@ +{ + "now": 1798761600, + "cases": [ + { + "name": "merge by squashing", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + }, + { + "name": "merge commit, then delete the branch", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" with a merge commit, then delete its branch" + }, + { + "name": "rebase onto a base with . / + and _", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"release/v2.1+hotfix_x\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"rebase\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"rebase\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"release/v2.1+hotfix_x\" by rebasing" + }, + { + "name": "a non-ASCII base is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"release/ünï-2\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"rebase\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"rebase\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+0007 (control) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\u0007in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+0009 tab is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\tin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+000A newline is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\nin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+007F delete is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+00AD soft hyphen (format) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma­in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+200B zero-width space (format) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma​in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+202E right-to-left override (format) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma‮in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+2066 left-to-right isolate (format) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma⁦in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+FEFF byte order mark (format) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+0020 space is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+00A0 no-break space is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+3000 ideographic space is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+2028 line separator is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma
in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+3164 Hangul filler is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"maㅤin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+2800 braille blank is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma⠀in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+115F Hangul choseong filler is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"maᅟin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+0301 combining acute accent is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"máin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+05D0 Hebrew letter (right-to-left) is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"maאin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with U+0430 Cyrillic a, a Latin look-alike is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"maаin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with a double quote is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\\"in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field with a backslash is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\\\in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a 100-character branch is shown in full", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\" by squashing" + }, + { + "name": "a long repo and branch over 200 characters are refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"ooooooooooooooooooooooooooooooooooooooo/rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a prompt of exactly 200 characters keeps its fixed words", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" with a merge commit, then delete its branch" + }, + { + "name": "a prompt of 201 characters is refused, not cut", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":true,\"host\":\"github.com\",\"mergeMethod\":\"merge\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "delete a branch", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"delete_branch\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"branch\",\"host\":\"github.com\",\"ref\":\"kin/fix-212\",\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Delete branch \"kin/fix-212\" (a1b2c3d4e5f60718) in GLDRoger/t3code" + }, + { + "name": "set a level in one chat", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"chatId\":\"chat_7\",\"leadId\":\"tech-lead\",\"level\":\"L2\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Set lead \"tech-lead\" to L2 in chat \"chat_7\"" + }, + { + "name": "set a level everywhere", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"tech-lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Set lead \"tech-lead\" to L0 in all chats" + }, + { + "name": "change rules", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"change_rules\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"content\",\"path\":\"rules.md\",\"sha256\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Change rules to \"rules.md\" (sha256 9f86d081884c7d65)" + }, + { + "name": "purge memory", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"memory_purge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"content\",\"path\":\"purge/item-4.json\",\"sha256\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Purge memory using \"purge/item-4.json\" (sha256 9f86d081884c7d65)" + }, + { + "name": "register an approver key", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Add approver key NzbLsXh8uDCcd-6M" + }, + { + "name": "escapes decode in a field that isn't shown", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_\\\"q\\\\\\u0001\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + }, + { + "name": "iat 300 s behind the device clock", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798761600,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761300,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + }, + { + "name": "empty", + "signingInput": "", + "error": "E_NOT_A_GRANT" + }, + { + "name": "no dot", + "signingInput": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlkwWmtYVmM2ZU5meHYzeFZOSFpKcDF4N20za1FxYjJPOHM1dkIxYVdjOUUiLCJ0eXAiOiJraW4tZ3JhbnQrandzIn0", + "error": "E_NOT_A_GRANT" + }, + { + "name": "three segments", + "signingInput": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlkwWmtYVmM2ZU5meHYzeFZOSFpKcDF4N20za1FxYjJPOHM1dkIxYVdjOUUiLCJ0eXAiOiJraW4tZ3JhbnQrandzIn0.eyJhY3Rpb25JZCI6ImFjdF8wMUpEN1owMDAwMDAwMDAwMDAwMDAwMDAwIiwiYXBwcm92ZXIiOnsiaHVtYW5JZCI6Imhfb3duZXIiLCJraWQiOiJZMFprWFZjNmVOZnh2M3hWTkhaSnAxeDdtM2tRcWIyTzhzNXZCMWFXYzlFIn0sImJhc2UiOiJtYWluIiwiZGVjaXNpb24iOiJhcHByb3ZlIiwiZXhwIjoxNzk4NzYyMTkwLCJoZWFkU2hhIjoiYTFiMmMzZDRlNWY2MDcxODI5M2E0YjVjNmQ3ZThmOTAxMjM0NTY3OCIsImlhdCI6MTc5ODc2MTU5MCwianRpIjoiWkdWMmFXTmxMV3AwYVMweE5pMWkiLCJraW5kIjoibWVyZ2VfcHVsbF9yZXF1ZXN0IiwibWVyZ2VNZXRob2QiOiJzcXVhc2giLCJub25jZSI6ImMyVnlkbVZ5TFc1dmJtTmxMVE15TFdKNWRHVnpMV0poYzJVMk5IVnliQSIsIm9yZ0lkIjoib3JnXzAxIiwicmV2aXNpb24iOjIsInRhcmdldCI6eyJfdGFnIjoicHVsbF9yZXF1ZXN0IiwiZGVsZXRlQnJhbmNoQWZ0ZXIiOmZhbHNlLCJob3N0IjoiZ2l0aHViLmNvbSIsIm1lcmdlTWV0aG9kIjoic3F1YXNoIiwibnVtYmVyIjoyMTIsInJlcG8iOiJHTERSb2dlci90M2NvZGUifSwidGFyZ2V0RGlnZXN0IjoiOWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTViMGYwMGEwOCIsInYiOjF9.c2ln", + "error": "E_NOT_A_GRANT" + }, + { + "name": "padded segment", + "signingInput": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlkwWmtYVmM2ZU5meHYzeFZOSFpKcDF4N20za1FxYjJPOHM1dkIxYVdjOUUiLCJ0eXAiOiJraW4tZ3JhbnQrandzIn0.eyJhY3Rpb25JZCI6ImFjdF8wMUpEN1owMDAwMDAwMDAwMDAwMDAwMDAwIiwiYXBwcm92ZXIiOnsiaHVtYW5JZCI6Imhfb3duZXIiLCJraWQiOiJZMFprWFZjNmVOZnh2M3hWTkhaSnAxeDdtM2tRcWIyTzhzNXZCMWFXYzlFIn0sImJhc2UiOiJtYWluIiwiZGVjaXNpb24iOiJhcHByb3ZlIiwiZXhwIjoxNzk4NzYyMTkwLCJoZWFkU2hhIjoiYTFiMmMzZDRlNWY2MDcxODI5M2E0YjVjNmQ3ZThmOTAxMjM0NTY3OCIsImlhdCI6MTc5ODc2MTU5MCwianRpIjoiWkdWMmFXTmxMV3AwYVMweE5pMWkiLCJraW5kIjoibWVyZ2VfcHVsbF9yZXF1ZXN0IiwibWVyZ2VNZXRob2QiOiJzcXVhc2giLCJub25jZSI6ImMyVnlkbVZ5TFc1dmJtTmxMVE15TFdKNWRHVnpMV0poYzJVMk5IVnliQSIsIm9yZ0lkIjoib3JnXzAxIiwicmV2aXNpb24iOjIsInRhcmdldCI6eyJfdGFnIjoicHVsbF9yZXF1ZXN0IiwiZGVsZXRlQnJhbmNoQWZ0ZXIiOmZhbHNlLCJob3N0IjoiZ2l0aHViLmNvbSIsIm1lcmdlTWV0aG9kIjoic3F1YXNoIiwibnVtYmVyIjoyMTIsInJlcG8iOiJHTERSb2dlci90M2NvZGUifSwidGFyZ2V0RGlnZXN0IjoiOWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTViMGYwMGEwOCIsInYiOjF9eA==", + "error": "E_NOT_A_GRANT" + }, + { + "name": "standard base64 characters", + "signingInput": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlkwWmtYVmM2ZU5meHYzeFZOSFpKcDF4N20za1FxYjJPOHM1dkIxYVdjOUUiLCJ0eXAiOiJraW4tZ3JhbnQrandzIn0.eyJhY3Rpb25JZCI6ImFjdF8wMUpEN1owMDAwMDAwMDAwMDAwMDAwMDAwIiwiYXBwcm92ZXIiOnsiaHVtYW5JZCI6Imhfb3duZXIiLCJraWQiOiJZMFprWFZjNmVOZnh2M3hWTkhaSnAxeDdtM2tRcWIyTzhzNXZCMWFXYzlFIn0sImJhc2UiOiJtYWluIiwiZGVjaXNpb24iOiJhcHByb3ZlIiwiZXhwIjoxNzk4NzYyMTkwLCJoZWFkU2hhIjoiYTFiMmMzZDRlNWY2MDcxODI5M2E0YjVjNmQ3ZThmOTAxMjM0NTY3OCIsImlhdCI6MTc5ODc2MTU5MCwianRpIjoiWkdWMmFXTmxMV3AwYVMweE5pMWkiLCJraW5kIjoibWVyZ2VfcHVsbF9yZXF1ZXN0IiwibWVyZ2VNZXRob2QiOiJzcXVhc2giLCJub25jZSI6ImMyVnlkbVZ5TFc1dmJtTmxMVE15TFdKNWRHVnpMV0poYzJVMk5IVnliQSIsIm9yZ0lkIjoib3JnXzAxIiwicmV2aXNpb24iOjIsInRhcmdldCI6eyJfdGFnIjoicHVsbF9yZXF1ZXN0IiwiZGVsZXRlQnJhbmNoQWZ0ZXIiOmZhbHNlLCJob3N0IjoiZ2l0aHViLmNvbSIsIm1lcmdlTWV0aG9kIjoic3F1YXNoIiwibnVtYmVyIjoyMTIsInJlcG8iOiJHTERSb2dlci90M2NvZGUifSwidGFyZ2V0RGlnZXN0IjoiOWY4NmQwODE4ODRjN2Q2NTlhMmZlYWEwYzU1YWQwMTVhM2JmNGYxYjJiMGI4MjJjZDE1ZDZjMTViMGYwMGEwOCIsInYiOjF9+", + "error": "E_NOT_A_GRANT" + }, + { + "name": "control for the trailing-bits case", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"maina\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"maina\" by squashing" + }, + { + "name": "non-zero trailing bits", + "signingInput": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlkwWmtYVmM2ZU5meHYzeFZOSFpKcDF4N20za1FxYjJPOHM1dkIxYVdjOUUiLCJ0eXAiOiJraW4tZ3JhbnQrandzIn0.eyJhY3Rpb25JZCI6ImFjdF8wMUpEN1owMDAwMDAwMDAwMDAwMDAwMDAwIiwiYXBwcm92ZXIiOnsiaHVtYW5JZCI6Imhfb3duZXIiLCJraWQiOiJZMFprWFZjNmVOZnh2M3hWTkhaSnAxeDdtM2tRcWIyTzhzNXZCMWFXYzlFIn0sImJhc2UiOiJtYWluYSIsImRlY2lzaW9uIjoiYXBwcm92ZSIsImV4cCI6MTc5ODc2MjE5MCwiaGVhZFNoYSI6ImExYjJjM2Q0ZTVmNjA3MTgyOTNhNGI1YzZkN2U4ZjkwMTIzNDU2NzgiLCJpYXQiOjE3OTg3NjE1OTAsImp0aSI6IlpHVjJhV05sTFdwMGFTMHhOaTFpIiwia2luZCI6Im1lcmdlX3B1bGxfcmVxdWVzdCIsIm1lcmdlTWV0aG9kIjoic3F1YXNoIiwibm9uY2UiOiJjMlZ5ZG1WeUxXNXZibU5sTFRNeUxXSjVkR1Z6TFdKaGMyVTJOSFZ5YkEiLCJvcmdJZCI6Im9yZ18wMSIsInJldmlzaW9uIjoyLCJ0YXJnZXQiOnsiX3RhZyI6InB1bGxfcmVxdWVzdCIsImRlbGV0ZUJyYW5jaEFmdGVyIjpmYWxzZSwiaG9zdCI6ImdpdGh1Yi5jb20iLCJtZXJnZU1ldGhvZCI6InNxdWFzaCIsIm51bWJlciI6MjEyLCJyZXBvIjoiR0xEUm9nZXIvdDNjb2RlIn0sInRhcmdldERpZ2VzdCI6IjlmODZkMDgxODg0YzdkNjU5YTJmZWFhMGM1NWFkMDE1YTNiZjRmMWIyYjBiODIyY2QxNWQ2YzE1YjBmMDBhMDgiLCJ2IjoxfR", + "error": "E_NOT_A_GRANT" + }, + { + "name": "invalid UTF-8", + "signingInput": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlkwWmtYVmM2ZU5meHYzeFZOSFpKcDF4N20za1FxYjJPOHM1dkIxYVdjOUUiLCJ0eXAiOiJraW4tZ3JhbnQrandzIn0.eyL_IjoxfQ", + "error": "E_NOT_A_GRANT" + }, + { + "name": "typ is not kin-grant+jws", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"dpop+jwt\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "alg is not ES256", + "header": "{\"alg\":\"none\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "header carries a jwk", + "header": "{\"alg\":\"ES256\",\"jwk\":{\"kty\":\"EC\"},\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "header with whitespace", + "header": "{\n \"alg\": \"ES256\",\n \"kid\": \"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\n \"typ\": \"kin-grant+jws\"\n}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "header keys out of order", + "header": "{\"typ\":\"kin-grant+jws\",\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "duplicate payload key", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"delete_branch\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "payload with whitespace", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\n \"actionId\": \"act_01JD7Z0000000000000000000\",\n \"approver\": {\n \"humanId\": \"h_owner\",\n \"kid\": \"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"\n },\n \"base\": \"main\",\n \"decision\": \"approve\",\n \"exp\": 1798762190,\n \"headSha\": \"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\n \"iat\": 1798761590,\n \"jti\": \"ZGV2aWNlLWp0aS0xNi1i\",\n \"kind\": \"merge_pull_request\",\n \"mergeMethod\": \"squash\",\n \"nonce\": \"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\n \"orgId\": \"org_01\",\n \"revision\": 2,\n \"target\": {\n \"_tag\": \"pull_request\",\n \"deleteBranchAfter\": false,\n \"host\": \"github.com\",\n \"mergeMethod\": \"squash\",\n \"number\": 212,\n \"repo\": \"GLDRoger/t3code\"\n },\n \"targetDigest\": \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\n \"v\": 1\n}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "float", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2.0,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "leading zero", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":02,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "negative zero", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":-0,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "integer beyond 2^53", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":9007199254740993,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "escaped slash", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\/in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "uppercase \\u escape", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"ma\\u001Fin\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "\\u escape for a printable character", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"m\\u0061in\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "null value", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":null,\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "array value", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":[\"main\"],\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "unknown payload field", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"note\":\"hi\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "unknown target field", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"extra\":1,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "v is 2", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":2}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "decision is reject", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"reject\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "kind without a template", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"deploy\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "kind does not match the target", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"delete_branch\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "merge without headSha", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "merge without base", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "mergeMethod differs from the target", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"merge\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "uppercase headSha", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"A1B2C3D4E5F60718293A4B5C6D7E8F9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "delete_branch carrying base", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"delete_branch\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"branch\",\"host\":\"github.com\",\"ref\":\"x\",\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "set_level carrying headSha", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"l\",\"level\":\"L1\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "level L4", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"l\",\"level\":\"L4\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "exp more than 900 s after iat", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762500,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "exp not after iat", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798761590,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "iat 301 s ahead of the device clock", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762000,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761901,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "host is not github.com", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"gitlab.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "repo slug with a space", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLD Roger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "repo slug without an owner", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "number is zero", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":0,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a shown field that is only control characters", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"\\u0007‮\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "empty kid", + "header": "{\"alg\":\"ES256\",\"kid\":\"\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "short thumbprint", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"thumbprint\":\"abc\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "nested too deep", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h\",\"kid\":\"k\",\"x\":{\"y\":{}}},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "approver with an extra field", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"role\":\"owner\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "number as a string", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":\"212\",\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "negative revision", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":-1,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "target without deleteBranchAfter", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "uppercase targetDigest", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "empty jti", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a kid with K, the same bytes in header and approver", + "header": "{\"alg\":\"ES256\",\"kid\":\"K0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"K0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into \"main\" by squashing" + }, + { + "name": "approver.kid differs from the header kid", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"other\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "approver.kid is canonically equivalent to the header kid but not the same bytes (U+212A for K)", + "header": "{\"alg\":\"ES256\",\"kid\":\"K0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"K0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"base\":\"main\",\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"merge_pull_request\",\"mergeMethod\":\"squash\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"pull_request\",\"deleteBranchAfter\":false,\"host\":\"github.com\",\"mergeMethod\":\"squash\",\"number\":212,\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a leadId with a space is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"tech lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a chatId with a slash is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"chatId\":\"chat/7\",\"leadId\":\"tech-lead\",\"level\":\"L2\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a path with a space is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"change_rules\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"content\",\"path\":\"rules .md\",\"sha256\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a ref with a quote is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"delete_branch\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"branch\",\"host\":\"github.com\",\"ref\":\"kin/\\\"fix\",\"repo\":\"GLDRoger/t3code\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + } + ] +} diff --git a/apps/mobile/modules/kin-approval-key/index.test.ts b/apps/mobile/modules/kin-approval-key/index.test.ts new file mode 100644 index 0000000000000..fa6f7ebe55ce8 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/index.test.ts @@ -0,0 +1,86 @@ +import * as NodeCrypto from "node:crypto"; + +import { p256 } from "@noble/curves/nist"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { createKey, sign } from "./index"; +import { MalformedDerSignatureError } from "./src/derSignature"; + +const mocks = vi.hoisted(() => ({ + signDer: vi.fn<(signingInput: string) => Promise>(), + createKey: + vi.fn< + ( + challenge: string, + ) => Promise<{ publicKey: string; hardware: "tee"; attestationChain: string[] }> + >(), +})); + +vi.mock("expo", () => ({ + requireOptionalNativeModule: () => ({ signDer: mocks.signDer, createKey: mocks.createKey }), +})); + +function setup() { + mocks.signDer.mockReset(); + mocks.createKey.mockReset(); +} + +const b64 = (value: string | Uint8Array) => Buffer.from(value).toString("base64url"); +const signingInput = `${b64('{"alg":"ES256","kid":"k","typ":"kin-grant+jws"}')}.${b64('{"v":1}')}`; + +describe("sign", () => { + it("signs the signing input as given and returns a low-S compact signature", async () => { + setup(); + const { publicKey, privateKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + mocks.signDer.mockImplementation(async (input) => + b64(NodeCrypto.sign("sha256", Buffer.from(input), { key: privateKey, dsaEncoding: "der" })), + ); + + const signature = await sign(signingInput); + + expect(mocks.signDer).toHaveBeenCalledWith(signingInput); + const raw = publicKey.export({ format: "der", type: "spki" }).subarray(26); + const digest = NodeCrypto.hash("sha256", signingInput, "buffer"); + expect( + p256.verify(Buffer.from(signature, "base64url"), digest, raw, { + prehash: false, + format: "compact", + lowS: true, + }), + ).toBe(true); + }); + + it.each([ + ["empty", ""], + ["one part", b64("x")], + ["three parts", `${signingInput}.${b64("sig")}`], + ["an empty part", `${b64("x")}.`], + ["padding", `${b64("x")}==.${b64("y")}`], + ["standard base64", "a+b.c/d"], + ["whitespace", ` ${signingInput}`], + ])("rejects %s before reaching the native module", async (_name, input) => { + setup(); + await expect(sign(input)).rejects.toThrow("two unpadded base64url parts"); + expect(mocks.signDer).not.toHaveBeenCalled(); + }); + + it("rejects malformed DER from the native module", async () => { + setup(); + mocks.signDer.mockResolvedValueOnce(b64(new Uint8Array(64).fill(1))); + await expect(sign(signingInput)).rejects.toThrow(MalformedDerSignatureError); + mocks.signDer.mockResolvedValueOnce("not base64url!"); + await expect(sign(signingInput)).rejects.toThrow("signature is not base64url"); + }); +}); + +describe("createKey", () => { + it.each([ + ["15 bytes", b64(new Uint8Array(15))], + ["129 bytes", b64(new Uint8Array(129))], + ["padded", Buffer.from(new Uint8Array(32)).toString("base64")], + ])("refuses an attestation challenge that is %s", async (_name, challenge) => { + setup(); + await expect(createKey(challenge)).rejects.toThrow("attestationChallenge"); + expect(mocks.createKey).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/mobile/modules/kin-approval-key/index.ts b/apps/mobile/modules/kin-approval-key/index.ts new file mode 100644 index 0000000000000..c3c019d94fe7b --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/index.ts @@ -0,0 +1,111 @@ +import type { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Result from "effect/Result"; +import { requireOptionalNativeModule } from "expo"; + +import { derEcdsaSignatureToCompact } from "./src/derSignature"; +import { publicJwkFromNativePublicKey } from "./src/publicJwk"; + +export type KinApprovalKeyHardware = "secure_enclave" | "strongbox" | "tee"; + +/** Codes on errors the native side rejects with; see README.md. */ +export type KinApprovalKeyErrorCode = + | "E_NO_SECURE_HARDWARE" + | "E_UNSUPPORTED_OS" + | "E_BIOMETRY_UNAVAILABLE" + | "E_BIOMETRY_LOCKOUT" + | "E_KEY_EXISTS" + | "E_KEY_NOT_FOUND" + | "E_KEY_INVALIDATED" + | "E_USER_CANCELED" + | "E_AUTH_FAILED" + | "E_BUSY" + | "E_NOT_A_GRANT" + | "E_NO_ACTIVITY" + | "E_OBSCURED" + | "E_INVALID_INPUT" + | "E_KEYCHAIN" + | "E_KEYSTORE"; + +export interface KinApprovalKeyAttestation { + readonly format: "android-key"; + /** Leaf first, base64 (not base64url) DER, as in a JWS `x5c`. */ + readonly certificateChain: ReadonlyArray; +} + +export interface KinApprovalKey { + readonly publicJwk: DpopPublicJwk; + readonly hardware: KinApprovalKeyHardware; + readonly attestation?: KinApprovalKeyAttestation; +} + +interface NativeKinApprovalKey { + createKey(attestationChallenge: string): Promise<{ + readonly publicKey: string; + readonly hardware: KinApprovalKeyHardware; + readonly attestationChain?: ReadonlyArray; + }>; + signDer(signingInput: string): Promise; + hasKey(): Promise; + deleteKey(): Promise; +} + +const BASE64URL = /^[A-Za-z0-9_-]+$/; +const SIGNING_INPUT = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/; +const MIN_CHALLENGE_BYTES = 16; +const MAX_CHALLENGE_BYTES = 128; + +function native(): NativeKinApprovalKey { + const module = requireOptionalNativeModule("KinApprovalKey"); + if (!module) + throw new Error("KinApprovalKey is not in this build; install a current dev client."); + return module; +} + +function decodeBase64Url(value: string, label: string): Uint8Array { + const decoded = BASE64URL.test(value) ? Base64Url.decode(value) : undefined; + if (!decoded || Result.isFailure(decoded)) throw new Error(`${label} is not base64url.`); + return decoded.success; +} + +/** + * Creates the device's approval key in the Secure Enclave or Android Keystore. Fails with + * `E_KEY_EXISTS` rather than replacing a key the server may already trust. + * `attestationChallenge` is the server's registration nonce as unpadded base64url of 16 to 128 + * bytes. Android binds it into the attestation chain; iOS has no attestation yet and ignores it. + */ +export async function createKey(attestationChallenge: string): Promise { + const challenge = decodeBase64Url(attestationChallenge, "attestationChallenge"); + if (challenge.length < MIN_CHALLENGE_BYTES || challenge.length > MAX_CHALLENGE_BYTES) + throw new Error("attestationChallenge must encode 16 to 128 bytes."); + const created = await native().createKey(attestationChallenge); + const publicJwk = publicJwkFromNativePublicKey(decodeBase64Url(created.publicKey, "publicKey")); + return { + publicJwk, + hardware: created.hardware, + ...(created.attestationChain + ? { attestation: { format: "android-key", certificateChain: created.attestationChain } } + : {}), + }; +} + +/** + * `signingInput` is the grant's JWS signing input as-is (spec section 5): unpadded base64url of + * the `stableStringify` header and payload, joined by "."; the key signs its ASCII bytes after a + * biometric. Natively: non-grants get `E_NOT_A_GRANT`, the prompt is written from the payload, and + * a second call before the first settles gets `E_BUSY`. Resolves to the low-S `r‖s`, base64url. + */ +export async function sign(signingInput: string): Promise { + if (!SIGNING_INPUT.test(signingInput)) + throw new Error("signingInput must be two unpadded base64url parts joined by one dot."); + const der = await native().signDer(signingInput); + return Base64Url.encode(derEcdsaSignatureToCompact(decodeBase64Url(der, "signature"))); +} + +export function hasKey(): Promise { + return native().hasKey(); +} + +export function deleteKey(): Promise { + return native().deleteKey(); +} diff --git a/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift b/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift new file mode 100644 index 0000000000000..1df467115b4d2 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift @@ -0,0 +1,176 @@ +import UIKit + +/// The Face ID confirmation sheet, in a window the module owns above the app's own window, so the +/// app's JS can't draw over the grant text and leave the real Approve button exposed. +@MainActor +final class ConfirmationSheet { + enum Outcome { + case approved + case obscured + case canceled(String) + } + + private let window: UIWindow + private let controller: ConfirmationController + private weak var previousKeyWindow: UIWindow? + private var observers: [NSObjectProtocol] = [] + private var onOutcome: ((Outcome) -> Void)? + + /// Shows the sheet at once. `onOutcome` is called exactly once, after the sheet is gone. + init(scene: UIWindowScene, prompt: String, onOutcome: @escaping (Outcome) -> Void) { + self.onOutcome = onOutcome + previousKeyWindow = scene.keyWindow + // An input accessory view lives in the keyboard's window, above every app window. + for window in scene.windows { window.endEditing(true) } + window = UIWindow(windowScene: scene) + window.windowLevel = .alert + 1 + controller = ConfirmationController(prompt: prompt) + window.rootViewController = controller + + controller.onCancel = { [weak self] in self?.finish(.canceled("Approval was canceled.")) } + controller.onApprove = { [weak self] in + guard let self else { return } + finish(isUnobscured ? .approved : .obscured) + } + controller.onDisappear = { [weak self] in self?.finish(.canceled("The confirmation sheet closed.")) } + let center = NotificationCenter.default + let leaving: [(Notification.Name, AnyObject?)] = [ + (UIScene.didEnterBackgroundNotification, scene), + (UIScene.didDisconnectNotification, scene), + (UIApplication.didEnterBackgroundNotification, nil), + ] + for (name, object) in leaving { + observers.append(center.addObserver(forName: name, object: object, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { self?.finish(.canceled("The app left the foreground during approval.")) } + }) + } + window.makeKeyAndVisible() + } + + /// Removes the sheet without an outcome; safe to call more than once. + func close() { + onOutcome = nil + for observer in observers { NotificationCenter.default.removeObserver(observer) } + observers = [] + window.isHidden = true + window.rootViewController = nil + if let previousKeyWindow, !previousKeyWindow.isHidden { previousKeyWindow.makeKey() } + } + + private func finish(_ outcome: Outcome) { + guard let onOutcome else { return } + close() + onOutcome(outcome) + } + + /// Checked when Approve is tapped: this window is key and on top, and nothing sits over the card, + /// whether another window, a view added to this one (react-native-screens' FullWindowOverlay + /// joins the key window), or a controller presented over the sheet (RN's Alert presents there). + private var isUnobscured: Bool { + guard window.isKeyWindow, !window.isHidden, let scene = window.windowScene else { return false } + let windowAbove = scene.windows.contains { other in + other !== window && !other.isHidden && other.windowLevel >= window.windowLevel + } + return !windowAbove + && window.subviews.last === controller.view + && controller.view.subviews.last === controller.card + && controller.presentedViewController == nil + } +} + +private final class ConfirmationController: UIViewController { + var onApprove: (() -> Void)? + var onCancel: (() -> Void)? + var onDisappear: (() -> Void)? + let card = UIView() + private let prompt: String + private let scroll = UIScrollView() + + init(prompt: String) { + self.prompt = prompt + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = UIColor.black.withAlphaComponent(0.4) + view.maximumContentSizeCategory = .accessibilityLarge + + card.backgroundColor = .systemBackground + card.layer.cornerRadius = 14 + card.layer.cornerCurve = .continuous + card.accessibilityViewIsModal = true + + let title = label("Confirm approval", .headline) + title.accessibilityTraits = .header + let message = label(prompt, .body) + scroll.addSubview(message) + + let cancel = UIButton(configuration: .gray(), primaryAction: UIAction(title: "Cancel") { [weak self] _ in + self?.onCancel?() + }) + let approve = UIButton(configuration: .filled(), primaryAction: UIAction(title: "Approve") { [weak self] _ in + self?.onApprove?() + }) + let buttons = UIStackView(arrangedSubviews: [cancel, approve]) + buttons.spacing = 8 + buttons.distribution = .fillEqually + + let content = UIStackView(arrangedSubviews: [title, scroll, buttons]) + content.axis = .vertical + content.spacing = 16 + content.translatesAutoresizingMaskIntoConstraints = false + card.addSubview(content) + card.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(card) + + let safe = view.safeAreaLayoutGuide + // The text scrolls instead of clipping when it can't fit, so no fixed word is ever cut off. + let fitText = scroll.heightAnchor.constraint(equalTo: scroll.contentLayoutGuide.heightAnchor) + fitText.priority = .defaultHigh + let preferredWidth = card.widthAnchor.constraint(equalToConstant: 320) + preferredWidth.priority = .defaultHigh + NSLayoutConstraint.activate([ + card.centerXAnchor.constraint(equalTo: safe.centerXAnchor), + card.centerYAnchor.constraint(equalTo: safe.centerYAnchor), + card.leadingAnchor.constraint(greaterThanOrEqualTo: safe.leadingAnchor, constant: 20), + card.topAnchor.constraint(greaterThanOrEqualTo: safe.topAnchor, constant: 20), + preferredWidth, + content.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 20), + content.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -20), + content.topAnchor.constraint(equalTo: card.topAnchor, constant: 20), + content.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -20), + message.leadingAnchor.constraint(equalTo: scroll.contentLayoutGuide.leadingAnchor), + message.trailingAnchor.constraint(equalTo: scroll.contentLayoutGuide.trailingAnchor), + message.topAnchor.constraint(equalTo: scroll.contentLayoutGuide.topAnchor), + message.bottomAnchor.constraint(equalTo: scroll.contentLayoutGuide.bottomAnchor), + message.widthAnchor.constraint(equalTo: scroll.frameLayoutGuide.widthAnchor), + fitText, + ]) + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + scroll.flashScrollIndicators() + UIAccessibility.post(notification: .screenChanged, argument: card) + } + + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + onDisappear?() + } + + private func label(_ text: String, _ style: UIFont.TextStyle) -> UILabel { + let label = UILabel() + label.text = text + label.font = .preferredFont(forTextStyle: style) + label.adjustsFontForContentSizeCategory = true + label.numberOfLines = 0 + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + } +} diff --git a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec new file mode 100644 index 0000000000000..8995267b44e74 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec @@ -0,0 +1,13 @@ +Pod::Spec.new do |s| + s.name = 'KinApprovalKey' + s.version = '1.0.0' + s.summary = 'Secure Enclave approval key for Kin grants.' + s.author = 'Kin' + s.homepage = 'https://github.com/GLDRoger/t3code' + s.platform = :ios, '18.0' + s.source = { :path => '.' } + s.static_framework = true + s.dependency 'ExpoModulesCore' + s.source_files = '*.swift' + s.frameworks = 'CryptoKit', 'LocalAuthentication', 'Security' +end diff --git a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift new file mode 100644 index 0000000000000..06fe88d98b9cf --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift @@ -0,0 +1,339 @@ +import CryptoKit +import ExpoModulesCore +import Foundation +import LocalAuthentication +import Security +import UIKit + +// One approval key per install. It only ever signs Kin grants, never connections. +private let keyTag = Data("kin.approval-key.v1".utf8) +// The biometric enrolment the key was bound to, kept only to tell re-enrolment from a failed match. +private let biometryStateService = "kin.approval-key.v1.biometry-state" + +public class KinApprovalKeyModule: Module { + // Concurrent, so a second sign reaches the busy check while the first one waits on Face ID. + private static let signQueue = DispatchQueue(label: "kin.approval-key", attributes: .concurrent) + + public func definition() -> ModuleDefinition { + Name("KinApprovalKey") + + // iOS has no attestation in phase 1, so the challenge is unused here. + AsyncFunction("createKey") { (_: String) throws -> [String: Any] in + try createKey() + } + + AsyncFunction("signDer") { (signingInput: String, promise: Promise) in + SignRequest.start(signingInput: signingInput, promise: promise, queue: Self.signQueue) + }.runOnQueue(Self.signQueue) + + AsyncFunction("hasKey") { () throws -> Bool in + try loadPrivateKey(context: nil) != nil + } + + AsyncFunction("deleteKey") { () throws in + let status = SecItemDelete(privateKeyQuery() as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { + throw ApprovalKeyException("E_KEYCHAIN", "Deleting the approval key failed (OSStatus \(status)).") + } + SecItemDelete(biometryStateQuery() as CFDictionary) + } + } +} + +private func createKey() throws -> [String: Any] { + guard SecureEnclave.isAvailable else { + throw ApprovalKeyException("E_NO_SECURE_HARDWARE", "This device has no Secure Enclave.") + } + let context = LAContext() + var policyError: NSError? + guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &policyError) else { + throw ApprovalKeyException( + "E_BIOMETRY_UNAVAILABLE", + "Face ID or Touch ID must be set up, with a passcode, to create an approval key.", + cause: policyError) + } + guard try loadPrivateKey(context: nil) == nil else { + throw ApprovalKeyException("E_KEY_EXISTS", "An approval key already exists; delete it first.") + } + + var error: Unmanaged? + // .biometryCurrentSet: every signature needs biometrics, and changing enrolment invalidates the key. + guard let access = SecAccessControlCreateWithFlags( + kCFAllocatorDefault, + kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, + [.privateKeyUsage, .biometryCurrentSet], + &error + ) else { + throw ApprovalKeyException("E_KEYCHAIN", "Creating the access control failed.", cause: error?.takeRetainedValue()) + } + let attributes: [String: Any] = [ + kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, + kSecAttrKeySizeInBits as String: 256, + kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, + kSecPrivateKeyAttrs as String: [ + kSecAttrIsPermanent as String: true, + kSecAttrApplicationTag as String: keyTag, + kSecAttrAccessControl as String: access, + ] as [String: Any], + ] + guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else { + throw ApprovalKeyException( + "E_KEYCHAIN", "Creating the Secure Enclave key failed.", cause: error?.takeRetainedValue()) + } + guard let publicKey = SecKeyCopyPublicKey(privateKey), + let x963 = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else { + SecItemDelete(privateKeyQuery() as CFDictionary) + throw ApprovalKeyException( + "E_KEYCHAIN", "Exporting the approval public key failed.", cause: error?.takeRetainedValue()) + } + storeBiometryState(context.domainState.biometry.stateHash) + return ["publicKey": base64UrlEncode(x963), "hardware": "secure_enclave"] +} + +/// One `sign` call. Only one may be in flight; every path settles its promise exactly once. +private final class SignRequest: @unchecked Sendable { + private static let gate = NSLock() + nonisolated(unsafe) private static var busy = false + + private let promise: Promise + private let queue: DispatchQueue + private let lock = NSLock() + private var settled = false + @MainActor private var sheet: ConfirmationSheet? + + private init(promise: Promise, queue: DispatchQueue) { + self.promise = promise + self.queue = queue + } + + static func start(signingInput: String, promise: Promise, queue: DispatchQueue) { + gate.lock() + let wasBusy = busy + busy = true + gate.unlock() + guard !wasBusy else { + promise.reject(ApprovalKeyException("E_BUSY", "Another approval is already waiting for the user.")) + return + } + SignRequest(promise: promise, queue: queue).prepare(signingInput: signingInput) + } + + private func prepare(signingInput: String) { + let prompt: String + do { + prompt = try KinGrant.prompt(signingInput: signingInput, now: Int64(Date().timeIntervalSince1970)) + } catch { + return reject(ApprovalKeyException("E_NOT_A_GRANT", "Only Kin grants can be signed: \(error).")) + } + // A fresh context per signature, so no earlier match is ever reused. + let context = LAContext() + context.localizedFallbackTitle = "" + context.localizedReason = prompt + var policyError: NSError? + guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &policyError) else { + let lockedOut = (policyError?.code == LAError.biometryLockout.rawValue) + return reject(ApprovalKeyException( + lockedOut ? "E_BIOMETRY_LOCKOUT" : "E_BIOMETRY_UNAVAILABLE", + lockedOut ? "Biometrics are locked; unlock with the passcode first." : "Face ID or Touch ID isn't available.", + cause: policyError)) + } + let enrolmentChanged = biometryStateChanged(context.domainState.biometry.stateHash) + let key: SecKey + do { + guard let found = try loadPrivateKey(context: context) else { + return reject(enrolmentChanged ? invalidated() : ApprovalKeyException( + "E_KEY_NOT_FOUND", "There is no approval key on this device.")) + } + key = found + } catch { + return reject(error) + } + // Face ID and Optic ID mostly ignore localizedReason, so the grant is shown natively first. + let needsSheet = context.biometryType != .touchID + DispatchQueue.main.async { + self.confirm(prompt: prompt, needsSheet: needsSheet) { + self.queue.async { + self.sign(Data(signingInput.utf8), with: key, context: context, enrolmentChanged: enrolmentChanged) + } + } + } + } + + @MainActor + private func confirm(prompt: String, needsSheet: Bool, approved: @escaping () -> Void) { + guard !isSettled else { return } + let scene = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .first { $0.activationState == .foregroundActive } + guard UIApplication.shared.applicationState == .active, let scene else { + return reject(ApprovalKeyException("E_NO_ACTIVITY", "Approvals need the app in the foreground.")) + } + guard needsSheet else { return approved() } + sheet = ConfirmationSheet(scene: scene, prompt: prompt) { outcome in + switch outcome { + case .approved: + approved() + case .obscured: + self.reject(ApprovalKeyException("E_OBSCURED", "Something covered the confirmation sheet, so nothing was signed.")) + case .canceled(let reason): + self.reject(ApprovalKeyException("E_USER_CANCELED", reason)) + } + } + } + + private func sign(_ message: Data, with key: SecKey, context: LAContext, enrolmentChanged: Bool) { + guard !isSettled else { return } + var error: Unmanaged? + guard let signature = SecKeyCreateSignature( + key, .ecdsaSignatureMessageX962SHA256, message as CFData, &error + ) as Data? else { + return reject(signingException(error?.takeRetainedValue(), enrolmentChanged: enrolmentChanged)) + } + // The key still signs, so the current enrolment is the one it's bound to (e.g. after an OS update). + if enrolmentChanged { storeBiometryState(context.domainState.biometry.stateHash) } + settle { $0.resolve(base64UrlEncode(signature)) } + } + + private var isSettled: Bool { + lock.lock() + defer { lock.unlock() } + return settled + } + + private func reject(_ error: Error) { + settle { $0.reject(error) } + } + + private func settle(_ body: (Promise) -> Void) { + lock.lock() + let first = !settled + settled = true + lock.unlock() + guard first else { return } + Self.gate.lock() + Self.busy = false + Self.gate.unlock() + DispatchQueue.main.async { + self.sheet?.close() + self.sheet = nil + } + body(promise) + } +} + +private func invalidated() -> ApprovalKeyException { + ApprovalKeyException( + "E_KEY_INVALIDATED", + "Biometric enrolment changed, so the approval key no longer works. Delete it and register a new one.") +} + +private func privateKeyQuery() -> [String: Any] { + [ + kSecClass as String: kSecClassKey, + kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, + kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, + kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, + kSecAttrApplicationTag as String: keyTag, + ] +} + +private func loadPrivateKey(context: LAContext?) throws -> SecKey? { + var query = privateKeyQuery() + query[kSecReturnRef as String] = true + if let context { + query[kSecUseAuthenticationContext as String] = context + } else { + // Looking the key up must never show UI; only signing authenticates. + let silent = LAContext() + silent.interactionNotAllowed = true + query[kSecUseAuthenticationContext as String] = silent + } + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + switch status { + case errSecSuccess: + guard let item, CFGetTypeID(item) == SecKeyGetTypeID() else { + throw ApprovalKeyException("E_KEYCHAIN", "The approval key lookup returned something other than a key.") + } + return unsafeDowncast(item, to: SecKey.self) + case errSecItemNotFound: + return nil + default: + throw ApprovalKeyException("E_KEYCHAIN", "Reading the approval key failed (OSStatus \(status)).") + } +} + +private func biometryStateQuery() -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: biometryStateService, + kSecAttrAccount as String: "state", + ] +} + +// Best effort: the state only classifies errors. Apple warns it can change across major OS +// versions with no enrolment change, so a mismatch alone never blocks signing. +private func storeBiometryState(_ state: Data?) { + SecItemDelete(biometryStateQuery() as CFDictionary) + guard let state else { return } + var item = biometryStateQuery() + item[kSecValueData as String] = state + item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly + SecItemAdd(item as CFDictionary, nil) +} + +private func biometryStateChanged(_ current: Data?) -> Bool { + var query = biometryStateQuery() + query[kSecReturnData as String] = true + var item: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, let stored = item as? Data else { + return false + } + return stored != current +} + +private func signingException(_ error: CFError?, enrolmentChanged: Bool) -> ApprovalKeyException { + guard let error else { + return ApprovalKeyException("E_AUTH_FAILED", "Signing failed without an error.") + } + let nsError = error as Error as NSError + let la = nsError.domain == LAErrorDomain + let status = nsError.domain == NSOSStatusErrorDomain ? OSStatus(nsError.code) : nil + let canceled: Set = [ + LAError.userCancel.rawValue, LAError.appCancel.rawValue, LAError.systemCancel.rawValue, + LAError.userFallback.rawValue, + ] + let unavailable: Set = [ + LAError.biometryNotEnrolled.rawValue, LAError.biometryNotAvailable.rawValue, LAError.passcodeNotSet.rawValue, + ] + if (la && canceled.contains(nsError.code)) || status == errSecUserCanceled { + return ApprovalKeyException("E_USER_CANCELED", "Approval was canceled.", cause: nsError) + } + if la && nsError.code == LAError.biometryLockout.rawValue { + return ApprovalKeyException("E_BIOMETRY_LOCKOUT", "Biometrics are locked; unlock with the passcode first.", cause: nsError) + } + if la && unavailable.contains(nsError.code) { + return ApprovalKeyException("E_BIOMETRY_UNAVAILABLE", "Face ID or Touch ID isn't available.", cause: nsError) + } + if (la && nsError.code == LAError.notInteractive.rawValue) || status == errSecInteractionNotAllowed { + return ApprovalKeyException("E_NO_ACTIVITY", "Approvals need the app in the foreground.", cause: nsError) + } + if enrolmentChanged { return invalidated() } + // A failed match, or a re-enrolment made before this install recorded its enrolment state. + return ApprovalKeyException( + "E_AUTH_FAILED", "Signing failed (\(nsError.domain) \(nsError.code)).", cause: nsError) +} + +private func base64UrlEncode(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") +} + +private final class ApprovalKeyException: Exception, @unchecked Sendable { + init(_ code: String, _ description: String, cause: Error? = nil) { + super.init(name: "ApprovalKeyException", description: description, code: code) + self.cause = cause + } +} diff --git a/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift b/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift new file mode 100644 index 0000000000000..52bd8b3f448c9 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift @@ -0,0 +1,430 @@ +import Foundation + +// Parses a KinGrant JWS signing input (docs/kin/specs/approvals.md, section 5) and builds the +// approval prompt from it. Foundation only, so test/native/run.sh can compile it on a Mac; it must +// accept and reject exactly what android/.../KinGrant.java does (fixtures/grant-vectors.json). +enum KinGrant { + struct NotAGrant: Error, CustomStringConvertible { + let description: String + init(_ description: String) { self.description = description } + } + + /// A JSON string or key as its UTF-8 bytes. Swift's `String` compares and hashes by canonical + /// equivalence ("\u{212A}" == "K"), which Java doesn't, so every comparison here is on bytes. + struct Bytes: Hashable, ExpressibleByStringLiteral, CustomStringConvertible { + let utf8: [UInt8] + init(_ utf8: [UInt8]) { self.utf8 = utf8 } + init(stringLiteral value: String) { utf8 = Array(value.utf8) } + var description: String { String(decoding: utf8, as: UTF8.self) } + } + + private static let maxSigningInput = 8192 + private static let maxDepth = 3 + private static let maxPromptBytes = 200 + private static let shownHashLength = 16 + private static let maxSafeInteger: Int64 = 9_007_199_254_740_991 + private static let maxLifetimeSeconds: Int64 = 900 + private static let maxClockSkewSeconds: Int64 = 300 + private static let payloadRequired: Set = [ + "v", "orgId", "actionId", "revision", "nonce", "jti", "kind", "targetDigest", "target", + "approver", "decision", "iat", "exp", + ] + private static let payloadOptional: Set = ["headSha", "base", "mergeMethod"] + + /// Returns the prompt text for a valid grant signing input, or throws `NotAGrant`. + static func prompt(signingInput: String, now: Int64) throws -> String { + guard !signingInput.isEmpty, signingInput.utf8.count <= maxSigningInput else { + throw NotAGrant("signing input is empty or too long") + } + let segments = signingInput.utf8.split(separator: UInt8(ascii: "."), omittingEmptySubsequences: false) + guard segments.count == 2 else { throw NotAGrant("signing input is not header.payload") } + let header = try object(Array(segments[0]), "header") + let payload = try object(Array(segments[1]), "payload") + try checkHeader(header) + return try promptFor(payload, kid: try string(header, "kid"), now: now) + } + + private static func object(_ segment: [UInt8], _ label: String) throws -> [Bytes: Value] { + let bytes = try base64UrlDecode(segment, label) + guard String(validating: bytes, as: UTF8.self) != nil else { throw NotAGrant("\(label) is not UTF-8") } + var parser = Parser(bytes: bytes) + guard case .object(let map) = try parser.parseDocument() else { throw NotAGrant("\(label) is not an object") } + return map + } + + private static func checkHeader(_ header: [Bytes: Value]) throws { + try exactKeys(header, ["alg", "kid", "typ"], [], "header") + guard try string(header, "alg") == "ES256" else { throw NotAGrant("alg is not ES256") } + guard try string(header, "typ") == "kin-grant+jws" else { throw NotAGrant("typ is not kin-grant+jws") } + try nonEmpty(header, "kid") + } + + private static func promptFor(_ p: [Bytes: Value], kid: Bytes, now: Int64) throws -> String { + try exactKeys(p, payloadRequired, payloadOptional, "payload") + guard try integer(p, "v") == 1 else { throw NotAGrant("v is not 1") } + guard try string(p, "decision") == "approve" else { throw NotAGrant("decision is not approve") } + for key: Bytes in ["orgId", "actionId", "nonce", "jti"] { try nonEmpty(p, key) } + guard try integer(p, "revision") >= 0 else { throw NotAGrant("revision is negative") } + _ = try hex(p, "targetDigest", length: 64) + let approver = try child(p, "approver") + try exactKeys(approver, ["humanId", "kid"], [], "approver") + try nonEmpty(approver, "humanId") + guard try string(approver, "kid") == kid else { throw NotAGrant("approver.kid is not the header kid") } + + let iat = try integer(p, "iat") + let exp = try integer(p, "exp") + guard exp > iat, exp - iat <= maxLifetimeSeconds else { throw NotAGrant("exp is outside iat + 900") } + guard abs(now - iat) <= maxClockSkewSeconds else { throw NotAGrant("iat is not now") } + + let target = try child(p, "target") + let kind = try string(p, "kind") + let text: String + switch kind { + case "merge_pull_request": + try only(p, ["headSha", "base", "mergeMethod"]) + try exactKeys(target, ["_tag", "host", "repo", "number", "mergeMethod", "deleteBranchAfter"], [], "target") + try tag(target, "pull_request") + let repo = try githubRepo(target) + let number = try integer(target, "number") + guard number >= 1 else { throw NotAGrant("number is not positive") } + guard case .bool(let deleteAfter) = target["deleteBranchAfter"] else { + throw NotAGrant("deleteBranchAfter is not a boolean") + } + let method = try string(p, "mergeMethod") + guard try string(target, "mergeMethod") == method else { throw NotAGrant("mergeMethod differs from target") } + text = "Merge \(repo) #\(number) (\(try headSha(p))) into \"\(try shown(p, "base", .name))\" " + + (try methodWords(method)) + + (deleteAfter ? ", then delete its branch" : "") + case "delete_branch": + try only(p, ["headSha"]) + try exactKeys(target, ["_tag", "host", "repo", "ref"], [], "target") + try tag(target, "branch") + let repo = try githubRepo(target) + text = "Delete branch \"\(try shown(target, "ref", .name))\" (\(try headSha(p))) in \(repo)" + case "set_level": + try only(p, []) + try exactKeys(target, ["_tag", "leadId", "level"], ["chatId"], "target") + try tag(target, "level") + let level = try string(target, "level") + guard ["L0", "L1", "L2", "L3"].contains(level) else { throw NotAGrant("level is not L0-L3") } + let chat = target["chatId"] == nil ? " in all chats" : " in chat \"\(try shown(target, "chatId", .id))\"" + text = "Set lead \"\(try shown(target, "leadId", .id))\" to \(level)\(chat)" + case "change_rules", "memory_purge": + try only(p, []) + try exactKeys(target, ["_tag", "path", "sha256"], [], "target") + try tag(target, "content") + let hash = try hex(target, "sha256", length: 64).prefix(shownHashLength) + let path = try shown(target, "path", .name) + text = kind == "change_rules" + ? "Change rules to \"\(path)\" (sha256 \(hash))" + : "Purge memory using \"\(path)\" (sha256 \(hash))" + case "register_approver_key": + try only(p, []) + try exactKeys(target, ["_tag", "thumbprint"], [], "target") + try tag(target, "device_key") + let thumbprint = try string(target, "thumbprint").utf8 + guard thumbprint.count == 43, thumbprint.allSatisfy(isBase64UrlByte) else { + throw NotAGrant("thumbprint is malformed") + } + text = "Add approver key \(Bytes(Array(thumbprint.prefix(shownHashLength))))" + default: + throw NotAGrant("kind has no prompt template") + } + // Refused rather than cut, so the fixed words after a long value always show. + guard text.utf8.count <= maxPromptBytes else { throw NotAGrant("the prompt is over 200 characters") } + return text + } + + private static func githubRepo(_ target: [Bytes: Value]) throws -> String { + guard try string(target, "host") == "github.com" else { throw NotAGrant("host is not github.com") } + let repo = try string(target, "repo") + let parts = repo.utf8.split(separator: UInt8(ascii: "/"), omittingEmptySubsequences: false) + let ownerOK = parts.count == 2 && (1...39).contains(parts[0].count) + && parts[0].allSatisfy { isAlphanumeric($0) || $0 == UInt8(ascii: "-") } + let nameOK = parts.count == 2 && (1...100).contains(parts[1].count) + && parts[1].allSatisfy(ShownField.id.allows) + guard ownerOK, nameOK else { throw NotAGrant("repo is malformed") } + return repo.description + } + + private static func methodWords(_ method: Bytes) throws -> String { + switch method { + case "merge": return "with a merge commit" + case "squash": return "by squashing" + case "rebase": return "by rebasing" + default: throw NotAGrant("mergeMethod is unknown") + } + } + + private static func headSha(_ p: [Bytes: Value]) throws -> String { + String(try hex(p, "headSha", length: 40).prefix(shownHashLength)) + } + + /// The optional payload fields allowed for this kind, all required; any other is refused. + private static func only(_ p: [Bytes: Value], _ allowed: Set) throws { + for key in payloadOptional where p[key] != nil && !allowed.contains(key) { + throw NotAGrant("\(key) is not allowed here") + } + for key in allowed where p[key] == nil { throw NotAGrant("\(key) is required") } + } + + private static func tag(_ target: [Bytes: Value], _ expected: Bytes) throws { + guard case .string(expected) = target["_tag"] else { throw NotAGrant("target is not \(expected)") } + } + + private static func exactKeys( + _ map: [Bytes: Value], _ required: Set, _ optional: Set, _ label: String + ) throws { + for key in required where map[key] == nil { throw NotAGrant("\(label).\(key) is missing") } + for key in map.keys where !required.contains(key) && !optional.contains(key) { + throw NotAGrant("\(label).\(key) is not allowed") + } + } + + private static func string(_ map: [Bytes: Value], _ key: Bytes) throws -> Bytes { + guard case .string(let value) = map[key] else { throw NotAGrant("\(key) is not a string") } + return value + } + + private static func nonEmpty(_ map: [Bytes: Value], _ key: Bytes) throws { + guard try !string(map, key).utf8.isEmpty else { throw NotAGrant("\(key) is empty") } + } + + private static func hex(_ map: [Bytes: Value], _ key: Bytes, length: Int) throws -> String { + let value = try string(map, key).utf8 + let lowerHex = value.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + guard value.count == length, lowerHex else { throw NotAGrant("\(key) is malformed") } + return String(decoding: value, as: UTF8.self) + } + + private static func integer(_ map: [Bytes: Value], _ key: Bytes) throws -> Int64 { + guard case .integer(let value) = map[key] else { throw NotAGrant("\(key) is not an integer") } + return value + } + + private static func child(_ map: [Bytes: Value], _ key: Bytes) throws -> [Bytes: Value] { + guard case .object(let value) = map[key] else { throw NotAGrant("\(key) is not an object") } + return value + } + + /// What a shown value may contain. ASCII only, so no platform Unicode table is consulted and + /// nothing invisible, confusable or reordering can reach the prompt; a quote can't occur. + enum ShownField { + /// Branch names and paths: letters, digits and `. _ - / +` (a subset of what git allows). + case name + /// Lead and chat ids: letters, digits and `. _ -`. + case id + + func allows(_ byte: UInt8) -> Bool { + if KinGrant.isAlphanumeric(byte) { return true } + switch self { + case .name: return Array("._-/+".utf8).contains(byte) + case .id: return Array("._-".utf8).contains(byte) + } + } + } + + /// A shown value, refused (never cleaned) if it is empty or has a byte outside its allowlist. + private static func shown(_ map: [Bytes: Value], _ key: Bytes, _ field: ShownField) throws -> String { + let value = try string(map, key) + guard !value.utf8.isEmpty, value.utf8.allSatisfy(field.allows) else { + throw NotAGrant("\(key) has a character that can't be shown") + } + return value.description + } + + private static func isAlphanumeric(_ byte: UInt8) -> Bool { + (48...57).contains(byte) || (65...90).contains(byte) || (97...122).contains(byte) + } + + private static func isBase64UrlByte(_ byte: UInt8) -> Bool { + isAlphanumeric(byte) || byte == UInt8(ascii: "-") || byte == UInt8(ascii: "_") + } + + /// Unpadded base64url with zero trailing bits, so every byte string has exactly one encoding. + static func base64UrlDecode(_ input: [UInt8], _ label: String) throws -> [UInt8] { + guard !input.isEmpty, input.count % 4 != 1 else { throw NotAGrant("\(label) is not base64url") } + var out: [UInt8] = [] + out.reserveCapacity(input.count * 3 / 4) + var buffer: UInt32 = 0 + var bits = 0 + for byte in input { + let digit: UInt32 + switch byte { + case 65...90: digit = UInt32(byte - 65) + case 97...122: digit = UInt32(byte - 97 + 26) + case 48...57: digit = UInt32(byte - 48 + 52) + case UInt8(ascii: "-"): digit = 62 + case UInt8(ascii: "_"): digit = 63 + default: throw NotAGrant("\(label) is not base64url") + } + buffer = (buffer << 6) | digit + bits += 6 + if bits >= 8 { + bits -= 8 + out.append(UInt8(truncatingIfNeeded: buffer >> UInt32(bits))) + buffer &= (1 << UInt32(bits)) - 1 + } + } + guard buffer == 0 else { throw NotAGrant("\(label) has non-zero trailing bits") } + return out + } + + enum Value { + case object([Bytes: Value]) + case string(Bytes) + case integer(Int64) + case bool(Bool) + } + + // Accepts only the canonical form stableStringify (packages/shared/src/relaySigning.ts) writes: + // no whitespace, keys in strictly increasing UTF-16 order (so no duplicates), JSON.stringify's + // string escapes, safe integers. Only objects, strings, integers and booleans occur in a grant. + private struct Parser { + let bytes: [UInt8] + var at = 0 + + init(bytes: [UInt8]) { self.bytes = bytes } + + mutating func parseDocument() throws -> Value { + let value = try parseValue(depth: 0) + guard at == bytes.count else { throw fail("trailing characters") } + return value + } + + private mutating func parseValue(depth: Int) throws -> Value { + guard at < bytes.count else { throw fail("unexpected end") } + switch bytes[at] { + case UInt8(ascii: "{"): return .object(try parseObject(depth: depth)) + case UInt8(ascii: "\""): return .string(try parseString()) + case UInt8(ascii: "-"), 48...57: return .integer(try parseInteger()) + default: + if literal("true") { return .bool(true) } + if literal("false") { return .bool(false) } + throw fail("unsupported value") + } + } + + private mutating func literal(_ word: String) -> Bool { + let utf8 = Array(word.utf8) + guard bytes.count - at >= utf8.count, Array(bytes[at.. [Bytes: Value] { + guard depth < KinGrant.maxDepth else { throw fail("nested too deep") } + at += 1 + var map: [Bytes: Value] = [:] + if peek("}") { + at += 1 + return map + } + var previous: Bytes? + while true { + guard peek("\"") else { throw fail("expected a key") } + let key = try parseString() + // UTF-16 code-unit order, as JavaScript sorts; String's utf16 view never normalizes. + if let previous, !previous.description.utf16.lexicographicallyPrecedes(key.description.utf16) { + throw fail("keys are not in canonical order") + } + previous = key + try expect(":") + map[key] = try parseValue(depth: depth + 1) + if peek(",") { + at += 1 + continue + } + try expect("}") + return map + } + } + + private mutating func parseString() throws -> Bytes { + at += 1 + var out: [UInt8] = [] + while true { + guard at < bytes.count else { throw fail("unterminated string") } + let byte = bytes[at] + at += 1 + if byte == UInt8(ascii: "\"") { + guard String(validating: out, as: UTF8.self) != nil else { throw fail("string is not UTF-8") } + return Bytes(out) + } + guard byte >= 0x20 else { throw fail("raw control character") } + guard byte == UInt8(ascii: "\\") else { + out.append(byte) + continue + } + guard at < bytes.count else { throw fail("unterminated escape") } + let escape = bytes[at] + at += 1 + switch escape { + case UInt8(ascii: "\""): out.append(UInt8(ascii: "\"")) + case UInt8(ascii: "\\"): out.append(UInt8(ascii: "\\")) + case UInt8(ascii: "b"): out.append(0x08) + case UInt8(ascii: "f"): out.append(0x0C) + case UInt8(ascii: "n"): out.append(0x0A) + case UInt8(ascii: "r"): out.append(0x0D) + case UInt8(ascii: "t"): out.append(0x09) + case UInt8(ascii: "u"): out.append(try parseControlEscape()) + default: throw fail("non-canonical escape") + } + } + } + + // JSON.stringify only writes \u for control characters without a short escape (and lone + // surrogates, which a grant never contains), always as lowercase \u00xx. + private mutating func parseControlEscape() throws -> UInt8 { + guard bytes.count - at >= 4, bytes[at] == 48, bytes[at + 1] == 48 else { + throw fail("non-canonical \\u escape") + } + let high = bytes[at + 2] + let low = bytes[at + 3] + guard high == 48 || high == 49 else { throw fail("non-canonical \\u escape") } + let lowValue: UInt8 + switch low { + case 48...57: lowValue = low - 48 + case 97...102: lowValue = low - 97 + 10 + default: throw fail("non-canonical \\u escape") + } + let value = (high - 48) * 16 + lowValue + guard ![0x08, 0x09, 0x0A, 0x0C, 0x0D].contains(value) else { throw fail("non-canonical \\u escape") } + at += 4 + return value + } + + private mutating func parseInteger() throws -> Int64 { + let start = at + if peek("-") { at += 1 } + if peek("0") { + at += 1 + } else { + guard at < bytes.count, (49...57).contains(bytes[at]) else { throw fail("bad number") } + while at < bytes.count, (48...57).contains(bytes[at]) { at += 1 } + } + if at < bytes.count, [UInt8(ascii: "."), UInt8(ascii: "e"), UInt8(ascii: "E")].contains(bytes[at]) { + throw fail("not an integer") + } + let digits = String(decoding: bytes[start.. Bool { + at < bytes.count && bytes[at] == UInt8(ascii: char) + } + + private mutating func expect(_ char: Unicode.Scalar) throws { + guard peek(char) else { throw fail("expected \(char)") } + at += 1 + } + + private func fail(_ reason: String) -> NotAGrant { + NotAGrant("not canonical JSON: \(reason)") + } + } +} diff --git a/apps/mobile/modules/kin-approval-key/src/derSignature.test.ts b/apps/mobile/modules/kin-approval-key/src/derSignature.test.ts new file mode 100644 index 0000000000000..4e96641e8c6e0 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/src/derSignature.test.ts @@ -0,0 +1,216 @@ +import * as NodeCrypto from "node:crypto"; + +import { p256 } from "@noble/curves/nist"; +import { describe, expect, it } from "vite-plus/test"; + +import { derEcdsaSignatureToCompact, MalformedDerSignatureError } from "./derSignature"; + +const N = p256.CURVE.n; +const message = new TextEncoder().encode("eyJhbGciOiJFUzI1NiJ9.eyJ2IjoxfQ"); + +function bytesToBigInt(bytes: Uint8Array) { + return BigInt(`0x${Buffer.from(bytes).toString("hex") || "0"}`); +} + +function bigIntTo32(value: bigint) { + return Uint8Array.from(Buffer.from(value.toString(16).padStart(64, "0"), "hex")); +} + +function derInteger(value: bigint) { + const digits = value.toString(16); + const magnitude = Buffer.from(digits.length % 2 ? `0${digits}` : digits, "hex"); + const bytes = (magnitude[0] ?? 0) & 0x80 ? [0, ...magnitude] : [...magnitude]; + return Uint8Array.from([0x02, bytes.length, ...bytes]); +} + +function derSignature(r: bigint, s: bigint) { + const body = [...derInteger(r), ...derInteger(s)]; + return Uint8Array.from([0x30, body.length, ...body]); +} + +function nodeKeyPair() { + return NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); +} + +function rawPublicKey(publicKey: NodeCrypto.KeyObject) { + return new Uint8Array(publicKey.export({ format: "der", type: "spki" }).subarray(26)); +} + +function verifiesEverywhere(publicKey: NodeCrypto.KeyObject, compact: Uint8Array) { + const node = NodeCrypto.verify( + "sha256", + message, + { key: publicKey, dsaEncoding: "ieee-p1363" }, + compact, + ); + const noble = p256.verify( + compact, + NodeCrypto.hash("sha256", message, "buffer"), + rawPublicKey(publicKey), + // The server's settings (approvals spec, section 5): high-S signatures are refused. + { prehash: false, format: "compact", lowS: true }, + ); + return { node, noble }; +} + +describe("derEcdsaSignatureToCompact", () => { + it("converts node:crypto DER signatures to compact signatures both verifiers accept", () => { + const { publicKey, privateKey } = nodeKeyPair(); + for (let i = 0; i < 64; i++) { + const der = new Uint8Array( + NodeCrypto.sign("sha256", message, { key: privateKey, dsaEncoding: "der" }), + ); + const compact = derEcdsaSignatureToCompact(der); + expect(compact).toHaveLength(64); + expect(verifiesEverywhere(publicKey, compact)).toEqual({ node: true, noble: true }); + } + }); + + it("normalises s to the low half of the order, so a grant has one signature", () => { + const { publicKey, privateKey } = nodeKeyPair(); + for (let i = 0; i < 16; i++) { + const compact = derEcdsaSignatureToCompact( + new Uint8Array(NodeCrypto.sign("sha256", message, { key: privateKey, dsaEncoding: "der" })), + ); + const r = bytesToBigInt(compact.subarray(0, 32)); + const s = bytesToBigInt(compact.subarray(32)); + expect(s <= N >> 1n).toBe(true); + const fromHighS = derEcdsaSignatureToCompact(derSignature(r, N - s)); + expect(Buffer.from(fromHighS)).toEqual(Buffer.from(compact)); + expect(verifiesEverywhere(publicKey, fromHighS)).toEqual({ node: true, noble: true }); + } + const half = N >> 1n; + expect(bytesToBigInt(derEcdsaSignatureToCompact(derSignature(1n, half)).subarray(32))).toBe( + half, + ); + expect( + bytesToBigInt(derEcdsaSignatureToCompact(derSignature(1n, half + 1n)).subarray(32)), + ).toBe(N - half - 1n); + }); + + it("left-pads short scalars and strips the sign byte from high-bit scalars", () => { + const { publicKey, privateKey } = nodeKeyPair(); + const der = new Uint8Array( + NodeCrypto.sign("sha256", message, { key: privateKey, dsaEncoding: "der" }), + ); + const compact = derEcdsaSignatureToCompact(der); + const r = bytesToBigInt(compact.subarray(0, 32)); + const s = bytesToBigInt(compact.subarray(32)); + + // (r, n - s) is the other valid signature for the same message. One of s and n - s has its + // high bit set, so this always exercises the 33-byte INTEGER with a 0x00 sign byte. + for (const candidateS of [s, N - s]) { + const reencoded = derSignature(r, candidateS); + const converted = derEcdsaSignatureToCompact(reencoded); + expect(Buffer.from(converted.subarray(32))).toEqual(Buffer.from(bigIntTo32(s))); + expect(verifiesEverywhere(publicKey, converted)).toEqual({ node: true, noble: true }); + } + expect(derInteger(s >> 255n ? s : N - s)[1]).toBe(33); + }); + + it("verifies real signatures whose r or s needs fewer than 32 bytes", () => { + const privateKey = p256.utils.randomPrivateKey(); + const publicKey = NodeCrypto.createPublicKey({ + key: Buffer.concat([ + Buffer.from("3059301306072a8648ce3d020106082a8648ce3d030107034200", "hex"), + Buffer.from(p256.getPublicKey(privateKey, false)), + ]), + format: "der", + type: "spki", + }); + const digest = NodeCrypto.hash("sha256", message, "buffer"); + let found = 0; + // Each scalar is short with probability 1/256; 20k tries find one with overwhelming odds. + for (let i = 0; i < 20_000 && found < 2; i++) { + const signature = p256.sign(digest, privateKey, { prehash: false, extraEntropy: true }); + if (signature.r >= 1n << 248n && signature.s >= 1n << 248n) continue; + found++; + const der = signature.toDERRawBytes(); + const compact = derEcdsaSignatureToCompact(der); + expect(Buffer.from(compact)).toEqual(Buffer.from(signature.normalizeS().toCompactRawBytes())); + expect(verifiesEverywhere(publicKey, compact)).toEqual({ node: true, noble: true }); + } + expect(found).toBe(2); + }); + + it("keeps the smallest scalars at the right of their 32-byte slot", () => { + const compact = derEcdsaSignatureToCompact(derSignature(1n, 0x80n)); + expect(Buffer.from(compact).toString("hex")).toBe(`${"00".repeat(31)}01${"00".repeat(31)}80`); + const maxScalars = derEcdsaSignatureToCompact(derSignature(N - 1n, N - 1n)); + expect(Buffer.from(maxScalars.subarray(0, 32))).toEqual(Buffer.from(bigIntTo32(N - 1n))); + }); + + const valid = derSignature(0x1234n, 0x5678n); + const hex = (value: string) => Uint8Array.from(Buffer.from(value.replaceAll(" ", ""), "hex")); + const malformed: ReadonlyArray = [ + ["empty", "too short", new Uint8Array()], + ["compact instead of DER", "not a SEQUENCE", new Uint8Array(64).fill(1)], + ["SET instead of SEQUENCE", "not a SEQUENCE", Uint8Array.from([0x31, ...valid.subarray(1)])], + [ + "sequence length too long", + "SEQUENCE length", + Uint8Array.from([0x30, valid.length - 1, ...valid.subarray(2)]), + ], + [ + "sequence length too short", + "SEQUENCE length", + Uint8Array.from([0x30, valid.length - 3, ...valid.subarray(2)]), + ], + [ + "trailing bytes", + "trailing bytes", + Uint8Array.from([0x30, valid.length - 1, ...valid.subarray(2), 0x00]), + ], + [ + "long-form length", + "long-form", + Uint8Array.from([0x30, 0x81, valid.length - 2, ...valid.subarray(2)]), + ], + ["r not an INTEGER", "r is not an INTEGER", hex("3008 0402 1234 0202 5678")], + ["zero-length r", "r has no length", hex("3006 0200 0202 5678")], + ["negative r", "r is negative", hex("3008 0202 9234 0202 5678")], + ["non-minimal r", "r has a non-minimal", hex("3009 0203 001234 0202 5678")], + ["r = 0", "r is outside", hex("3007 0201 00 0202 5678")], + ["r = n", "r is outside", derSignature(N, 1n)], + ["s > n", "s is outside", derSignature(1n, N + 5n)], + [ + "33-byte r without sign byte", + "r is wider than 32", + Uint8Array.from([ + 0x30, + 0x26, + 0x02, + 0x21, + 0x01, + ...new Uint8Array(32).fill(1), + 0x02, + 0x01, + 0x01, + ]), + ], + [ + "34-byte r", + "r is longer than 33", + Uint8Array.from([ + 0x30, + 0x27, + 0x02, + 0x22, + 0x00, + 0x00, + ...new Uint8Array(32).fill(0x80), + 0x02, + 0x01, + 0x01, + ]), + ], + ["missing s", "s is not an INTEGER", hex("3006 0204 12345678")], + ["s runs past the end", "s runs past", hex("3008 0202 1234 0204 5678")], + ["a third INTEGER", "trailing bytes", hex("300b 0202 1234 0202 5678 0201 01")], + ]; + + it.each(malformed)("rejects %s", (_name, reason, der) => { + expect(() => derEcdsaSignatureToCompact(der)).toThrow(MalformedDerSignatureError); + expect(() => derEcdsaSignatureToCompact(der)).toThrow(reason); + }); +}); diff --git a/apps/mobile/modules/kin-approval-key/src/derSignature.ts b/apps/mobile/modules/kin-approval-key/src/derSignature.ts new file mode 100644 index 0000000000000..e8b590628457f --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/src/derSignature.ts @@ -0,0 +1,74 @@ +import * as Schema from "effect/Schema"; + +const P256_ORDER = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n; +const HALF_ORDER = P256_ORDER >> 1n; +const SCALAR_BYTES = 32; + +export class MalformedDerSignatureError extends Schema.TaggedError()( + "MalformedDerSignatureError", + { reason: Schema.String }, +) { + override get message(): string { + return `Malformed DER ECDSA signature: ${this.reason}.`; + } +} + +function fail(reason: string): never { + throw new MalformedDerSignatureError({ reason }); +} + +function readScalar(der: Uint8Array, offset: number, label: string) { + if (der[offset] !== 0x02) fail(`${label} is not an INTEGER`); + const length = der[offset + 1]; + if (length === undefined || length === 0) fail(`${label} has no length`); + if (length > SCALAR_BYTES + 1) fail(`${label} is longer than 33 bytes`); + const start = offset + 2; + const end = start + length; + if (end > der.length) fail(`${label} runs past the end`); + const first = der[start] ?? 0; + if (first & 0x80) fail(`${label} is negative`); + if (first === 0x00 && length > 1 && ((der[start + 1] ?? 0) & 0x80) === 0) { + fail(`${label} has a non-minimal leading zero`); + } + const magnitude = first === 0x00 ? der.subarray(start + 1, end) : der.subarray(start, end); + if (magnitude.length > SCALAR_BYTES) fail(`${label} is wider than 32 bytes`); + + let value = 0n; + for (const byte of magnitude) value = (value << 8n) | BigInt(byte); + if (value === 0n || value >= P256_ORDER) fail(`${label} is outside [1, n-1]`); + + return { value, end }; +} + +function scalarBytes(value: bigint): Uint8Array { + const bytes = new Uint8Array(SCALAR_BYTES); + let rest = value; + for (let index = SCALAR_BYTES - 1; index >= 0; index--, rest >>= 8n) + bytes[index] = Number(rest & 0xffn); + return bytes; +} + +/** + * Converts a strict-DER P-256 ECDSA signature (what the Secure Enclave and Android Keystore return) + * into the 64-byte `r‖s` form JWS ES256 uses, with `s` normalised to the low half of the group + * order. Anything that isn't canonical DER is rejected. + */ +export function derEcdsaSignatureToCompact(der: Uint8Array): Uint8Array { + if (der.length < 8) fail("too short"); + if (der[0] !== 0x30) fail("not a SEQUENCE"); + // P-256 signatures are at most 72 bytes, so the length is always short form. + const sequenceLength = der[1] ?? 0; + if (sequenceLength & 0x80) fail("long-form length"); + if (sequenceLength !== der.length - 2) fail("SEQUENCE length does not match"); + + const r = readScalar(der, 2, "r"); + const s = readScalar(der, r.end, "s"); + if (s.end !== der.length) fail("trailing bytes"); + + // (r, s) and (r, n − s) both verify; the server accepts only low-S, so one grant has one signature. + const lowS = s.value > HALF_ORDER ? P256_ORDER - s.value : s.value; + const compact = new Uint8Array(SCALAR_BYTES * 2); + compact.set(scalarBytes(r.value), 0); + compact.set(scalarBytes(lowS), SCALAR_BYTES); + return compact; +} diff --git a/apps/mobile/modules/kin-approval-key/src/grantVectors.test.ts b/apps/mobile/modules/kin-approval-key/src/grantVectors.test.ts new file mode 100644 index 0000000000000..21b10e527afa6 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/src/grantVectors.test.ts @@ -0,0 +1,23 @@ +import * as NodeFS from "node:fs"; + +import { stableStringify } from "@t3tools/shared/relaySigning"; +import { describe, expect, it } from "vite-plus/test"; + +// The Swift and Java parsers run these through test/native/run.sh; this ties the vectors they +// accept to the encoder the server uses, so a grant the server writes is one the phone accepts. +const vectors: { + cases: ReadonlyArray<{ name: string; header?: string; payload?: string; prompt?: string }>; +} = JSON.parse( + NodeFS.readFileSync(new URL("../fixtures/grant-vectors.json", import.meta.url), "utf8"), +); + +describe("grant vectors", () => { + it("accept exactly what stableStringify writes", () => { + const accepted = vectors.cases.filter((vector) => vector.prompt !== undefined); + expect(accepted.length).toBeGreaterThan(10); + for (const { name, header = "", payload = "" } of accepted) { + expect({ name, header: stableStringify(JSON.parse(header)) }).toEqual({ name, header }); + expect({ name, payload: stableStringify(JSON.parse(payload)) }).toEqual({ name, payload }); + } + }); +}); diff --git a/apps/mobile/modules/kin-approval-key/src/publicJwk.test.ts b/apps/mobile/modules/kin-approval-key/src/publicJwk.test.ts new file mode 100644 index 0000000000000..93ea4b1650a8b --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/src/publicJwk.test.ts @@ -0,0 +1,83 @@ +import * as NodeCrypto from "node:crypto"; + +import { p256 } from "@noble/curves/nist"; +import { computeDpopJwkThumbprint } from "@t3tools/shared/dpop"; +import { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { derEcdsaSignatureToCompact } from "./derSignature"; +import { InvalidApprovalPublicKeyError, publicJwkFromNativePublicKey } from "./publicJwk"; + +const decodeJwk = Schema.decodeUnknownSync(DpopPublicJwk); + +function nodeP256Key() { + const { publicKey, privateKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + const spki = new Uint8Array(publicKey.export({ format: "der", type: "spki" })); + return { publicKey, privateKey, spki, x963: spki.subarray(26) }; +} + +describe("publicJwkFromNativePublicKey", () => { + it("builds the same JWK from Android's SPKI and iOS's X9.63 export", () => { + const { publicKey, spki, x963 } = nodeP256Key(); + const expected = publicKey.export({ format: "jwk" }); + + const fromSpki = publicJwkFromNativePublicKey(spki); + const fromX963 = publicJwkFromNativePublicKey(x963); + + expect(fromSpki).toEqual({ kty: "EC", crv: "P-256", x: expected.x, y: expected.y }); + expect(fromX963).toEqual(fromSpki); + expect(decodeJwk(fromSpki)).toEqual(fromSpki); + expect(computeDpopJwkThumbprint(fromSpki)).toMatch(/^[A-Za-z0-9_-]{43}$/); + }); + + it("produces a JWK that verifies a converted signature the way the server will", () => { + const { privateKey, spki } = nodeP256Key(); + const signingInput = "eyJ0eXAiOiJraW4tZ3JhbnQrandzIn0.eyJ2IjoxfQ"; + const bytes = new TextEncoder().encode(signingInput); + const der = new Uint8Array( + NodeCrypto.sign("sha256", bytes, { key: privateKey, dsaEncoding: "der" }), + ); + + const jwk = publicJwkFromNativePublicKey(spki); + const point = Uint8Array.from([ + 0x04, + ...Result.getOrThrow(Base64Url.decode(jwk.x)), + ...Result.getOrThrow(Base64Url.decode(jwk.y)), + ]); + const verified = p256.verify( + derEcdsaSignatureToCompact(der), + NodeCrypto.hash("sha256", bytes, "buffer"), + point, + { prehash: false, format: "compact" }, + ); + expect(verified).toBe(true); + }); + + it("rejects keys that are not uncompressed P-256 points", () => { + const { spki, x963 } = nodeP256Key(); + const p384 = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-384" }).publicKey.export({ + format: "der", + type: "spki", + }); + const offCurve = Uint8Array.from(x963); + offCurve[64] = (offCurve[64] ?? 0) ^ 1; + const compressed = p256.ProjectivePoint.fromHex(x963).toRawBytes(true); + const wrongPrefix = Uint8Array.from(spki); + wrongPrefix[20] = 0x02; + + for (const key of [ + new Uint8Array(), + compressed, + Uint8Array.from([0x05, ...x963.subarray(1)]), + offCurve, + new Uint8Array(p384), + wrongPrefix, + Uint8Array.from([...spki, 0x00]), + ]) { + expect(() => publicJwkFromNativePublicKey(key)).toThrow(InvalidApprovalPublicKeyError); + } + }); +}); diff --git a/apps/mobile/modules/kin-approval-key/src/publicJwk.ts b/apps/mobile/modules/kin-approval-key/src/publicJwk.ts new file mode 100644 index 0000000000000..c977a0db09094 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/src/publicJwk.ts @@ -0,0 +1,57 @@ +import { p256 } from "@noble/curves/nist"; +import type { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Schema from "effect/Schema"; + +// SubjectPublicKeyInfo DER header for id-ecPublicKey / prime256v1 with an uncompressed point. +const P256_SPKI_PREFIX = Uint8Array.from([ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, +]); +const UNCOMPRESSED_POINT_BYTES = 65; + +export class InvalidApprovalPublicKeyError extends Schema.TaggedError()( + "InvalidApprovalPublicKeyError", + { message: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) {} + +function uncompressedPoint(publicKey: Uint8Array): Uint8Array { + if (publicKey.length === UNCOMPRESSED_POINT_BYTES) return publicKey; + if ( + publicKey.length === P256_SPKI_PREFIX.length + UNCOMPRESSED_POINT_BYTES && + P256_SPKI_PREFIX.every((byte, index) => publicKey[index] === byte) + ) { + return publicKey.subarray(P256_SPKI_PREFIX.length); + } + throw new InvalidApprovalPublicKeyError({ + message: + "Approval public key is neither an uncompressed P-256 point nor a P-256 SubjectPublicKeyInfo.", + }); +} + +/** + * Builds the JWK for the native key's public half: iOS exports an X9.63 uncompressed point, + * Android a SubjectPublicKeyInfo. The point must lie on P-256. + */ +export function publicJwkFromNativePublicKey(publicKey: Uint8Array): DpopPublicJwk { + const point = uncompressedPoint(publicKey); + if (point[0] !== 0x04) { + throw new InvalidApprovalPublicKeyError({ + message: "Approval public key is not an uncompressed point.", + }); + } + try { + p256.ProjectivePoint.fromHex(point).assertValidity(); + } catch (cause) { + throw new InvalidApprovalPublicKeyError({ + message: "Approval public key is not on P-256.", + cause, + }); + } + return { + kty: "EC", + crv: "P-256", + x: Base64Url.encode(point.subarray(1, 33)), + y: Base64Url.encode(point.subarray(33, 65)), + }; +} diff --git a/apps/mobile/modules/kin-approval-key/test/native/java/KinGrantVectors.java b/apps/mobile/modules/kin-approval-key/test/native/java/KinGrantVectors.java new file mode 100644 index 0000000000000..cf9f53e026782 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/test/native/java/KinGrantVectors.java @@ -0,0 +1,32 @@ +package expo.modules.kinapprovalkey; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +public final class KinGrantVectors { + public static void main(String[] args) throws Exception { + List lines = Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8); + long now = Long.parseLong(lines.get(0)); + int total = 0; + int failures = 0; + for (String line : lines.subList(1, lines.size())) { + if (line.isEmpty()) continue; + String[] fields = line.split("\t", -1); + String actual; + try { + actual = KinGrant.prompt(fields[1], now); + } catch (KinGrant.NotAGrantException error) { + actual = "!E_NOT_A_GRANT"; + } + total++; + if (!actual.equals(fields[2])) { + failures++; + System.out.println("FAIL java: " + fields[0] + "\n expected: " + fields[2] + "\n actual: " + actual); + } + } + System.out.println("java: " + (total - failures) + "/" + total + " grant vectors pass"); + System.exit(failures == 0 ? 0 : 1); + } +} diff --git a/apps/mobile/modules/kin-approval-key/test/native/run.sh b/apps/mobile/modules/kin-approval-key/test/native/run.sh new file mode 100755 index 0000000000000..e2b8fb1a7a0e7 --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/test/native/run.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Runs fixtures/grant-vectors.json through the Swift and Java grant parsers on a Mac with the +# Xcode command line tools and a JDK. No simulator, emulator or Android SDK needed. +set -eu +here=$(cd "$(dirname "$0")" && pwd) +module=$(cd "$here/../.." && pwd) +out=$(mktemp -d) +trap 'rm -rf "$out"' EXIT + +node -e ' +const { now, cases } = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); +const b64 = (s) => Buffer.from(s, "utf8").toString("base64url"); +const lines = cases.map((c) => [c.name, c.signingInput ?? `${b64(c.header)}.${b64(c.payload)}`, c.prompt ?? "!" + c.error].join("\t")); +process.stdout.write(`${now}\n${lines.join("\n")}\n`); +' "$module/fixtures/grant-vectors.json" > "$out/vectors.tsv" + +xcrun swiftc -O -o "$out/swift-vectors" "$module/ios/KinGrant.swift" "$here/swift/main.swift" +"$out/swift-vectors" "$out/vectors.tsv" + +javac -d "$out/java" \ + "$module/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java" \ + "$here/java/KinGrantVectors.java" +java -cp "$out/java" expo.modules.kinapprovalkey.KinGrantVectors "$out/vectors.tsv" diff --git a/apps/mobile/modules/kin-approval-key/test/native/swift/main.swift b/apps/mobile/modules/kin-approval-key/test/native/swift/main.swift new file mode 100644 index 0000000000000..e19435424c39d --- /dev/null +++ b/apps/mobile/modules/kin-approval-key/test/native/swift/main.swift @@ -0,0 +1,22 @@ +import Foundation + +let lines = try String(contentsOfFile: CommandLine.arguments[1], encoding: .utf8) + .split(separator: "\n", omittingEmptySubsequences: true) +guard let now = Int64(lines[0]) else { fatalError("The first line must be the vectors' clock.") } +var failures = 0 +for line in lines.dropFirst() { + let fields = line.split(separator: "\t", omittingEmptySubsequences: false).map(String.init) + let (name, signingInput, expected) = (fields[0], fields[1], fields[2]) + let actual: String + do { + actual = try KinGrant.prompt(signingInput: signingInput, now: now) + } catch { + actual = "!E_NOT_A_GRANT" + } + if actual != expected { + failures += 1 + print("FAIL swift: \(name)\n expected: \(expected)\n actual: \(actual)") + } +} +print("swift: \(lines.count - 1 - failures)/\(lines.count - 1) grant vectors pass") +exit(failures == 0 ? 0 : 1) diff --git a/apps/mobile/plugins/withKinApprovalKey.cjs b/apps/mobile/plugins/withKinApprovalKey.cjs new file mode 100644 index 0000000000000..71ee4743c9721 --- /dev/null +++ b/apps/mobile/plugins/withKinApprovalKey.cjs @@ -0,0 +1,12 @@ +const { withInfoPlist } = require("expo/config-plugins"); + +// No app name: source stays unbranded (KIN.md), and $(PRODUCT_NAME) would show the build target's name. +const FACE_ID_USAGE = "Face ID confirms the merges and other actions you approve."; + +// Set unconditionally so expo-secure-store's generic default never wins, whichever mod runs first. +module.exports = function withKinApprovalKey(config) { + return withInfoPlist(config, (nextConfig) => { + nextConfig.modResults.NSFaceIDUsageDescription = FACE_ID_USAGE; + return nextConfig; + }); +}; diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 601a726c276af..e4ebb45c39bc7 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -172,7 +172,7 @@ Storage (new, SQLite, Kin's own migration set in `apps/server/src/kin/persistenc **Modules.** None of this exists in the repo's dependencies. -- **Recommended: a new local Expo module** `apps/mobile/modules/kin-approval-key` (Swift + Kotlin, autolinked from `modules/`). API: `createKey(): {publicJwk, attestation?}`, `sign(signingInput: base64url, prompt: string): base64url`, `hasKey()`, `deleteKey()`. The Kotlin side needs `androidx.biometric:biometric` (**new dependency**, Google, declared in the module's own `android/build.gradle`). +- **Recommended: a new local Expo module** `apps/mobile/modules/kin-approval-key` (Swift + Kotlin, autolinked from `modules/`). API: `createKey(attestationChallenge): {publicJwk, hardware, attestation?}`, `sign(signingInput): base64url`, `hasKey()`, `deleteKey()`. `signingInput` is the grant's JWS signing input (section 5). The module signs nothing else: natively, it refuses anything that isn't a well-formed `KinGrant` and writes the approval text from the payload, so no caller chooses what the user is shown. The Kotlin side needs `androidx.biometric:biometric` (**new dependency**, Google, declared in the module's own `android/build.gradle`). - Not enough on their own: `expo-local-authentication` (**new**, Expo) only shows a prompt and doesn't bind a key; `expo-secure-store` (already installed, `~58.0.2`) with `requireAuthentication: true` gates a stored secret, but the key is still generated in JS and its bytes enter JS memory. Use the latter only as a stopgap behind a `softwareKey: true` flag that the card shows and the audit records. - Considered and not used: `react-native-biometrics` (**new**, third party) makes RSA keys and isn't Secure Enclave-backed on iOS. - iOS needs `NSFaceIDUsageDescription`. Add it with a Kin config plugin `apps/mobile/plugins/withKinApprovalKey.cjs` (new), listed with one line in `apps/mobile/app.config.ts`. @@ -197,7 +197,9 @@ export const KinApproverKey = Schema.Struct({ Registration: -1. The phone calls `kin.approvals.registerKey({publicJwk, platform, hardware, attestation?, deviceLabel})` over an authenticated session with `access:write`. The server stores it as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`. +1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`. + - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with a signing-certificate SHA-256 on the server's allowlist. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. + - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. 3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. 4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. @@ -206,7 +208,7 @@ A key's role isn't stored on the key. It is read at verify time from org members ### 5. `KinGrant`: format and checks -The grant is a compact JWS: `b64url(header).b64url(payload).b64url(sig)`, ES256, payload bytes = `stableStringify(payload)`. +The grant is a compact JWS: `b64url(header).b64url(payload).b64url(sig)`, ES256, with header bytes = `stableStringify(header)` and payload bytes = `stableStringify(payload)` (`packages/shared/src/relaySigning.ts`), and `b64url` unpadded. The signing input is the ASCII string `b64url(header).b64url(payload)`. The header has exactly the three fields below; `target` is encoded with its `_tag`. `headSha` is present for `merge_pull_request` and `delete_branch` and absent otherwise; `base` and `mergeMethod` are present for `merge_pull_request` only, and `mergeMethod` equals `target.mergeMethod`. ```ts export const KinGrantHeader = Schema.Struct({ @@ -238,11 +240,13 @@ export const KinGrantPayload = Schema.Struct({ **The card is drawn from the payload it signs.** `kin.approvals.challenge(actionId)` returns the unsigned payload (minus `jti`, `iat`, `exp`, which the device adds). The app parses it and renders repo, PR, SHA, base, method, diff size and checks from those fields and `resolved`, then signs the same bytes. There is no second copy of the facts that could drift from what is signed. +**The device checks what it signs.** The approval key module parses the signing input natively before it asks for a biometric, and refuses it unless: both parts are canonical `stableStringify` JSON (no whitespace, sorted keys, so no duplicate keys); the header has exactly `alg: "ES256"`, `typ: "kin-grant+jws"` and a `kid`; the payload has only the fields above, with `v: 1`, `decision: "approve"`, a `kind` the module has a prompt for, the matching `target` tag, `approver.kid` equal to the header `kid` byte for byte, `exp − iat ≤ 900` and `|deviceNow − iat| ≤ 300`. The prompt text comes from fixed per-kind templates in the module, such as `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing`, with the first 16 characters of every hash. Shown values are refused, never cleaned, unless they are ASCII from a per-field allowlist (branches and paths: letters, digits, `. _ - / +`; lead and chat ids: letters, digits, `. _ -`), and a prompt over 200 characters is refused rather than cut. A kind with no template can't be signed until the module adds one. The server's checks below still apply in full. + `kin.approvals.submitGrant({compact})` checks, in this order, and stops at the first failure with a typed reason: -1. Decode header and payload; `alg`, `typ`, no `jwk` → `malformed`. -2. `kid` is an `active` key in `payload.orgId` → `unknown_key` / `revoked_key`. -3. Signature verifies with `p256.verify(sig, sha256(signingInput), key, {prehash: false, format: "compact"})`, as `verifyDpopProof` does → `bad_signature`. +1. Decode header and payload; `alg`, `typ`, no `jwk`; each part's bytes equal `stableStringify(JSON.parse(bytes))` → `malformed`. +2. `kid` is an `active` key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. +3. Signature verifies with `p256.verify(sig, sha256(signingInput), key, {prehash: false, format: "compact", lowS: true})` → `bad_signature`. Unlike `verifyDpopProof`, `lowS: true` is required: the device always sends low-S, and ECDSA's `(r, n − s)` twin of a signature would otherwise also verify. Never identify or deduplicate a grant by its compact string; `jti` is its identity, and `compact` is kept for audit only. 4. `approver.humanId` equals the key's `humanId`, and that person currently meets a `requiredApprovers` entry (phase 1: holds the owner role in the org) → `not_owner`. 5. The RPC caller's session is the session the key was registered from, or another session of the same person → `session_mismatch`. (Defence in depth; the signature is the real check.) 6. Pending action exists in the org, is `awaiting_approval`, and `revision` and `nonce` match → `stale` (the card refreshes). @@ -319,8 +323,8 @@ export const KinProvenance = Schema.Struct({ - Apps render the card natively from `kin.approvals.get(actionId)`. The server projects per viewer: - **Owner:** full facts, `canApprove: true`, shown in **Waiting on you** and the direct chat. - **Anyone else:** `{repo, number, title, state, waitingOn: "Nishchay"}`, `canApprove: false`, no challenge. `kin.approvals.challenge` and `submitGrant` refuse non-owners with `not_owner` anyway. -- The card shows repo, PR number and title, head SHA (first 7, full on tap), base ← head, method, `+additions −deletions` and file count, required checks with status, the agent's reason as a quote, and the provenance warning. -- Approve: biometric prompt with the text "Merge GLDRoger/t3code #212 (abc1234) into main" → sign → submit. Notification and lock-screen actions open the app to this card; nothing is signed in the background. +- The card shows repo, PR number and title, head SHA (first 16, full on tap), base ← head, method, `+additions −deletions` and file count, required checks with status, the agent's reason as a quote, and the provenance warning. +- Approve: the approval key module shows the grant's own text, written natively from the signed payload (section 5): `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing` → biometric → sign → submit. Android shows it in the `BiometricPrompt`. Face ID mostly ignores the prompt's reason text, so on Face ID iPhones the module first shows it in a native confirmation sheet, in its own window above the app's; Approve refuses to sign (`E_OBSCURED`) unless that window is key and nothing covers it. Touch ID shows it in the system prompt. Notification and lock-screen actions open the app to this card; nothing is signed in the background, and the module signs one grant at a time. - Desktop and web show the card read-only with "Approve on your phone" in phase 1. ### 10. GitHub: the bot App, the owner's review, rulesets @@ -433,6 +437,8 @@ At startup and hourly, the executor checks which GitHub identity T3 itself uses | Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | | Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | | Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | +| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | +| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | | Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | | Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | | Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | @@ -442,6 +448,10 @@ At startup and hourly, the executor checks which GitHub identity T3 itself uses | Workflow exfiltration | Worker adds a workflow that prints secrets | App has no Workflows permission | | Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | +Tampered JS delivered over the air is the attacker the native sheet and grant parser defend against, so release builds must set `updates.codeSigningCertificate` for `expo-updates`. + +`deleteKey` needs no biometric, so tampered JS can delete the approval key. That is an accepted denial of service: registering a new key needs a fresh session challenge, attestation on Android, and the owner's confirmation. + ## Files New (Kin-owned): @@ -464,7 +474,7 @@ Upstream hooks (one line each): - HTTP route for `/kin/mcp` — the same router hook the chat spec uses for Kin routes. - `apps/mobile/app.config.ts` — `"./plugins/withKinApprovalKey.cjs",` in `plugins`. -RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read`; `challenge`, `submitGrant`, `reject` → `orchestration:operate`; `registerKey`, `confirmKey`, `listKeys`, `revokeKey`, `kin.audit.list`, `kin.audit.verify` → `access:write`. Scopes are only the outer gate; the person and signature checks above are the real ones. +RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read`; `challenge`, `submitGrant`, `reject` → `orchestration:operate`; `keyChallenge`, `registerKey`, `confirmKey`, `listKeys`, `revokeKey`, `kin.audit.list`, `kin.audit.verify` → `access:write`. Scopes are only the outer gate; the person and signature checks above are the real ones. ## Interfaces to other specs @@ -496,7 +506,7 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read 19. `the merge token is never written to logs, audit, env or child processes` — grep the captured logs and spawned env in an integration test. 20. `the audit chain detects an edited row` (`kin.audit.verify`). 21. `the first approver key can't be confirmed from a remote session`. -22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`. +22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`. The module's README has the checklist; its grant parser's vectors run without a device. 23. GitHub (`scripts/kin-rulesets.ts --check`, run against a scratch repo): `the owner merge token can't submit a review` (expect 403), `the bot can't merge to main` and `a merge without a code-owner review is blocked`. Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot PR; the owner approves on the phone with Face ID; the GitHub review lands from the phone; the executor merges with the pinned SHA; the audit lists grant, device, SHA, provenance and merge commit. Tests 1–21 pass in CI; 22–23 pass on the release checklist. diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 7fb352ed1871c..02a2e887a5456 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -238,7 +238,7 @@ Every screen handles the same seven states. Each state's copy is fixed below. 3. `prTitle` on its own line, plain text, limited to 2 lines. 4. Facts list, one line each: - Repository: `GLDRoger/t3code` - - Commit: first 7 characters of `headSha`, with the full SHA in the accessibility label and on long-press copy + - Commit: first 16 characters of `headSha`, with the full SHA in the accessibility label and on long-press copy - Merge method: Squash - Changes: 4 files, +120 −30 - Checks: 12 passed, 0 failed, 1 pending, with each required check underneath diff --git a/knip.jsonc b/knip.jsonc index ed4bf19129645..fc1297b4388d3 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -115,6 +115,8 @@ "scripts/generate-device-stream.mts", "src/features/devices/device-stream.browser.ts!", "src/features/browser/preview-stream.browser.ts!", + // Kin's approval key has no importer until APPR-7's approval flow. + "modules/kin-approval-key/index.ts!", ], // Fonts are configured as asset paths; Expo autolinks the native packages. "ignoreDependencies": [ From 789035c9a45b74686f0db3cc744eaa6a1dc82355 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:05:28 +0530 Subject: [PATCH 2/9] fix(kin): arm the Face ID sheet and attest iOS approval keys Approve now ignores taps until the confirmation sheet has been key and uncovered for 0.7 s in a row, so a double tap or a cover hidden after the first tap can't land on it. Keyboard visibility comes from notifications, invisible and empty windows are skipped, keyboard host windows count only while they hold app views, and a sheet left without a key window takes key back instead of failing. createKey on iOS now returns an App Attest attestation over sha256(challenge || the new Secure Enclave public key), computed natively, with the entitlement added by the config plugin. register_approver_key targets carry hardware and attested: true. The spec requires the server to verify App Attest per Apple's steps, never activate an unattested key, and close the Android attestation gaps; it states that Kin ships with OTA updates off. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/app.config.ts | 11 +- .../mobile/modules/kin-approval-key/README.md | 45 ++++-- .../expo/modules/kinapprovalkey/KinGrant.java | 21 ++- .../fixtures/grant-vectors.json | 52 ++++++- .../modules/kin-approval-key/index.test.ts | 70 ++++++++- apps/mobile/modules/kin-approval-key/index.ts | 64 ++++++-- .../ios/ConfirmationSheet.swift | 144 +++++++++++++++--- .../ios/KinApprovalKey.podspec | 2 +- .../ios/KinApprovalKeyModule.swift | 56 ++++++- .../kin-approval-key/ios/KinGrant.swift | 16 +- apps/mobile/plugins/withKinApprovalKey.cjs | 21 ++- docs/kin/specs/approvals.md | 71 +++++---- docs/kin/specs/mobile.md | 2 +- 13 files changed, 466 insertions(+), 109 deletions(-) diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 7b25a0daa54b0..c37307ce928a8 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -454,7 +454,16 @@ const config: ExpoConfig = { "./plugins/withAndroidModernAlertDialog.cjs", "./plugins/withAndroidPredictiveBackCompat.cjs", "./plugins/withAndroidTabletOrientation.cjs", - "./plugins/withKinApprovalKey.cjs", + [ + "./plugins/withKinApprovalKey.cjs", + { + appAttestEnvironment: isIosPersonalTeamBuild + ? null + : APP_VARIANT === "development" + ? "development" + : "production", + }, + ], ...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []), ], extra: { diff --git a/apps/mobile/modules/kin-approval-key/README.md b/apps/mobile/modules/kin-approval-key/README.md index b123bcb99a1e6..580b905da93eb 100644 --- a/apps/mobile/modules/kin-approval-key/README.md +++ b/apps/mobile/modules/kin-approval-key/README.md @@ -6,12 +6,12 @@ This key only signs grants. It is separate from the relay DPoP key in `src/featu ## API (`index.ts`) -| Call | Result | -| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `createKey(attestationChallenge)` | `{ publicJwk, hardware, attestation? }`. `attestationChallenge` is the server's registration nonce, unpadded base64url of 16 to 128 bytes. On Android, `attestation.certificateChain` is the Keystore chain (leaf first, base64 DER) with the nonce bound in; iOS has no attestation. Fails with `E_KEY_EXISTS` if a key is already there. | -| `sign(signingInput)` | `signingInput` is a grant's JWS signing input, `b64url(header).b64url(payload)`. The module refuses it unless it is a well-formed grant, shows the user what it approves, takes a biometric, and signs the ASCII bytes with ES256. Returns the 64-byte low-S `r‖s` as base64url, the JWS's third part. | -| `hasKey()` | Whether a key exists. This never prompts. See the device tests for what it returns after invalidation. | -| `deleteKey()` | Removes the key. Does nothing if there isn't one. | +| Call | Result | +| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `createKey(attestationChallenge)` | `{ publicJwk, hardware, attestation? }`. `attestationChallenge` is the server's registration nonce, unpadded base64url of 16 to 128 bytes. On Android, `attestation` is `{ format: "android-key", certificateChain }`, the Keystore chain (leaf first, base64 DER) with the nonce bound in. On iOS it is `{ format: "apple-app-attest", keyId, attestationObject }` (both base64), an App Attest attestation over `sha256(challenge ‖ public key)`. No `attestation` means the device can't attest; the server won't activate that key. Fails with `E_KEY_EXISTS` if a key is already there. | +| `sign(signingInput)` | `signingInput` is a grant's JWS signing input, `b64url(header).b64url(payload)`. The module refuses it unless it is a well-formed grant, shows the user what it approves, takes a biometric, and signs the ASCII bytes with ES256. Returns the 64-byte low-S `r‖s` as base64url, the JWS's third part. | +| `hasKey()` | Whether a key exists. This never prompts. See the device tests for what it returns after invalidation. | +| `deleteKey()` | Removes the key. Does nothing if there isn't one. | ### What the user sees @@ -24,7 +24,7 @@ The caller doesn't choose the approval text. `ios/KinGrant.swift` and `android/. | `set_level` | Set lead "tech-lead" to L2 in chat "chat_7" (or "in all chats") | | `change_rules` | Change rules to "rules.md" (sha256 9f86d081884c7d65) | | `memory_purge` | Purge memory using "purge/item-4.json" (sha256 9f86d081884c7d65) | -| `register_approver_key` | Add approver key NzbLsXh8uDCcd-6M | +| `register_approver_key` | Add approver key NzbLsXh8uDCcd-6M (Secure Enclave, attested) | Every hash shows its first 16 characters. A shown value is never cleaned or cut: the grant is refused (`E_NOT_A_GRANT`) unless each value is ASCII from its field's allowlist, so nothing invisible, look-alike or reordering reaches the prompt and no platform Unicode table is involved: @@ -32,6 +32,8 @@ Every hash shows its first 16 characters. A shown value is never cleaned or cut: - Branches (`base`, `ref`) and `path`: letters, digits and `. _ - / +`. That is a subset of what git allows, so a merge into a branch with other characters (non-ASCII, `@`, `#` and so on) can't be approved from the phone. - `leadId`, `chatId`: letters, digits and `. _ -`. +`register_approver_key` also needs `hardware` (`secure_enclave`, `strongbox` or `tee`) and `attested: true` in its target: the server never activates an unattested key, so there is nothing to approve for one. + None of these allow a space or a quote, so the quotes around a value in the template can't be faked. A prompt over 200 characters is refused, so the merge method and ", then delete its branch" always show. A new action kind needs a template in both parsers and new rows in `fixtures/grant-vectors.json`. The two parsers must agree; `test/native/run.sh` checks both against the vectors on a Mac with the Xcode command line tools and a JDK (no simulator or Android SDK). `src/grantVectors.test.ts` checks in CI that the accepted vectors are exactly what `stableStringify` writes. @@ -55,13 +57,19 @@ Error codes on rejected promises: - `E_USER_CANCELED`: the user canceled, chose the fallback, or the app left the foreground mid-approval. - `E_AUTH_FAILED`: the biometric didn't unlock the key. - `E_NO_ACTIVITY`: the app isn't in the foreground or the device is locked, so nothing can be shown. -- `E_OBSCURED` (Face ID): Approve was tapped while something could cover the confirmation sheet: its window wasn't key, another window was at its level or above, or a view or screen was on top of it. Nothing is signed. +- `E_OBSCURED` (Face ID): Approve was tapped while something covered the confirmation sheet, after it had been clear for the arming delay. Nothing is signed. See the confirmation sheet below for what counts. +- `E_ATTESTATION_FAILED` (iOS): App Attest returned an error other than "unsupported", for example while offline. The new key is deleted, so `createKey` can be called again. - `E_INVALID_INPUT`, `E_KEYCHAIN`, `E_KEYSTORE`. ## Platform notes - **iOS:** the key is created with `SecKeyCreateRandomKey` and `kSecAttrTokenIDSecureEnclave`, gated by `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` with `[.privateKeyUsage, .biometryCurrentSet]`. It signs with `.ecdsaSignatureMessageX962SHA256` on the module's own `kin.approval-key` queue, so an open prompt never blocks Expo's shared queue. The queue is concurrent on purpose: `SecKeyCreateSignature` blocks its thread while Face ID is up, and a serial queue would hold a second call until the first finished and then show a second prompt, instead of rejecting it with `E_BUSY`. Each signature uses a fresh `LAContext` with `localizedFallbackTitle = ""`, so no earlier match is reused and there is no "Enter Password" button. `NSFaceIDUsageDescription` comes from `plugins/withKinApprovalKey.cjs`. -- **iOS confirmation sheet (Face ID, Optic ID):** `ios/ConfirmationSheet.swift` shows the grant text in a window the module owns, at `windowLevel = .alert + 1` in the foreground scene, so views the app's JS can add to its own window (a `FullWindowOverlay`, a modal) sit below it. It ends editing first, since a keyboard's input accessory view would sit above every app window. When Approve is tapped, it signs only if the sheet's window is key and visible, no other visible window in the scene is at its level or above, and nothing has been added or presented over the card; otherwise `E_OBSCURED`. The window is removed on every outcome. Cancel, the sheet disappearing without a choice, or the scene going to the background reject with `E_USER_CANCELED`. +- **iOS confirmation sheet (Face ID, Optic ID):** `ios/ConfirmationSheet.swift` shows the grant text in a window the module owns, at `windowLevel = .alert + 1` in the foreground scene, so views the app's JS can add to its own window (a `FullWindowOverlay`, a modal) sit below it. It ends editing first, since a keyboard's input accessory view would sit above every app window. + - **Arming.** Approve shows disabled and ignores taps until the sheet has been key and uncovered for 0.7 s in a row. The delay restarts when the sheet appears, when its window becomes or stops being key, when the scene activates or deactivates, when the keyboard hides, and whenever a check finds the sheet covered. So JS can't draw a button where Approve will appear and catch the second tap of a double tap, or hide a cover just after the first tap. + - **Covered** means: the keyboard is up (tracked by `keyboardWillShow` and `keyboardDidHide`), a controller is presented over the sheet (RN's `Alert`), another window in the scene at its level or above is visible, or a view of the app's own classes sits over the card in the sheet's window. Windows that are hidden, have alpha 0 or have no subviews are skipped: they aren't drawn or hit-tested, and JS draws only with views. The keyboard's host windows (`UIRemoteKeyboardWindow`, `UITextEffectsWindow`) outlive the keyboard, so they count only while they hold app views (an `InputAccessoryView` or an `OverKeyboardView` left behind). UIKit's own views in the sheet's window, such as the iPad pointer-hover container, are skipped the same way. + - **Not key** (RN's `Alert.hide()` leaves no key window): the sheet calls `makeKey()` and the delay starts over, instead of failing. + - A tap that reaches an armed Approve while the sheet is covered rejects with `E_OBSCURED`. The window is removed on every outcome. Cancel, the sheet disappearing without a choice, or the scene going to the background reject with `E_USER_CANCELED`. +- **iOS App Attest:** after making the Secure Enclave key, `createKey` makes a fresh App Attest key with `DCAppAttestService` and attests it over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the key it just made. JS passes only the server's challenge, so it can't get an attestation over a key or data of its own. Where App Attest isn't supported (simulator, older devices, or `DCError.featureUnsupported`), there is no `attestation`. The entitlement `com.apple.developer.devicecheck.appattest-environment` comes from `plugins/withKinApprovalKey.cjs`: `development` for development builds, `production` otherwise, and none for personal-team builds. - **iOS re-enrolment:** `createKey` stores `LAContext.domainState.biometry.stateHash` in the keychain (this device only, never exported). A failed signature reports `E_KEY_INVALIDATED` rather than `E_AUTH_FAILED` when the stored hash differs from the current one. A mismatch alone never blocks signing, because Apple warns the hash can change across major OS versions with no enrolment change; after a successful signature, the stored hash is refreshed. - **Android:** an EC `secp256r1` key with `PURPOSE_SIGN` and `DIGEST_SHA256`, `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)` and `setInvalidatedByBiometricEnrollment(true)`. It tries StrongBox first and falls back to the TEE only on a `ProviderException` (which includes `StrongBoxUnavailableException`). After creation it checks `KeyInfo`: secure hardware, strong-biometric-only, per-use, invalidated by enrolment. Parsing and `Signature.initSign` run off the main thread; `BiometricPrompt` runs on it with a `CryptoObject(Signature)`, and the callback signs only if it gets back that exact `Signature`. The prompt is canceled if the activity stops, and after 300 seconds (the grant would be stale to the server by then). - **Android limitation:** `androidx.biometric` keeps one callback per activity, so a second `BiometricPrompt` made on the same activity while ours is open (by other code in the app) replaces our callback, and there's no public API to notice. Our call then settles only when the activity stops or the 300-second timeout fires, and until then `sign` returns `E_BUSY`. It can never sign the other prompt's operation, because the callback signs only its own `Signature`. Canceling on timeout can close the other prompt too. The module depends on `androidx.biometric:biometric:1.1.0`, the latest stable release. @@ -91,7 +99,7 @@ console.log(`${b(header)}.${b(payload)}`); ### 1. Signing without biometrics fails -1. Call `createKey()`. Check that `hardware` is `secure_enclave` on iOS and `strongbox` on the Pixel (`tee` if StrongBox is unavailable). On Android, check that `attestation.certificateChain` has at least 2 entries. +1. Call `createKey()`. Check that `hardware` is `secure_enclave` on iOS and `strongbox` on the Pixel (`tee` if StrongBox is unavailable). On Android, check that `attestation.certificateChain` has at least 2 entries; on iOS, that `attestation.format` is `apple-app-attest`. In airplane mode, iOS rejects with `E_ATTESTATION_FAILED` and `hasKey()` is then `false`. 2. Call `sign()`. **The prompt shows `Merge GLDRoger/t3code #212 (a1b2c3d000000000) into "main" by squashing`**: in the confirmation sheet on Face ID, in the system prompt on Touch ID and Android. Pass the biometric check. It resolves to an 86-character base64url string (64 bytes). 3. Call `sign` again and **cancel** the prompt (and, on Face ID, the sheet). It rejects with `E_USER_CANCELED`. 4. Call `sign` again and fail the biometric 5 times (cover the camera, or use an unenrolled finger). It rejects with `E_AUTH_FAILED` or `E_BIOMETRY_LOCKOUT`, and never resolves. @@ -107,15 +115,23 @@ console.log(`${b(header)}.${b(payload)}`); 1. Call `sign(inputA)` and, while its prompt is up, `sign(inputB)` with a different `number`. The second rejects at once with `E_BUSY`, and only one prompt is ever shown. Approve it: the first resolves, and its signature verifies for `inputA` only (section 4 below), never for `inputB`. 2. Call `sign` and send the app to the background while the prompt (or the Face ID sheet) is up. It rejects with `E_USER_CANCELED`. Bring the app back: no prompt is left, the promise never resolves later, and the next `sign` works (it doesn't get `E_BUSY`). 3. Call `sign` from a timer while the app is in the background, and again while the phone is locked. Both reject (`E_NO_ACTIVITY` expected) without showing a prompt or signing. -4. Android: call `sign` and, while its prompt is up, start a second `BiometricPrompt` on the activity (for example `expo-local-authentication`'s `authenticateAsync`). Pass that one. Our call doesn't resolve; it rejects with `E_USER_CANCELED` when the app goes to the background or 300 seconds after the prompt opened, and the next `sign` works. +4. Android, on a phone with an in-display fingerprint sensor: rest a finger on the sensor, then call `sign` from a timer. The prompt shows the grant text and doesn't sign from the finger that was already there; it signs only after you lift and touch again (record what happens). +5. Android: call `sign` and, while its prompt is up, start a second `BiometricPrompt` on the activity (for example `expo-local-authentication`'s `authenticateAsync`). Pass that one. Our call doesn't resolve; it rejects with `E_USER_CANCELED` when the app goes to the background or 300 seconds after the prompt opened, and the next `sign` works. ### 2a. An overlay over the sheet can't approve (Face ID) 1. Render a `FullWindowOverlay` (react-native-screens) with `pointerEvents="none"` and an opaque box over the middle of the screen, then call `sign`. The sheet shows above the box, its text readable. Approve signs. 2. Mount the same overlay from a timer 2 seconds after calling `sign`, while the sheet is up. It still appears below the sheet. Approve signs. -3. While the sheet is up, focus a `TextInput` that has an `InputAccessoryView` with an opaque box, from a timer. If the keyboard or its accessory comes up over the sheet, Approve rejects with `E_OBSCURED` and nothing is signed. +3. While the sheet is up, focus a `TextInput` that has an `InputAccessoryView` with an opaque box, from a timer. While the keyboard or its accessory is up, Approve shows disabled and taps do nothing. Dismiss it: Approve enables 0.7 s later and signs. 4. While the sheet is up, call `Alert.alert` from a timer. Dismiss that alert, then tap Approve: it signs, and only the grant's text was ever on the sheet. 5. Type in a `TextInput` and leave the keyboard open, then call `sign`. The keyboard closes, the sheet shows, and Approve signs (no `E_OBSCURED`). Repeat after the keyboard has been dismissed. +6. **Double tap.** Draw a JS button where Approve will appear whose `onPressIn` calls `sign`. Double-tap it quickly. The sheet shows with Approve disabled, the second tap does nothing, and nothing is signed until Approve enables and is tapped again. Repeat with a triple tap. +7. **Cover, then uncover.** While the sheet is up, put an opaque box over Approve two ways: an `OverKeyboardView` (react-native-keyboard-controller), and an `InputAccessoryView` on a `TextInput` focused from a timer. Hide each from its own `onPressIn`. Tap the box: nothing is signed, and Approve enables only 0.7 s after the box is gone. Then open the keyboard, mount the `OverKeyboardView` and call `sign`: the keyboard closes, the view is left in the keyboard's window, and Approve stays disabled until the view is removed. +8. **Alert, then no key window.** Call `Alert.alert` from a timer while the sheet is up, then dismiss it. Approve enables within about a second and signs (the sheet takes key back), with no `E_OBSCURED`. +9. **iPad pointer.** With a trackpad or mouse, hover over Approve until the pointer highlights it, then click. It signs (no `E_OBSCURED`, Approve not stuck disabled). +10. **VoiceOver.** Turn VoiceOver on and call `sign`. The grant text is read, Approve is announced dimmed until it arms, and double-tapping it then signs. **Full Keyboard Access:** on an iPad with a hardware keyboard, Tab to Approve and press Space; the same. +11. **Stage Manager and Split View (iPad).** Call `sign` with Kin in Split View, then in Stage Manager overlapped by another app's window. Tap the other app, then back into Kin's sheet: Approve is disabled for 0.7 s after Kin's window becomes key again, then signs. Record whether the other app's window can cover the sheet while Approve is armed. +12. **Picture in picture.** Start a video in picture in picture (from Safari or the app), drag it over the sheet's text and tap Approve. Record whether the sheet notices; the PiP window belongs to the system, so the module can't see it. ### 3. Re-enrolling biometrics invalidates the key @@ -147,10 +163,11 @@ console.log(`${b(header)}.${b(payload)}`); 4. Repeat steps 2 and 3 twenty times on each device. Roughly half the raw signatures have a high-bit `r` or `s` (a 33-byte DER INTEGER) and half have a high `s`, so this covers the sign-byte and low-S paths on real hardware. -### 5. Attestation (Android) +### 5. Attestation 1. Call `createKey()` with a recorded 32-byte nonce and save `attestation.certificateChain`. -2. Check it offline: the root is a Google hardware attestation root; the leaf's public key equals `publicJwk`; the KeyDescription's `attestationChallenge` is the nonce; the attestation and KeyMint security levels are `StrongBox` on the Pixel (`TrustedEnvironment` on TEE devices); `hardwareEnforced` has purpose `SIGN`, EC P-256, SHA-256, a biometric `userAuthType`, and no `authTimeout` or `noAuthRequired`. Record the tool and its output. +2. Android: check it offline: the root is a Google hardware attestation root; the leaf's public key equals `publicJwk`; the KeyDescription's `attestationChallenge` is the nonce; the attestation and KeyMint security levels are `StrongBox` on the Pixel (`TrustedEnvironment` on TEE devices); `hardwareEnforced` has purpose `SIGN`, EC P-256, SHA-256, a biometric `userAuthType`, and no `authTimeout` or `noAuthRequired`. Record the tool and its output. +3. iOS: save `attestation.keyId` and `attestation.attestationObject` and check them offline per Apple's steps (approvals spec, section 4): the `x5c` chain verifies to the Apple App Attest root; the nonce extension equals `sha256(authData ‖ sha256(nonce ‖ 0x04 ‖ x ‖ y))` from `publicJwk`; the RP ID hash is `sha256(".")`; the counter is 0; the aaguid is `appattestdevelop` on a development build. Record the tool and its output. ### 6. Reinstall and restore diff --git a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java index 8d699de7a7de4..0bf556c725356 100644 --- a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java +++ b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java @@ -142,9 +142,13 @@ private static String promptFor(Map p, String kid, long now) thr } case "register_approver_key": { only(p); - exactKeys(target, setOf("_tag", "thumbprint"), setOf(), "target"); + exactKeys(target, setOf("_tag", "thumbprint", "hardware", "attested"), setOf(), "target"); tag(target, "device_key"); - text = "Add approver key " + matches(target, "thumbprint", THUMBPRINT).substring(0, SHOWN_HASH_LENGTH); + String thumbprint = matches(target, "thumbprint", THUMBPRINT); + // The server never activates an unattested key, so there is nothing to approve for one. + if (!Boolean.TRUE.equals(target.get("attested"))) throw new NotAGrantException("the key is not attested"); + text = "Add approver key " + thumbprint.substring(0, SHOWN_HASH_LENGTH) + + " (" + hardwareWords(string(target, "hardware")) + ", attested)"; break; } default: @@ -170,6 +174,19 @@ private static void githubRepo(Map target) throws NotAGrantExcep matches(target, "repo", REPO); } + private static String hardwareWords(String hardware) throws NotAGrantException { + switch (hardware) { + case "secure_enclave": + return "Secure Enclave"; + case "strongbox": + return "StrongBox"; + case "tee": + return "TEE"; + default: + throw new NotAGrantException("hardware is not secure_enclave, strongbox or tee"); + } + } + private static String methodWords(String method) throws NotAGrantException { switch (method) { case "merge": diff --git a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json index 32efb28ed0a61..87db8c84a1c3e 100644 --- a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json +++ b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json @@ -208,8 +208,56 @@ { "name": "register an approver key", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"secure_enclave\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Add approver key NzbLsXh8uDCcd-6M (Secure Enclave, attested)" + }, + { + "name": "register a StrongBox approver key", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"strongbox\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Add approver key NzbLsXh8uDCcd-6M (StrongBox, attested)" + }, + { + "name": "register a TEE approver key", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"tee\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "prompt": "Add approver key NzbLsXh8uDCcd-6M (TEE, attested)" + }, + { + "name": "an unattested approver key is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":false,\"hardware\":\"secure_enclave\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "a software approver key is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"software\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "an approver key with attested as a string is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":\"true\",\"hardware\":\"secure_enclave\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "an approver key without hardware is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "an approver key without attested is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"hardware\":\"tee\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "error": "E_NOT_A_GRANT" + }, + { + "name": "an approver key with only a thumbprint is refused", + "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"thumbprint\":\"NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", - "prompt": "Add approver key NzbLsXh8uDCcd-6M" + "error": "E_NOT_A_GRANT" }, { "name": "escapes decode in a field that isn't shown", @@ -495,7 +543,7 @@ { "name": "short thumbprint", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"thumbprint\":\"abc\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"register_approver_key\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"device_key\",\"attested\":true,\"hardware\":\"secure_enclave\",\"thumbprint\":\"abc\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" }, { diff --git a/apps/mobile/modules/kin-approval-key/index.test.ts b/apps/mobile/modules/kin-approval-key/index.test.ts index fa6f7ebe55ce8..61ca29c2bc97a 100644 --- a/apps/mobile/modules/kin-approval-key/index.test.ts +++ b/apps/mobile/modules/kin-approval-key/index.test.ts @@ -8,12 +8,14 @@ import { MalformedDerSignatureError } from "./src/derSignature"; const mocks = vi.hoisted(() => ({ signDer: vi.fn<(signingInput: string) => Promise>(), - createKey: - vi.fn< - ( - challenge: string, - ) => Promise<{ publicKey: string; hardware: "tee"; attestationChain: string[] }> - >(), + createKey: vi.fn< + (challenge: string) => Promise<{ + publicKey: string; + hardware: "tee" | "secure_enclave"; + attestationChain?: string[]; + appAttest?: { keyId: string; attestationObject: string }; + }> + >(), })); vi.mock("expo", () => ({ @@ -83,4 +85,60 @@ describe("createKey", () => { await expect(createKey(challenge)).rejects.toThrow("attestationChallenge"); expect(mocks.createKey).not.toHaveBeenCalled(); }); + + const challenge = b64(new Uint8Array(32).fill(7)); + const point = p256.getPublicKey(p256.utils.randomPrivateKey(), false); + const keyId = Buffer.alloc(32, 1).toString("base64"); + + it.each([ + [ + "an App Attest object", + { appAttest: { keyId, attestationObject: "o2NmbXQ=" } }, + { + attestation: { format: "apple-app-attest", keyId, attestationObject: "o2NmbXQ=" }, + }, + ], + [ + "a Keystore chain", + { attestationChain: ["MIIB", "MIIC"] }, + { + attestation: { format: "android-key", certificateChain: ["MIIB", "MIIC"] }, + }, + ], + ["no attestation", {}, {}], + ])("returns %s as the attestation", async (_name, native, expected) => { + setup(); + mocks.createKey.mockResolvedValueOnce({ + publicKey: b64(point), + hardware: "secure_enclave", + ...native, + }); + const created = await createKey(challenge); + expect(mocks.createKey).toHaveBeenCalledWith(challenge); + expect({ ...created, publicJwk: undefined }).toEqual({ + publicJwk: undefined, + hardware: "secure_enclave", + ...expected, + }); + }); + + it.each([ + [ + "a keyId that isn't 32 bytes", + { keyId: Buffer.alloc(16).toString("base64"), attestationObject: "o2NmbXQ=" }, + ], + [ + "a base64url keyId", + { keyId: Buffer.alloc(32, 0xff).toString("base64url"), attestationObject: "o2NmbXQ=" }, + ], + ["an empty attestation object", { keyId, attestationObject: "" }], + ])("refuses an App Attest result with %s", async (_name, appAttest) => { + setup(); + mocks.createKey.mockResolvedValueOnce({ + publicKey: b64(point), + hardware: "secure_enclave", + appAttest, + }); + await expect(createKey(challenge)).rejects.toThrow(); + }); }); diff --git a/apps/mobile/modules/kin-approval-key/index.ts b/apps/mobile/modules/kin-approval-key/index.ts index c3c019d94fe7b..24aa924b132a7 100644 --- a/apps/mobile/modules/kin-approval-key/index.ts +++ b/apps/mobile/modules/kin-approval-key/index.ts @@ -1,4 +1,5 @@ import type { DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Base64 from "effect/encoding/Base64"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Result from "effect/Result"; import { requireOptionalNativeModule } from "expo"; @@ -23,15 +24,25 @@ export type KinApprovalKeyErrorCode = | "E_NOT_A_GRANT" | "E_NO_ACTIVITY" | "E_OBSCURED" + | "E_ATTESTATION_FAILED" | "E_INVALID_INPUT" | "E_KEYCHAIN" | "E_KEYSTORE"; -export interface KinApprovalKeyAttestation { - readonly format: "android-key"; - /** Leaf first, base64 (not base64url) DER, as in a JWS `x5c`. */ - readonly certificateChain: ReadonlyArray; -} +export type KinApprovalKeyAttestation = + | { + readonly format: "android-key"; + /** Leaf first, base64 (not base64url) DER, as in a JWS `x5c`. */ + readonly certificateChain: ReadonlyArray; + } + | { + /** Its client data hash is `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the new key. */ + readonly format: "apple-app-attest"; + /** Base64: the SHA-256 of the App Attest key's public key. */ + readonly keyId: string; + /** Base64 CBOR attestation object from `DCAppAttestService.attestKey`. */ + readonly attestationObject: string; + }; export interface KinApprovalKey { readonly publicJwk: DpopPublicJwk; @@ -44,6 +55,7 @@ interface NativeKinApprovalKey { readonly publicKey: string; readonly hardware: KinApprovalKeyHardware; readonly attestationChain?: ReadonlyArray; + readonly appAttest?: { readonly keyId: string; readonly attestationObject: string }; }>; signDer(signingInput: string): Promise; hasKey(): Promise; @@ -62,6 +74,32 @@ function native(): NativeKinApprovalKey { return module; } +const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const APP_ATTEST_KEY_ID_BYTES = 32; + +function decodeBase64(value: unknown, label: string): Uint8Array { + const decoded = + typeof value === "string" && BASE64.test(value) ? Base64.decode(value) : undefined; + if (!decoded || Result.isFailure(decoded) || decoded.success.length === 0) + throw new Error(`${label} is not base64.`); + return decoded.success; +} + +function attestationOf(created: Awaited>) { + if (created.attestationChain) { + for (const certificate of created.attestationChain) decodeBase64(certificate, "certificate"); + return { format: "android-key", certificateChain: created.attestationChain } as const; + } + if (created.appAttest) { + const { keyId, attestationObject } = created.appAttest; + if (decodeBase64(keyId, "keyId").length !== APP_ATTEST_KEY_ID_BYTES) + throw new Error("keyId is not a SHA-256 hash."); + decodeBase64(attestationObject, "attestationObject"); + return { format: "apple-app-attest", keyId, attestationObject } as const; + } + return undefined; +} + function decodeBase64Url(value: string, label: string): Uint8Array { const decoded = BASE64URL.test(value) ? Base64Url.decode(value) : undefined; if (!decoded || Result.isFailure(decoded)) throw new Error(`${label} is not base64url.`); @@ -69,10 +107,9 @@ function decodeBase64Url(value: string, label: string): Uint8Array { } /** - * Creates the device's approval key in the Secure Enclave or Android Keystore. Fails with - * `E_KEY_EXISTS` rather than replacing a key the server may already trust. - * `attestationChallenge` is the server's registration nonce as unpadded base64url of 16 to 128 - * bytes. Android binds it into the attestation chain; iOS has no attestation yet and ignores it. + * Creates the approval key; `E_KEY_EXISTS` rather than replacing one the server may trust. + * `attestationChallenge` is the server's nonce (base64url, 16 to 128 bytes), bound into the + * Keystore chain or App Attest client data. No `attestation`: the server won't activate the key. */ export async function createKey(attestationChallenge: string): Promise { const challenge = decodeBase64Url(attestationChallenge, "attestationChallenge"); @@ -80,13 +117,8 @@ export async function createKey(attestationChallenge: string): Promise Void)? + private var armedAt = CFTimeInterval.infinity + private var keyboardVisible = false /// Shows the sheet at once. `onOutcome` is called exactly once, after the sheet is gone. init(scene: UIWindowScene, prompt: String, onOutcome: @escaping (Outcome) -> Void) { self.onOutcome = onOutcome previousKeyWindow = scene.keyWindow - // An input accessory view lives in the keyboard's window, above every app window. - for window in scene.windows { window.endEditing(true) } window = UIWindow(windowScene: scene) window.windowLevel = .alert + 1 controller = ConfirmationController(prompt: prompt) window.rootViewController = controller controller.onCancel = { [weak self] in self?.finish(.canceled("Approval was canceled.")) } - controller.onApprove = { [weak self] in - guard let self else { return } - finish(isUnobscured ? .approved : .obscured) - } + controller.onApprove = { [weak self] in self?.approveTapped() } + controller.onAppear = { [weak self] in self?.rearm() } controller.onDisappear = { [weak self] in self?.finish(.canceled("The confirmation sheet closed.")) } - let center = NotificationCenter.default let leaving: [(Notification.Name, AnyObject?)] = [ (UIScene.didEnterBackgroundNotification, scene), (UIScene.didDisconnectNotification, scene), (UIApplication.didEnterBackgroundNotification, nil), ] for (name, object) in leaving { - observers.append(center.addObserver(forName: name, object: object, queue: .main) { [weak self] _ in - MainActor.assumeIsolated { self?.finish(.canceled("The app left the foreground during approval.")) } - }) + observe(name, object) { $0.finish(.canceled("The app left the foreground during approval.")) } + } + let rearming: [(Notification.Name, AnyObject?)] = [ + (UIWindow.didBecomeKeyNotification, window), + (UIWindow.didResignKeyNotification, window), + (UIScene.willDeactivateNotification, scene), + (UIScene.didActivateNotification, scene), + ] + for (name, object) in rearming { observe(name, object) { $0.rearm() } } + // Before endEditing, so a keyboard that is up now reports its hide. + observe(UIResponder.keyboardWillShowNotification, nil) { sheet in + sheet.keyboardVisible = true + sheet.rearm() + } + observe(UIResponder.keyboardDidHideNotification, nil) { sheet in + sheet.keyboardVisible = false + sheet.rearm() } + // An input accessory view lives in the keyboard's window, above every app window. + for window in scene.windows { window.endEditing(true) } window.makeKeyAndVisible() } @@ -57,32 +80,108 @@ final class ConfirmationSheet { if let previousKeyWindow, !previousKeyWindow.isHidden { previousKeyWindow.makeKey() } } + private func observe(_ name: Notification.Name, _ object: AnyObject?, _ body: @escaping (ConfirmationSheet) -> Void) { + observers.append(NotificationCenter.default.addObserver(forName: name, object: object, queue: .main) { [weak self] _ in + MainActor.assumeIsolated { if let self { body(self) } } + }) + } + private func finish(_ outcome: Outcome) { guard let onOutcome else { return } close() onOutcome(outcome) } - /// Checked when Approve is tapped: this window is key and on top, and nothing sits over the card, - /// whether another window, a view added to this one (react-native-screens' FullWindowOverlay - /// joins the key window), or a controller presented over the sheet (RN's Alert presents there). - private var isUnobscured: Bool { - guard window.isKeyWindow, !window.isHidden, let scene = window.windowScene else { return false } + /// Disables Approve and starts the arming delay again. Approve enables only if the sheet is + /// still clear when the delay ends; a check that fails starts it over. + private func rearm() { + guard onOutcome != nil else { return } + let deadline = CACurrentMediaTime() + Self.armDelay + armedAt = deadline + controller.approve.isEnabled = false + DispatchQueue.main.asyncAfter(deadline: .now() + Self.armDelay) { [weak self] in + // A later rearm owns the timer. + guard let self, onOutcome != nil, armedAt == deadline else { return } + switch coverage { + case .clear: + controller.approve.isEnabled = true + case .notKey: + // RN's Alert.hide() leaves no key window. Take key back once; the delay starts over. + window.makeKey() + rearm() + case .covered: + rearm() + } + } + } + + private func approveTapped() { + // A disabled button gets no taps; this guards a tap already in flight when Approve disabled. + guard controller.approve.isEnabled, CACurrentMediaTime() >= armedAt else { return } + switch coverage { + case .clear: + finish(.approved) + case .notKey: + window.makeKey() + rearm() + case .covered: + // Clear for the whole delay and covered at the tap: something appeared over the sheet. + finish(.obscured) + } + } + + /// Whether the sheet could be covered right now: the keyboard is up, a controller is presented + /// over the sheet (RN's Alert presents there), another window is at its level or above, or + /// app-drawn views sit over the card (react-native-screens' FullWindowOverlay joins the key + /// window). + private var coverage: Coverage { + guard !window.isHidden, let scene = window.windowScene else { return .covered } + if keyboardVisible || controller.presentedViewController != nil { return .covered } let windowAbove = scene.windows.contains { other in - other !== window && !other.isHidden && other.windowLevel >= window.windowLevel + other !== window && other.windowLevel >= window.windowLevel && Self.covers(other) + } + if windowAbove { return .covered } + let views = window.subviews + guard let index = views.lastIndex(where: { $0 === controller.view }) else { return .covered } + if views[(index + 1)...].contains(where: Self.showsAppContent) { return .covered } + if controller.view.subviews.drop(while: { $0 !== controller.card }).dropFirst().contains(where: Self.showsAppContent) { + return .covered } - return !windowAbove - && window.subviews.last === controller.view - && controller.view.subviews.last === controller.card - && controller.presentedViewController == nil + return window.isKeyWindow ? .clear : .notKey } + + /// Hidden or transparent windows aren't drawn or hit-tested, and JS draws only with views, so a + /// window without subviews shows nothing it controls. Keyboard host windows outlive the keyboard, + /// which is tracked by notification instead, so they count only while they hold app views (an + /// InputAccessoryView or OverKeyboardView left behind). + private static func covers(_ other: UIWindow) -> Bool { + guard !other.isHidden, other.alpha >= 0.01, !other.subviews.isEmpty else { return false } + let name = NSStringFromClass(type(of: other)) + let keyboardHost = name.contains("RemoteKeyboardWindow") || name.contains("TextEffectsWindow") + return !keyboardHost || showsAppContent(other) + } + + /// Whether a visible part of this view tree is a class the app ships (React Native and module + /// views) rather than one of UIKit's, such as the iPad pointer-hover container. JS can only + /// draw through the app's own view classes. + private static func showsAppContent(_ view: UIView) -> Bool { + guard !view.isHidden, view.alpha >= 0.01 else { return false } + if Bundle(for: type(of: view)).bundleURL.path.hasPrefix(appBundlePath) { return true } + return view.subviews.contains(where: showsAppContent) + } + + private static let appBundlePath = Bundle.main.bundleURL.path } private final class ConfirmationController: UIViewController { var onApprove: (() -> Void)? var onCancel: (() -> Void)? + var onAppear: (() -> Void)? var onDisappear: (() -> Void)? let card = UIView() + private(set) lazy var approve = UIButton(configuration: .filled(), primaryAction: UIAction(title: "Approve") { [weak self] _ in + self?.onApprove?() + }) private let prompt: String private let scroll = UIScrollView() @@ -112,9 +211,7 @@ private final class ConfirmationController: UIViewController { let cancel = UIButton(configuration: .gray(), primaryAction: UIAction(title: "Cancel") { [weak self] _ in self?.onCancel?() }) - let approve = UIButton(configuration: .filled(), primaryAction: UIAction(title: "Approve") { [weak self] _ in - self?.onApprove?() - }) + approve.isEnabled = false let buttons = UIStackView(arrangedSubviews: [cancel, approve]) buttons.spacing = 8 buttons.distribution = .fillEqually @@ -155,6 +252,7 @@ private final class ConfirmationController: UIViewController { override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) scroll.flashScrollIndicators() + onAppear?() UIAccessibility.post(notification: .screenChanged, argument: card) } diff --git a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec index 8995267b44e74..7609f190a024b 100644 --- a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec +++ b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec @@ -9,5 +9,5 @@ Pod::Spec.new do |s| s.static_framework = true s.dependency 'ExpoModulesCore' s.source_files = '*.swift' - s.frameworks = 'CryptoKit', 'LocalAuthentication', 'Security' + s.frameworks = 'CryptoKit', 'DeviceCheck', 'LocalAuthentication', 'Security' end diff --git a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift index 06fe88d98b9cf..c08fbe35b8538 100644 --- a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift +++ b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift @@ -1,4 +1,5 @@ import CryptoKit +import DeviceCheck import ExpoModulesCore import Foundation import LocalAuthentication @@ -17,9 +18,8 @@ public class KinApprovalKeyModule: Module { public func definition() -> ModuleDefinition { Name("KinApprovalKey") - // iOS has no attestation in phase 1, so the challenge is unused here. - AsyncFunction("createKey") { (_: String) throws -> [String: Any] in - try createKey() + AsyncFunction("createKey") { (attestationChallenge: String, promise: Promise) in + createKey(attestationChallenge: attestationChallenge, promise: promise) } AsyncFunction("signDer") { (signingInput: String, promise: Promise) in @@ -40,7 +40,53 @@ public class KinApprovalKeyModule: Module { } } -private func createKey() throws -> [String: Any] { +/// Makes the Secure Enclave key, then an App Attest attestation over +/// `sha256(challenge ‖ that key's X9.63 public key)`. The module hashes the key it just made +/// itself, so JS can never get an attestation over a key or data of its own. +private func createKey(attestationChallenge: String, promise: Promise) { + let challenge: Data + let publicKey: Data + do { + challenge = try decodeChallenge(attestationChallenge) + publicKey = try createSecureEnclaveKey() + } catch { + return promise.reject(error) + } + let created: [String: Any] = ["publicKey": base64UrlEncode(publicKey), "hardware": "secure_enclave"] + let service = DCAppAttestService.shared + // Simulators and devices without App Attest: the server stores the key unattested and unusable. + guard service.isSupported else { return promise.resolve(created) } + let clientDataHash = Data(SHA256.hash(data: challenge + publicKey)) + let fail: (Error?) -> Void = { error in + if let error = error as? DCError, error.code == .featureUnsupported { return promise.resolve(created) } + // No half-made key: a retry must make and attest a fresh one. + SecItemDelete(privateKeyQuery() as CFDictionary) + SecItemDelete(biometryStateQuery() as CFDictionary) + promise.reject(ApprovalKeyException( + "E_ATTESTATION_FAILED", "App Attest couldn't attest the approval key; try again.", cause: error)) + } + service.generateKey { keyId, error in + guard let keyId else { return fail(error) } + service.attestKey(keyId, clientDataHash: clientDataHash) { attestationObject, error in + guard let attestationObject else { return fail(error) } + var result = created + result["appAttest"] = ["keyId": keyId, "attestationObject": attestationObject.base64EncodedString()] + promise.resolve(result) + } + } +} + +private func decodeChallenge(_ value: String) throws -> Data { + var base64 = value.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) + guard !value.contains("="), let data = Data(base64Encoded: base64), (16...128).contains(data.count) else { + throw ApprovalKeyException("E_INVALID_INPUT", "attestationChallenge must be base64url of 16 to 128 bytes.") + } + return data +} + +/// Returns the new key's public key in X9.63 form (`04 ‖ x ‖ y`). +private func createSecureEnclaveKey() throws -> Data { guard SecureEnclave.isAvailable else { throw ApprovalKeyException("E_NO_SECURE_HARDWARE", "This device has no Secure Enclave.") } @@ -87,7 +133,7 @@ private func createKey() throws -> [String: Any] { "E_KEYCHAIN", "Exporting the approval public key failed.", cause: error?.takeRetainedValue()) } storeBiometryState(context.domainState.biometry.stateHash) - return ["publicKey": base64UrlEncode(x963), "hardware": "secure_enclave"] + return x963 } /// One `sign` call. Only one may be in flight; every path settles its promise exactly once. diff --git a/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift b/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift index 52bd8b3f448c9..df431cb92da80 100644 --- a/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift +++ b/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift @@ -120,13 +120,16 @@ enum KinGrant { : "Purge memory using \"\(path)\" (sha256 \(hash))" case "register_approver_key": try only(p, []) - try exactKeys(target, ["_tag", "thumbprint"], [], "target") + try exactKeys(target, ["_tag", "thumbprint", "hardware", "attested"], [], "target") try tag(target, "device_key") let thumbprint = try string(target, "thumbprint").utf8 guard thumbprint.count == 43, thumbprint.allSatisfy(isBase64UrlByte) else { throw NotAGrant("thumbprint is malformed") } - text = "Add approver key \(Bytes(Array(thumbprint.prefix(shownHashLength))))" + // The server never activates an unattested key, so there is nothing to approve for one. + guard case .bool(true) = target["attested"] else { throw NotAGrant("the key is not attested") } + text = "Add approver key \(Bytes(Array(thumbprint.prefix(shownHashLength)))) " + + "(\(try hardwareWords(try string(target, "hardware"))), attested)" default: throw NotAGrant("kind has no prompt template") } @@ -156,6 +159,15 @@ enum KinGrant { } } + private static func hardwareWords(_ hardware: Bytes) throws -> String { + switch hardware { + case "secure_enclave": return "Secure Enclave" + case "strongbox": return "StrongBox" + case "tee": return "TEE" + default: throw NotAGrant("hardware is not secure_enclave, strongbox or tee") + } + } + private static func headSha(_ p: [Bytes: Value]) throws -> String { String(try hex(p, "headSha", length: 40).prefix(shownHashLength)) } diff --git a/apps/mobile/plugins/withKinApprovalKey.cjs b/apps/mobile/plugins/withKinApprovalKey.cjs index 71ee4743c9721..d0e5a583bae42 100644 --- a/apps/mobile/plugins/withKinApprovalKey.cjs +++ b/apps/mobile/plugins/withKinApprovalKey.cjs @@ -1,12 +1,25 @@ -const { withInfoPlist } = require("expo/config-plugins"); +const { withEntitlementsPlist, withInfoPlist } = require("expo/config-plugins"); // No app name: source stays unbranded (KIN.md), and $(PRODUCT_NAME) would show the build target's name. const FACE_ID_USAGE = "Face ID confirms the merges and other actions you approve."; +const APP_ATTEST_ENVIRONMENT = "com.apple.developer.devicecheck.appattest-environment"; -// Set unconditionally so expo-secure-store's generic default never wins, whichever mod runs first. -module.exports = function withKinApprovalKey(config) { - return withInfoPlist(config, (nextConfig) => { +// `appAttestEnvironment` is "development" or "production", or null where the signing team can't +// hold the App Attest capability (personal teams); keys made there are unattested. +module.exports = function withKinApprovalKey(config, { appAttestEnvironment = null } = {}) { + if (![null, "development", "production"].includes(appAttestEnvironment)) { + throw new Error( + "withKinApprovalKey: appAttestEnvironment must be development, production or null.", + ); + } + // Set unconditionally so expo-secure-store's generic default never wins, whichever mod runs first. + const withUsage = withInfoPlist(config, (nextConfig) => { nextConfig.modResults.NSFaceIDUsageDescription = FACE_ID_USAGE; return nextConfig; }); + return withEntitlementsPlist(withUsage, (nextConfig) => { + if (appAttestEnvironment) nextConfig.modResults[APP_ATTEST_ENVIRONMENT] = appAttestEnvironment; + else delete nextConfig.modResults[APP_ATTEST_ENVIRONMENT]; + return nextConfig; + }); }; diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 123fc37dbc143..7105b2ef162bd 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -92,7 +92,11 @@ export const KinActionTarget = Schema.Union([ chatId: Schema.optional(KinChatId), level: KinLevel, }), - Schema.TaggedStruct("device_key", { thumbprint: Schema.String }), + Schema.TaggedStruct("device_key", { + thumbprint: Schema.String, + hardware: Schema.Literals(["secure_enclave", "strongbox", "tee"]), // the server's record + attested: Schema.Literal(true), // only an attested key can be proposed + }), ]); ``` @@ -168,14 +172,14 @@ Storage (new, SQLite, Kin's own migration set in `apps/server/src/kin/persistenc | Key | P-256 in the Secure Enclave: `SecKeyCreateRandomKey` with `kSecAttrTokenIDSecureEnclave`, not exportable | EC `secp256r1` in `AndroidKeyStore`, `PURPOSE_SIGN`, `DIGEST_SHA256`, `setIsStrongBoxBacked(true)` with fallback to TEE | | Gate | `SecAccessControlCreateWithFlags(… kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, [.privateKeyUsage, .biometryCurrentSet])`: every signature needs Face ID or Touch ID; the key dies if biometrics are re-enrolled | `setUserAuthenticationRequired(true)`, `setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)` (per-use), `setInvalidatedByBiometricEnrollment(true)`; sign inside `BiometricPrompt` with a `CryptoObject(Signature)` | | Signature | `SecKeyCreateSignature(.ecdsaSignatureMessageX962SHA256)` → DER; convert to 64-byte `r‖s` | `SHA256withECDSA` → DER; convert the same way | -| Attestation | Not in phase 1 (App Attest is a later option) | Record the `setAttestationChallenge` certificate chain; verify the root is Google's hardware root; store `attested: true/false` | +| Attestation | App Attest (`DCAppAttestService`) over `sha256(challenge ‖ public key)`, made natively from the key just created; verify per Apple's steps; store `attested: true/false` | Record the `setAttestationChallenge` certificate chain; verify the root is Google's hardware root; store `attested: true/false` | **Modules.** None of this exists in the repo's dependencies. - **Recommended: a new local Expo module** `apps/mobile/modules/kin-approval-key` (Swift + Kotlin, autolinked from `modules/`). API: `createKey(attestationChallenge): {publicJwk, hardware, attestation?}`, `sign(signingInput): base64url`, `hasKey()`, `deleteKey()`. `signingInput` is the grant's JWS signing input (section 5). The module signs nothing else: natively, it refuses anything that isn't a well-formed `KinGrant` and writes the approval text from the payload, so no caller chooses what the user is shown. The Kotlin side needs `androidx.biometric:biometric` (**new dependency**, Google, declared in the module's own `android/build.gradle`). -- Not enough on their own: `expo-local-authentication` (**new**, Expo) only shows a prompt and doesn't bind a key; `expo-secure-store` (already installed, `~58.0.2`) with `requireAuthentication: true` gates a stored secret, but the key is still generated in JS and its bytes enter JS memory. Use the latter only as a stopgap behind a `softwareKey: true` flag that the card shows and the audit records. +- Not enough on their own: `expo-local-authentication` (**new**, Expo) only shows a prompt and doesn't bind a key; `expo-secure-store` (already installed, `~58.0.2`) with `requireAuthentication: true` gates a stored secret, but the key is still generated in JS and its bytes enter JS memory. Neither is a stopgap: a key made in JS can't be attested, so the server never activates it. - Considered and not used: `react-native-biometrics` (**new**, third party) makes RSA keys and isn't Secure Enclave-backed on iOS. -- iOS needs `NSFaceIDUsageDescription`. Add it with a Kin config plugin `apps/mobile/plugins/withKinApprovalKey.cjs` (new), listed with one line in `apps/mobile/app.config.ts`. +- iOS needs `NSFaceIDUsageDescription` and the `com.apple.developer.devicecheck.appattest-environment` entitlement (`development` for development builds, `production` otherwise; none for personal-team builds, whose keys stay unattested). Add both with a Kin config plugin `apps/mobile/plugins/withKinApprovalKey.cjs` (new), listed with one entry in `apps/mobile/app.config.ts`. App Attest is a system framework, so it adds no dependency; the App ID needs the App Attest capability. ```ts export const KinApproverKey = Schema.Struct({ @@ -198,10 +202,11 @@ export const KinApproverKey = Schema.Struct({ Registration: 1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`. - - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to a Google hardware attestation root and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk`; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC on P-256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `attestationApplicationId` names the release package with a signing-certificate SHA-256 on the server's allowlist. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - - **iOS:** no attestation in phase 1, so the key is stored with `attested: false` and `hardware: "secure_enclave"`, which is claimed by the platform, not proven. + - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC with `ecCurve` P-256 and `keySize` 256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, the release package, whose set of signing-certificate SHA-256 digests equals the server's allowlist. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. + - **iOS:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The App Attest key is used only here; nothing later asserts with it. + - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; `confirmKey` refuses it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. -3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. +3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6M (Secure Enclave, attested)`), and the module refuses a target that isn't attested. 4. Revoking (`kin.approvals.revokeKey`, from settings or the desktop) sets `revoked` and voids every `approved` action whose grant that key signed. Revoking a T3 device session (`revokeClient`) also revokes keys registered from it. A key's role isn't stored on the key. It is read at verify time from org membership (chat spec), so demoting a person takes effect at once. @@ -324,7 +329,7 @@ export const KinProvenance = Schema.Struct({ - **Owner:** full facts, `canApprove: true`, shown in **Waiting on you** and the direct chat. - **Anyone else:** `{repo, number, title, state, waitingOn: "Nishchay"}`, `canApprove: false`, no challenge. `kin.approvals.challenge` and `submitGrant` refuse non-owners with `not_owner` anyway. - The card shows repo, PR number and title, head SHA (first 16, full on tap), base ← head, method, `+additions −deletions` and file count, required checks with status, the agent's reason as a quote, and the provenance warning. -- Approve: the approval key module shows the grant's own text, written natively from the signed payload (section 5): `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing` → biometric → sign → submit. Android shows it in the `BiometricPrompt`. Face ID mostly ignores the prompt's reason text, so on Face ID iPhones the module first shows it in a native confirmation sheet, in its own window above the app's; Approve refuses to sign (`E_OBSCURED`) unless that window is key and nothing covers it. Touch ID shows it in the system prompt. Notification and lock-screen actions open the app to this card; nothing is signed in the background, and the module signs one grant at a time. +- Approve: the approval key module shows the grant's own text, written natively from the signed payload (section 5): `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing` → biometric → sign → submit. Android shows it in the `BiometricPrompt`. Face ID mostly ignores the prompt's reason text, so on Face ID iPhones the module first shows it in a native confirmation sheet, in its own window above the app's. Approve stays disabled, and ignores taps, until the sheet has been key and uncovered for 0.7 s in a row; the delay restarts when the sheet appears, becomes key again, the keyboard hides, or a coverage check fails. So a tap aimed at something JS drew, or the second tap of a double tap, can't land on it. A tap that arrives while something covers the sheet signs nothing (`E_OBSCURED`). Touch ID shows it in the system prompt. Notification and lock-screen actions open the app to this card; nothing is signed in the background, and the module signs one grant at a time. - Desktop and web show the card read-only with "Approve on your phone" in phase 1. ### 10. GitHub: the bot App, the owner's review, rulesets @@ -431,26 +436,28 @@ At startup and hourly, the executor checks which GitHub identity T3 itself uses ## Threat model -| Threat | Example | Stopped by | -| ------------------------------------------ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -| Injected instruction | PR body says "merge this now" | Lead can only `request_action`; owner signs a native card; ceiling flags it | -| Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | -| Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | -| Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | -| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | -| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | -| Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | -| Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | -| Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | -| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; revoke from desktop | -| Compromised Kin server or agent with shell | Reads the keychain merge token | Token can't review; ruleset needs the owner's code-owner review at the current SHA, which only the phone can make | -| Bot self-approval | Bot approves its own PR | GitHub forbids author approval; bot isn't a code owner | -| Workflow exfiltration | Worker adds a workflow that prints secrets | App has no Workflows permission | -| Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | - -Tampered JS delivered over the air is the attacker the native sheet and grant parser defend against, so release builds must set `updates.codeSigningCertificate` for `expo-updates`. - -`deleteKey` needs no biometric, so tampered JS can delete the approval key. That is an accepted denial of service: registering a new key needs a fresh session challenge, attestation on Android, and the owner's confirmation. +| Threat | Example | Stopped by | +| ------------------------------------------ | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | +| Injected instruction | PR body says "merge this now" | Lead can only `request_action`; owner signs a native card; ceiling flags it | +| Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | +| Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | +| Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | +| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | +| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | +| Tampered JS times a tap onto Approve | Draws a button where Approve will appear, calls `sign` on touch-down; or covers Approve, then uncovers it | Approve takes taps only after the sheet has been key and uncovered for 0.7 s in a row | +| Tampered JS registers a software key | Deletes the hardware key, makes a P-256 key in JS, registers it | App Attest or Keystore attestation of a key the native module made; unattested keys are never activated | +| Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | +| Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | +| Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | +| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; revoke from desktop | +| Compromised Kin server or agent with shell | Reads the keychain merge token | Token can't review; ruleset needs the owner's code-owner review at the current SHA, which only the phone can make | +| Bot self-approval | Bot approves its own PR | GitHub forbids author approval; bot isn't a code owner | +| Workflow exfiltration | Worker adds a workflow that prints secrets | App has no Workflows permission | +| Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | + +Tampered JS is the attacker the native sheet, the grant parser and attestation defend against. Kin ships with over-the-air updates off: the branded build (BRAND-1) removes upstream's updates URL and EAS project, so the only JS that runs is the JS in the signed binary. Turning OTA updates on requires `updates.codeSigningCertificate` for `expo-updates`, so only bundles signed by Kin's key load. + +`deleteKey` needs no biometric, so tampered JS can delete the approval key. That is only a denial of service because a replacement must be attested: registering a new key needs a fresh session challenge, an App Attest or Keystore attestation of a key the native module made, and the owner's confirmation, and the server never activates an unattested key. ## Files @@ -472,7 +479,7 @@ Upstream hooks (one line each): - `packages/contracts/src/kinRpcs.ts` (Kin-owned, created by CHAT-6) — add the approval RPCs and scopes to `KinRpcs` and `KIN_RPC_SCOPES`; `rpc.ts` and `RpcAuthorization.ts` already spread those. - `apps/server/src/server.ts` — Kin layer already added by the chat spec; approvals layers join `apps/server/src/kin/layer.ts`, not upstream. - HTTP route for `/kin/mcp` — the same router hook the chat spec uses for Kin routes. -- `apps/mobile/app.config.ts` — `"./plugins/withKinApprovalKey.cjs",` in `plugins`. +- `apps/mobile/app.config.ts` — `["./plugins/withKinApprovalKey.cjs", { appAttestEnvironment }]` in `plugins`. RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read`; `challenge`, `submitGrant`, `reject` → `orchestration:operate`; `keyChallenge`, `registerKey`, `confirmKey`, `listKeys`, `revokeKey`, `kin.audit.list`, `kin.audit.verify` → `access:write`. Scopes are only the outer gate; the person and signature checks above are the real ones. @@ -506,7 +513,7 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read 19. `the merge token is never written to logs, audit, env or child processes` — grep the captured logs and spawned env in an integration test. 20. `the audit chain detects an edited row` (`kin.audit.verify`). 21. `the first approver key can't be confirmed from a remote session`. -22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`. The module's README has the checklist; its grant parser's vectors run without a device. +22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`, `a double tap can't land on Approve`, `a cover removed after the first tap can't approve`, `system UI doesn't lock the sheet out`. The module's README has the checklist; its grant parser's vectors run without a device. 23. GitHub (`scripts/kin-rulesets.ts --check`, run against a scratch repo): `the owner merge token can't submit a review` (expect 403), `the bot can't merge to main` and `a merge without a code-owner review is blocked`. Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot PR; the owner approves on the phone with Face ID; the GitHub review lands from the phone; the executor merges with the pinned SHA; the audit lists grant, device, SHA, provenance and merge commit. Tests 1–21 pass in CI; 22–23 pass on the release checklist. @@ -521,9 +528,9 @@ Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot **APPR-4 Grant verification.** `GrantVerifier.ts` implementing checks 1–10, `challenge`, `submitGrant`, `reject` RPCs, audit on every rejection. Depends on: APPR-2, APPR-5. Done when: tests 1–9 pass. Owner: backend. -**APPR-5 Approver keys.** Registry, `registerKey`/`confirmKey`/`listKeys`/`revokeKey`, desktop loopback confirmation with matching code, revoke-on-session-revoke, `register_approver_key` handler. Depends on: APPR-1, APPR-2. Done when: tests 4 and 21 pass. Owner: backend. +**APPR-5 Approver keys.** Registry, `registerKey`/`confirmKey`/`listKeys`/`revokeKey`, App Attest and Keystore attestation verification (section 4), never activating an unattested key, desktop loopback confirmation with matching code, revoke-on-session-revoke, `register_approver_key` handler with `hardware` and `attested` in its target. Depends on: APPR-1, APPR-2. Done when: tests 4 and 21 pass. Owner: backend. -**APPR-6 Native approval key module.** `apps/mobile/modules/kin-approval-key` for iOS (Secure Enclave, `.biometryCurrentSet`) and Android (Keystore, StrongBox fallback, `BiometricPrompt`, attestation chain); DER-to-compact; config plugin for `NSFaceIDUsageDescription`. Depends on: nothing. Done when: device tests in 22 pass on one iPhone and one Pixel, and a signature verifies with `p256.verify`. Owner: UI (native). +**APPR-6 Native approval key module.** `apps/mobile/modules/kin-approval-key` for iOS (Secure Enclave, `.biometryCurrentSet`, App Attest) and Android (Keystore, StrongBox fallback, `BiometricPrompt`, attestation chain); DER-to-compact; config plugin for `NSFaceIDUsageDescription` and the App Attest entitlement. Depends on: nothing. Done when: device tests in 22 pass on one iPhone and one Pixel, and a signature verifies with `p256.verify`. Owner: UI (native). **APPR-7 Approval card and phone flow.** `approvePendingAction` (challenge, biometric sign and submit; the card itself is MOB-8), GitHub review from the phone with the device-flow token, "Approve on GitHub" fallback. Depends on: APPR-4, APPR-6, MOB-4. Done when: on a device, approving a test PR posts a GitHub review at the head SHA and moves the action to `approved`; a member account sees "Waiting on Nishchay" with no button (test 16 on the server). Owner: UI. diff --git a/docs/kin/specs/mobile.md b/docs/kin/specs/mobile.md index 57887a385080c..6658953e29341 100644 --- a/docs/kin/specs/mobile.md +++ b/docs/kin/specs/mobile.md @@ -449,7 +449,7 @@ Commands, from `apps/mobile`: `vp run typecheck` and `vp test run --project unit ## Open questions -- Which Apple Developer team signs the Kin build, and who creates its APNs key? Android FCM waits until someone uses Android. +- Which Apple Developer team signs the Kin build, and who creates its APNs key? Its App ID also needs the App Attest capability, or approval keys can't be activated (approvals spec, section 4). Android FCM waits until someone uses Android. - Is "Kin" the right label for the entry row, or should it carry the lead's name? - Should the Waiting on you banner also show on T3's Home list when the Kin row is scrolled away (for example, as a pinned header)? - Does phase 1 need folded agent talk, given there is one agent in a direct chat? From fb15e2d3463fe2a260b19db58696dc95a76c0dfc Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:08:22 +0530 Subject: [PATCH 3/9] fix(kin): key set_level grants by agentId (APPR-6) LEAD-1 renamed the level target's leadId to agentId. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/modules/kin-approval-key/README.md | 2 +- .../java/expo/modules/kinapprovalkey/KinGrant.java | 4 ++-- .../kin-approval-key/fixtures/grant-vectors.json | 14 +++++++------- .../modules/kin-approval-key/ios/KinGrant.swift | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/apps/mobile/modules/kin-approval-key/README.md b/apps/mobile/modules/kin-approval-key/README.md index 580b905da93eb..ef05c1f076f05 100644 --- a/apps/mobile/modules/kin-approval-key/README.md +++ b/apps/mobile/modules/kin-approval-key/README.md @@ -30,7 +30,7 @@ Every hash shows its first 16 characters. A shown value is never cleaned or cut: - Repo: GitHub's `owner/name` rules (owner: letters, digits, `-`, up to 39; name: letters, digits, `. _ -`, up to 100). - Branches (`base`, `ref`) and `path`: letters, digits and `. _ - / +`. That is a subset of what git allows, so a merge into a branch with other characters (non-ASCII, `@`, `#` and so on) can't be approved from the phone. -- `leadId`, `chatId`: letters, digits and `. _ -`. +- `agentId`, `chatId`: letters, digits and `. _ -`. `register_approver_key` also needs `hardware` (`secure_enclave`, `strongbox` or `tee`) and `attested: true` in its target: the server never activates an unattested key, so there is nothing to approve for one. diff --git a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java index 0bf556c725356..c987893330e6c 100644 --- a/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java +++ b/apps/mobile/modules/kin-approval-key/android/src/main/java/expo/modules/kinapprovalkey/KinGrant.java @@ -119,13 +119,13 @@ private static String promptFor(Map p, String kid, long now) thr } case "set_level": { only(p); - exactKeys(target, setOf("_tag", "leadId", "level"), setOf("chatId"), "target"); + exactKeys(target, setOf("_tag", "agentId", "level"), setOf("chatId"), "target"); tag(target, "level"); String level = string(target, "level"); if (!level.matches("L[0-3]")) throw new NotAGrantException("level is not L0-L3"); String chat = target.containsKey("chatId") ? " in chat \"" + shown(target, "chatId", ID) + "\"" : " in all chats"; - text = "Set lead \"" + shown(target, "leadId", ID) + "\" to " + level + chat; + text = "Set lead \"" + shown(target, "agentId", ID) + "\" to " + level + chat; break; } case "change_rules": diff --git a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json index 87db8c84a1c3e..ed86f1979de86 100644 --- a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json +++ b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json @@ -184,13 +184,13 @@ { "name": "set a level in one chat", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"chatId\":\"chat_7\",\"leadId\":\"tech-lead\",\"level\":\"L2\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"tech-lead\",\"chatId\":\"chat_7\",\"level\":\"L2\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "prompt": "Set lead \"tech-lead\" to L2 in chat \"chat_7\"" }, { "name": "set a level everywhere", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"tech-lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"tech-lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "prompt": "Set lead \"tech-lead\" to L0 in all chats" }, { @@ -477,13 +477,13 @@ { "name": "set_level carrying headSha", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"l\",\"level\":\"L1\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"headSha\":\"a1b2c3d4e5f60718293a4b5c6d7e8f9012345678\",\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"l\",\"level\":\"L1\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" }, { "name": "level L4", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"l\",\"level\":\"L4\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"l\",\"level\":\"L4\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" }, { @@ -607,15 +607,15 @@ "error": "E_NOT_A_GRANT" }, { - "name": "a leadId with a space is refused", + "name": "a agentId with a space is refused", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"leadId\":\"tech lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"tech lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" }, { "name": "a chatId with a slash is refused", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", - "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"chatId\":\"chat/7\",\"leadId\":\"tech-lead\",\"level\":\"L2\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", + "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"tech-lead\",\"chatId\":\"chat/7\",\"level\":\"L2\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" }, { diff --git a/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift b/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift index df431cb92da80..72d691e8e766b 100644 --- a/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift +++ b/apps/mobile/modules/kin-approval-key/ios/KinGrant.swift @@ -103,12 +103,12 @@ enum KinGrant { text = "Delete branch \"\(try shown(target, "ref", .name))\" (\(try headSha(p))) in \(repo)" case "set_level": try only(p, []) - try exactKeys(target, ["_tag", "leadId", "level"], ["chatId"], "target") + try exactKeys(target, ["_tag", "agentId", "level"], ["chatId"], "target") try tag(target, "level") let level = try string(target, "level") guard ["L0", "L1", "L2", "L3"].contains(level) else { throw NotAGrant("level is not L0-L3") } let chat = target["chatId"] == nil ? " in all chats" : " in chat \"\(try shown(target, "chatId", .id))\"" - text = "Set lead \"\(try shown(target, "leadId", .id))\" to \(level)\(chat)" + text = "Set lead \"\(try shown(target, "agentId", .id))\" to \(level)\(chat)" case "change_rules", "memory_purge": try only(p, []) try exactKeys(target, ["_tag", "path", "sha256"], [], "target") From 67f7a41f10ead3429ff99311aae4de31bbb4f4fb Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:15:25 +0530 Subject: [PATCH 4/9] test(kin): fix a vector name (APPR-6) Co-Authored-By: Claude Opus 5.5 --- .../mobile/modules/kin-approval-key/fixtures/grant-vectors.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json index ed86f1979de86..4a4d3291f22de 100644 --- a/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json +++ b/apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json @@ -607,7 +607,7 @@ "error": "E_NOT_A_GRANT" }, { - "name": "a agentId with a space is refused", + "name": "an agentId with a space is refused", "header": "{\"alg\":\"ES256\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\",\"typ\":\"kin-grant+jws\"}", "payload": "{\"actionId\":\"act_01JD7Z0000000000000000000\",\"approver\":{\"humanId\":\"h_owner\",\"kid\":\"Y0ZkXVc6eNfxv3xVNHZJp1x7m3kQqb2O8s5vB1aWc9E\"},\"decision\":\"approve\",\"exp\":1798762190,\"iat\":1798761590,\"jti\":\"ZGV2aWNlLWp0aS0xNi1i\",\"kind\":\"set_level\",\"nonce\":\"c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA\",\"orgId\":\"org_01\",\"revision\":2,\"target\":{\"_tag\":\"level\",\"agentId\":\"tech lead\",\"level\":\"L0\"},\"targetDigest\":\"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\",\"v\":1}", "error": "E_NOT_A_GRANT" From 26e1f55efa08623f1aee86b5c4f48d5b34409dc6 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 07:45:51 +0530 Subject: [PATCH 5/9] fix(kin): arm the approval sheet only after every frame for 0.7 s is clear (APPR-6) Fourth security review. A single coverage check after 0.7 s let tampered JS hide a cover just before it. While arming, a CADisplayLink (weak proxy target) now samples coverage every frame and any unclear frame restarts the delay; the link stops once Approve arms and on teardown. The sheet ends picture in picture the app's web views started before it shows, and a failed attestation deletes its own key by application label instead of whatever key holds the tag. The spec adds the App Attest checks it was missing and states the OTA gate BRAND-1 now enforces. Co-Authored-By: Claude Opus 5.5 --- .../mobile/modules/kin-approval-key/README.md | 9 +- .../ios/ConfirmationSheet.swift | 83 ++++++++++++++----- .../ios/KinApprovalKey.podspec | 2 +- .../ios/KinApprovalKeyModule.swift | 21 +++-- docs/kin/PLAN.md | 2 +- docs/kin/specs/approvals.md | 47 ++++++----- 6 files changed, 108 insertions(+), 56 deletions(-) diff --git a/apps/mobile/modules/kin-approval-key/README.md b/apps/mobile/modules/kin-approval-key/README.md index ef05c1f076f05..4c22a99217124 100644 --- a/apps/mobile/modules/kin-approval-key/README.md +++ b/apps/mobile/modules/kin-approval-key/README.md @@ -65,9 +65,10 @@ Error codes on rejected promises: - **iOS:** the key is created with `SecKeyCreateRandomKey` and `kSecAttrTokenIDSecureEnclave`, gated by `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` with `[.privateKeyUsage, .biometryCurrentSet]`. It signs with `.ecdsaSignatureMessageX962SHA256` on the module's own `kin.approval-key` queue, so an open prompt never blocks Expo's shared queue. The queue is concurrent on purpose: `SecKeyCreateSignature` blocks its thread while Face ID is up, and a serial queue would hold a second call until the first finished and then show a second prompt, instead of rejecting it with `E_BUSY`. Each signature uses a fresh `LAContext` with `localizedFallbackTitle = ""`, so no earlier match is reused and there is no "Enter Password" button. `NSFaceIDUsageDescription` comes from `plugins/withKinApprovalKey.cjs`. - **iOS confirmation sheet (Face ID, Optic ID):** `ios/ConfirmationSheet.swift` shows the grant text in a window the module owns, at `windowLevel = .alert + 1` in the foreground scene, so views the app's JS can add to its own window (a `FullWindowOverlay`, a modal) sit below it. It ends editing first, since a keyboard's input accessory view would sit above every app window. - - **Arming.** Approve shows disabled and ignores taps until the sheet has been key and uncovered for 0.7 s in a row. The delay restarts when the sheet appears, when its window becomes or stops being key, when the scene activates or deactivates, when the keyboard hides, and whenever a check finds the sheet covered. So JS can't draw a button where Approve will appear and catch the second tap of a double tap, or hide a cover just after the first tap. + - **Arming.** Approve shows disabled and ignores taps until the sheet has been key and uncovered for 0.7 s in a row. While arming, a `CADisplayLink` checks coverage on every frame; any frame that isn't clear starts the 0.7 s over, so a cover hidden just before a check can't arm Approve early. The link runs only while arming and stops once Approve is enabled or the sheet goes. Arming starts again when the sheet appears, when its window becomes or stops being key, when the scene activates or deactivates, and when the keyboard shows or hides. So JS can't draw a button where Approve will appear and catch the second tap of a double tap, or hide a cover just after the first tap. Coverage is checked once more at the tap. + - **Picture in picture.** Before it shows, the sheet calls `closeAllMediaPresentations` on every `WKWebView` in the scene, which ends picture in picture (and fullscreen video) the app's web views started, such as the browser preview's stream of JS-drawn frames. The module can't see or end other picture-in-picture windows (another app's, or one from `expo-video`), which the system draws above every app window; see the approvals spec's threat model. - **Covered** means: the keyboard is up (tracked by `keyboardWillShow` and `keyboardDidHide`), a controller is presented over the sheet (RN's `Alert`), another window in the scene at its level or above is visible, or a view of the app's own classes sits over the card in the sheet's window. Windows that are hidden, have alpha 0 or have no subviews are skipped: they aren't drawn or hit-tested, and JS draws only with views. The keyboard's host windows (`UIRemoteKeyboardWindow`, `UITextEffectsWindow`) outlive the keyboard, so they count only while they hold app views (an `InputAccessoryView` or an `OverKeyboardView` left behind). UIKit's own views in the sheet's window, such as the iPad pointer-hover container, are skipped the same way. - - **Not key** (RN's `Alert.hide()` leaves no key window): the sheet calls `makeKey()` and the delay starts over, instead of failing. + - **Not key** (RN's `Alert.hide()` leaves no key window): the sheet calls `makeKey()` once per arming and the delay starts over, instead of failing. - A tap that reaches an armed Approve while the sheet is covered rejects with `E_OBSCURED`. The window is removed on every outcome. Cancel, the sheet disappearing without a choice, or the scene going to the background reject with `E_USER_CANCELED`. - **iOS App Attest:** after making the Secure Enclave key, `createKey` makes a fresh App Attest key with `DCAppAttestService` and attests it over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the key it just made. JS passes only the server's challenge, so it can't get an attestation over a key or data of its own. Where App Attest isn't supported (simulator, older devices, or `DCError.featureUnsupported`), there is no `attestation`. The entitlement `com.apple.developer.devicecheck.appattest-environment` comes from `plugins/withKinApprovalKey.cjs`: `development` for development builds, `production` otherwise, and none for personal-team builds. - **iOS re-enrolment:** `createKey` stores `LAContext.domainState.biometry.stateHash` in the keychain (this device only, never exported). A failed signature reports `E_KEY_INVALIDATED` rather than `E_AUTH_FAILED` when the stored hash differs from the current one. A mismatch alone never blocks signing, because Apple warns the hash can change across major OS versions with no enrolment change; after a successful signature, the stored hash is refreshed. @@ -126,12 +127,12 @@ console.log(`${b(header)}.${b(payload)}`); 4. While the sheet is up, call `Alert.alert` from a timer. Dismiss that alert, then tap Approve: it signs, and only the grant's text was ever on the sheet. 5. Type in a `TextInput` and leave the keyboard open, then call `sign`. The keyboard closes, the sheet shows, and Approve signs (no `E_OBSCURED`). Repeat after the keyboard has been dismissed. 6. **Double tap.** Draw a JS button where Approve will appear whose `onPressIn` calls `sign`. Double-tap it quickly. The sheet shows with Approve disabled, the second tap does nothing, and nothing is signed until Approve enables and is tapped again. Repeat with a triple tap. -7. **Cover, then uncover.** While the sheet is up, put an opaque box over Approve two ways: an `OverKeyboardView` (react-native-keyboard-controller), and an `InputAccessoryView` on a `TextInput` focused from a timer. Hide each from its own `onPressIn`. Tap the box: nothing is signed, and Approve enables only 0.7 s after the box is gone. Then open the keyboard, mount the `OverKeyboardView` and call `sign`: the keyboard closes, the view is left in the keyboard's window, and Approve stays disabled until the view is removed. +7. **Cover, then uncover.** While the sheet is up, put an opaque box over Approve two ways: an `OverKeyboardView` (react-native-keyboard-controller), and an `InputAccessoryView` on a `TextInput` focused from a timer. Hide each from its own `onPressIn`. Tap the box: nothing is signed, and Approve enables only 0.7 s after the box is gone. Then open the keyboard, mount the `OverKeyboardView` and call `sign`: the keyboard closes, the view is left in the keyboard's window, and Approve stays disabled until the view is removed. **Randomised hide:** about 50 times, mount the `OverKeyboardView` over Approve while the sheet is up and hide it from a timer with a random delay of 0 to 1.5 s, logging when it hid (`performance.now()`) and when Approve enabled (watch `isEnabled`, or record the screen at 120 fps). Approve must never enable less than 0.7 s after the box is gone. 8. **Alert, then no key window.** Call `Alert.alert` from a timer while the sheet is up, then dismiss it. Approve enables within about a second and signs (the sheet takes key back), with no `E_OBSCURED`. 9. **iPad pointer.** With a trackpad or mouse, hover over Approve until the pointer highlights it, then click. It signs (no `E_OBSCURED`, Approve not stuck disabled). 10. **VoiceOver.** Turn VoiceOver on and call `sign`. The grant text is read, Approve is announced dimmed until it arms, and double-tapping it then signs. **Full Keyboard Access:** on an iPad with a hardware keyboard, Tab to Approve and press Space; the same. 11. **Stage Manager and Split View (iPad).** Call `sign` with Kin in Split View, then in Stage Manager overlapped by another app's window. Tap the other app, then back into Kin's sheet: Approve is disabled for 0.7 s after Kin's window becomes key again, then signs. Record whether the other app's window can cover the sheet while Approve is armed. -12. **Picture in picture.** Start a video in picture in picture (from Safari or the app), drag it over the sheet's text and tap Approve. Record whether the sheet notices; the PiP window belongs to the system, so the module can't see it. +12. **Picture in picture.** Start the browser preview's picture in picture, then call `sign`: the PiP window closes as the sheet shows. Then start a video in picture in picture from Safari, drag it over the sheet's text and tap Approve: it signs, because the module can't see or end another app's PiP window (accepted in the approvals spec's threat model). Record both, and whether the PiP window could take the tap. ### 3. Re-enrolling biometrics invalidates the key diff --git a/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift b/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift index 78c88fb740d2e..10154cec217c5 100644 --- a/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift +++ b/apps/mobile/modules/kin-approval-key/ios/ConfirmationSheet.swift @@ -1,4 +1,5 @@ import UIKit +import WebKit /// The Face ID confirmation sheet, in a window the module owns above the app's own window, so the /// app's JS can't draw over the grant text and leave the real Approve button exposed. @@ -16,8 +17,8 @@ final class ConfirmationSheet { case covered } - /// How long the sheet must stay key and uncovered before Approve takes a tap, so a tap aimed at - /// something JS drew (or the second tap of a double tap) can't land on it. + /// How long the sheet must stay key and uncovered, sampled every frame, before Approve takes a + /// tap, so a tap aimed at something JS drew (or the second tap of a double tap) can't land on it. private static let armDelay: CFTimeInterval = 0.7 private let window: UIWindow @@ -25,7 +26,10 @@ final class ConfirmationSheet { private weak var previousKeyWindow: UIWindow? private var observers: [NSObjectProtocol] = [] private var onOutcome: ((Outcome) -> Void)? - private var armedAt = CFTimeInterval.infinity + private var armed = false + private var arming: CADisplayLink? + private var clearSince: CFTimeInterval? + private var tookKey = false private var keyboardVisible = false /// Shows the sheet at once. `onOutcome` is called exactly once, after the sheet is gone. @@ -67,12 +71,15 @@ final class ConfirmationSheet { } // An input accessory view lives in the keyboard's window, above every app window. for window in scene.windows { window.endEditing(true) } + // The browser preview can stream JS-drawn frames into system picture in picture, over the sheet. + for window in scene.windows { Self.closeMediaPresentations(in: window) } window.makeKeyAndVisible() } /// Removes the sheet without an outcome; safe to call more than once. func close() { onOutcome = nil + stopArming() for observer in observers { NotificationCenter.default.removeObserver(observer) } observers = [] window.isHidden = true @@ -92,32 +99,51 @@ final class ConfirmationSheet { onOutcome(outcome) } - /// Disables Approve and starts the arming delay again. Approve enables only if the sheet is - /// still clear when the delay ends; a check that fails starts it over. + /// Disables Approve and samples coverage every frame until the sheet has been key and clear for + /// `armDelay` in a row. Any sample that isn't clear starts the delay over. private func rearm() { guard onOutcome != nil else { return } - let deadline = CACurrentMediaTime() + Self.armDelay - armedAt = deadline + armed = false + clearSince = nil + tookKey = false controller.approve.isEnabled = false - DispatchQueue.main.asyncAfter(deadline: .now() + Self.armDelay) { [weak self] in - // A later rearm owns the timer. - guard let self, onOutcome != nil, armedAt == deadline else { return } - switch coverage { - case .clear: - controller.approve.isEnabled = true - case .notKey: - // RN's Alert.hide() leaves no key window. Take key back once; the delay starts over. + guard arming == nil else { return } + let link = CADisplayLink(target: ArmingTarget(self), selector: #selector(ArmingTarget.sample)) + link.add(to: .main, forMode: .common) + arming = link + } + + fileprivate func sampleCoverage() { + guard onOutcome != nil else { return stopArming() } + let now = CACurrentMediaTime() + switch coverage { + case .clear: + let since = clearSince ?? now + clearSince = since + guard now - since >= Self.armDelay else { return } + stopArming() + armed = true + controller.approve.isEnabled = true + case .notKey: + clearSince = nil + // RN's Alert.hide() leaves no key window. Take key back once per arming. + if !tookKey { + tookKey = true window.makeKey() - rearm() - case .covered: - rearm() } + case .covered: + clearSince = nil } } + private func stopArming() { + arming?.invalidate() + arming = nil + } + private func approveTapped() { // A disabled button gets no taps; this guards a tap already in flight when Approve disabled. - guard controller.approve.isEnabled, CACurrentMediaTime() >= armedAt else { return } + guard armed, controller.approve.isEnabled else { return } switch coverage { case .clear: finish(.approved) @@ -171,6 +197,25 @@ final class ConfirmationSheet { } private static let appBundlePath = Bundle.main.bundleURL.path + + /// Ends picture in picture and fullscreen video started from any web view in this tree. + private static func closeMediaPresentations(in view: UIView) { + if let webView = view as? WKWebView { webView.closeAllMediaPresentations(completionHandler: nil) } + for subview in view.subviews { closeMediaPresentations(in: subview) } + } +} + +/// Holds the sheet weakly, so the display link's strong reference to its target can't keep it alive. +@MainActor +private final class ArmingTarget: NSObject { + private weak var sheet: ConfirmationSheet? + + init(_ sheet: ConfirmationSheet) { self.sheet = sheet } + + @objc func sample(_ link: CADisplayLink) { + guard let sheet else { return link.invalidate() } + sheet.sampleCoverage() + } } private final class ConfirmationController: UIViewController { diff --git a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec index 7609f190a024b..680b53dfde075 100644 --- a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec +++ b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKey.podspec @@ -9,5 +9,5 @@ Pod::Spec.new do |s| s.static_framework = true s.dependency 'ExpoModulesCore' s.source_files = '*.swift' - s.frameworks = 'CryptoKit', 'DeviceCheck', 'LocalAuthentication', 'Security' + s.frameworks = 'CryptoKit', 'DeviceCheck', 'LocalAuthentication', 'Security', 'WebKit' end diff --git a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift index c08fbe35b8538..aed75c51e284b 100644 --- a/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift +++ b/apps/mobile/modules/kin-approval-key/ios/KinApprovalKeyModule.swift @@ -46,9 +46,10 @@ public class KinApprovalKeyModule: Module { private func createKey(attestationChallenge: String, promise: Promise) { let challenge: Data let publicKey: Data + let keyLabel: Data do { challenge = try decodeChallenge(attestationChallenge) - publicKey = try createSecureEnclaveKey() + (publicKey, keyLabel) = try createSecureEnclaveKey() } catch { return promise.reject(error) } @@ -59,9 +60,12 @@ private func createKey(attestationChallenge: String, promise: Promise) { let clientDataHash = Data(SHA256.hash(data: challenge + publicKey)) let fail: (Error?) -> Void = { error in if let error = error as? DCError, error.code == .featureUnsupported { return promise.resolve(created) } - // No half-made key: a retry must make and attest a fresh one. - SecItemDelete(privateKeyQuery() as CFDictionary) - SecItemDelete(biometryStateQuery() as CFDictionary) + // No half-made key: a retry must make and attest a fresh one. Delete this key by its label, not + // the tag, so a failure that lands after deleteKey and a new createKey can't remove the new key. + var thisKey = privateKeyQuery() + thisKey[kSecAttrApplicationLabel as String] = keyLabel + SecItemDelete(thisKey as CFDictionary) + if (try? loadPrivateKey(context: nil)) == nil { SecItemDelete(biometryStateQuery() as CFDictionary) } promise.reject(ApprovalKeyException( "E_ATTESTATION_FAILED", "App Attest couldn't attest the approval key; try again.", cause: error)) } @@ -85,8 +89,8 @@ private func decodeChallenge(_ value: String) throws -> Data { return data } -/// Returns the new key's public key in X9.63 form (`04 ‖ x ‖ y`). -private func createSecureEnclaveKey() throws -> Data { +/// Returns the new key's public key in X9.63 form (`04 ‖ x ‖ y`) and its keychain application label. +private func createSecureEnclaveKey() throws -> (publicKey: Data, label: Data) { guard SecureEnclave.isAvailable else { throw ApprovalKeyException("E_NO_SECURE_HARDWARE", "This device has no Secure Enclave.") } @@ -127,13 +131,14 @@ private func createSecureEnclaveKey() throws -> Data { "E_KEYCHAIN", "Creating the Secure Enclave key failed.", cause: error?.takeRetainedValue()) } guard let publicKey = SecKeyCopyPublicKey(privateKey), - let x963 = SecKeyCopyExternalRepresentation(publicKey, &error) as Data? else { + let x963 = SecKeyCopyExternalRepresentation(publicKey, &error) as Data?, + let label = (SecKeyCopyAttributes(privateKey) as? [String: Any])?[kSecAttrApplicationLabel as String] as? Data else { SecItemDelete(privateKeyQuery() as CFDictionary) throw ApprovalKeyException( "E_KEYCHAIN", "Exporting the approval public key failed.", cause: error?.takeRetainedValue()) } storeBiometryState(context.domainState.biometry.stateHash) - return x963 + return (x963, label) } /// One `sign` call. Only one may be in flight; every path settles its promise exactly once. diff --git a/docs/kin/PLAN.md b/docs/kin/PLAN.md index 4ea3d484f9518..3394bf7bd4e8a 100644 --- a/docs/kin/PLAN.md +++ b/docs/kin/PLAN.md @@ -91,7 +91,7 @@ A task can start once everything it depends on has merged. These waves come from **Critical path:** CHAT-1 → CHAT-3 → CHAT-4 → CHAT-5 → CHAT-7 → LEAD-7 → LEAD-9 → LEAD-11 → APPR-9 → TRIG-5 → TRIG-6 → TRIG-10. Review those PRs first. GitHub webhooks come late only because TRIG-5 creates repo hooks through the executor. If that becomes the bottleneck, TRIG-5 can create the hook directly with the bot's token and move to wave 5. -**BRAND-1. Branding script.** `scripts/kin-brand.ts`, `branding/rules.yaml`, `branding/assets/`, as described in [KIN.md](../../KIN.md#branding-at-build-time). Done when: running it on a clean checkout produces a copy that typechecks, shows "Kin" in the mobile, desktop and web app names, installs alongside T3 Code (different bundle ids and scheme), and its drift check fails when a rule matches nothing. Owner: backend. +**BRAND-1. Branding script.** `scripts/kin-brand.ts`, `branding/rules.yaml`, `branding/assets/`, as described in [KIN.md](../../KIN.md#branding-at-build-time). Done when: running it on a clean checkout produces a copy that typechecks, shows "Kin" in the mobile, desktop and web app names, installs alongside T3 Code (different bundle ids and scheme), turns over-the-air updates on only when both a Kin EAS project and an update code-signing certificate are configured, and its drift check fails when a rule matches nothing. Owner: backend. ## Shared decisions the specs settled diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index 7105b2ef162bd..5a0efdba02e51 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -203,7 +203,7 @@ Registration: 1. The phone calls `kin.approvals.keyChallenge()` (`access:write`), which returns a single-use 32-byte nonce bound to that session and valid for 5 minutes. It passes the nonce to `createKey`, then calls `kin.approvals.registerKey({publicJwk, platform, challenge, attestation?, deviceLabel})` over the same session. The server consumes the nonce, stores the key as `pending` and returns a 6-digit code derived from `sha256(thumbprint ‖ serverNonce)`. - **Android:** `attestation.certificateChain` is required. The server checks it offline: the chain verifies up to one of Google's two hardware attestation roots (the legacy RSA root and the newer ECDSA root), each pinned by its public key, and no certificate is on Google's attestation revocation list; the leaf's public key equals `publicJwk` and is EC P-256; the KeyDescription is read from the leaf only, and a chain where any other certificate carries one is refused; the leaf's KeyDescription has `attestationChallenge` equal to the nonce, `attestationSecurityLevel` and `keyMintSecurityLevel` (`keymasterSecurityLevel` before KeyMint) of `TrustedEnvironment` or `StrongBox`, and in `hardwareEnforced`: purpose `SIGN`, algorithm EC with `ecCurve` P-256 and `keySize` 256, digest SHA-256, `userAuthType` biometric only (`FINGERPRINT`, the value Keystore uses for every strong biometric), no `authTimeout`, no `noAuthRequired`, `origin` `GENERATED`, and `rootOfTrust` with `verifiedBootState` `Verified` and `deviceLocked` true; `allApplications` absent from both authorization lists; `attestationApplicationId` names exactly one package, the release package, whose set of signing-certificate SHA-256 digests equals the server's allowlist. Invalidation on biometric re-enrolment is checked only on the client (`KeyInfo` after creation, README); attestation can't prove it. All pass: `attested: true`, and `hardware` is `strongbox` or `tee` from the attestation security level. Any check fails: `attested: false`, `hardware: "software"`. The client never supplies `hardware`. - - **iOS:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The App Attest key is used only here; nothing later asserts with it. + - **iOS:** `attestation` is `{format: "apple-app-attest", keyId, attestationObject}`. `createKey` makes it natively: a fresh App Attest key, attested over the client data hash `sha256(challenge ‖ 0x04 ‖ x ‖ y)` of the Secure Enclave key it just made. The module computes that hash itself, so JS can't get an attestation over a key or data it chose. The server follows Apple's documented verification: the `x5c` chain verifies to the pinned Apple App Attest root; the nonce extension (OID `1.2.840.113635.100.8.2`) equals `sha256(authData ‖ clientDataHash)`, where the server recomputes `clientDataHash` from the nonce it issued and `publicJwk`; the credential certificate's public key hashes to `keyId`; `authData`'s RP ID hash is `sha256(".")` for the Kin bundle id; the counter is 0; the aaguid is `appattest` followed by seven zero bytes for production builds, and `appattestdevelop` only on a server configured to accept development builds; the credential id equals `keyId`. All pass: `attested: true`, `hardware: "secure_enclave"`. No attestation (a simulator or an unsupported device) or any failed check: `attested: false`, `hardware: "software"`. The attestation object's `fmt` must be `apple-appattest` (the CBOR field, distinct from the client's `format` label `apple-app-attest`). `keyId` is `sha256` of the credential certificate's public key as the 65-byte X9.63 point, not its SPKI. Every certificate in `x5c` must be valid at verification time. The App Attest key is used only here; nothing later asserts with it, so the attestation's receipt isn't needed. App Attest proves the app, not its version: once several native builds have shipped, the server keeps a minimum native build (or a version allowlist) and refuses registration from older ones. - **Either platform:** the server never makes a key with `attested: false` `active`. It is listed as "can't be used for approvals" and can only be revoked; `confirmKey` refuses it, and no `register_approver_key` action can be requested for it. This is what stops tampered JS from deleting the hardware key, making a P-256 key in JS and registering it: the 6-digit code would match, because it derives from whatever key was registered, but that key can't be attested. 2. **First key in an org:** confirmed on the Mac running the server, in the desktop app's local session (loopback only), where the owner checks the code shown on both screens. No remote path can confirm the first key. 3. **Later keys:** confirmed by a grant of kind `register_approver_key` signed by an existing active key. Its `device_key` target carries the new key's `hardware` and `attested` from the server's record, so the phone's prompt shows them (`Add approver key NzbLsXh8uDCcd-6M (Secure Enclave, attested)`), and the module refuses a target that isn't attested. @@ -329,7 +329,7 @@ export const KinProvenance = Schema.Struct({ - **Owner:** full facts, `canApprove: true`, shown in **Waiting on you** and the direct chat. - **Anyone else:** `{repo, number, title, state, waitingOn: "Nishchay"}`, `canApprove: false`, no challenge. `kin.approvals.challenge` and `submitGrant` refuse non-owners with `not_owner` anyway. - The card shows repo, PR number and title, head SHA (first 16, full on tap), base ← head, method, `+additions −deletions` and file count, required checks with status, the agent's reason as a quote, and the provenance warning. -- Approve: the approval key module shows the grant's own text, written natively from the signed payload (section 5): `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing` → biometric → sign → submit. Android shows it in the `BiometricPrompt`. Face ID mostly ignores the prompt's reason text, so on Face ID iPhones the module first shows it in a native confirmation sheet, in its own window above the app's. Approve stays disabled, and ignores taps, until the sheet has been key and uncovered for 0.7 s in a row; the delay restarts when the sheet appears, becomes key again, the keyboard hides, or a coverage check fails. So a tap aimed at something JS drew, or the second tap of a double tap, can't land on it. A tap that arrives while something covers the sheet signs nothing (`E_OBSCURED`). Touch ID shows it in the system prompt. Notification and lock-screen actions open the app to this card; nothing is signed in the background, and the module signs one grant at a time. +- Approve: the approval key module shows the grant's own text, written natively from the signed payload (section 5): `Merge GLDRoger/t3code #212 (a1b2c3d4e5f60718) into "main" by squashing` → biometric → sign → submit. Android shows it in the `BiometricPrompt`. Face ID mostly ignores the prompt's reason text, so on Face ID iPhones the module first shows it in a native confirmation sheet, in its own window above the app's. Before it shows, the sheet ends any picture in picture the app's web views started. Approve stays disabled, and ignores taps, until the sheet has been key and uncovered for 0.7 s in a row, checked on every frame while arming; any frame that isn't clear restarts the delay, as do the sheet appearing, becoming key again, and the keyboard showing or hiding. So a tap aimed at something JS drew, or the second tap of a double tap, can't land on it. A tap that arrives while something covers the sheet signs nothing (`E_OBSCURED`). Touch ID shows it in the system prompt. Notification and lock-screen actions open the app to this card; nothing is signed in the background, and the module signs one grant at a time. - Desktop and web show the card read-only with "Approve on your phone" in phase 1. ### 10. GitHub: the bot App, the owner's review, rulesets @@ -436,26 +436,27 @@ At startup and hourly, the executor checks which GitHub identity T3 itself uses ## Threat model -| Threat | Example | Stopped by | -| ------------------------------------------ | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | -| Injected instruction | PR body says "merge this now" | Lead can only `request_action`; owner signs a native card; ceiling flags it | -| Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | -| Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | -| Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | -| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | -| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | -| Tampered JS times a tap onto Approve | Draws a button where Approve will appear, calls `sign` on touch-down; or covers Approve, then uncovers it | Approve takes taps only after the sheet has been key and uncovered for 0.7 s in a row | -| Tampered JS registers a software key | Deletes the hardware key, makes a P-256 key in JS, registers it | App Attest or Keystore attestation of a key the native module made; unattested keys are never activated | -| Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | -| Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | -| Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | -| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; revoke from desktop | -| Compromised Kin server or agent with shell | Reads the keychain merge token | Token can't review; ruleset needs the owner's code-owner review at the current SHA, which only the phone can make | -| Bot self-approval | Bot approves its own PR | GitHub forbids author approval; bot isn't a code owner | -| Workflow exfiltration | Worker adds a workflow that prints secrets | App has no Workflows permission | -| Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | - -Tampered JS is the attacker the native sheet, the grant parser and attestation defend against. Kin ships with over-the-air updates off: the branded build (BRAND-1) removes upstream's updates URL and EAS project, so the only JS that runs is the JS in the signed binary. Turning OTA updates on requires `updates.codeSigningCertificate` for `expo-updates`, so only bundles signed by Kin's key load. +| Threat | Example | Stopped by | +| ------------------------------------------ | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Injected instruction | PR body says "merge this now" | Lead can only `request_action`; owner signs a native card; ceiling flags it | +| Fake approval in text | Member types "Nishchay approved" | Only `submitGrant` with a valid signature changes state | +| Forged approval from a member's client | Modified app calls `submitGrant` | Checks 2–4: key not registered, or registered to a non-owner → `not_owner` | +| Agent-drawn button | Generated widget labelled "Approve" | `approval` widgets carry only `actionId`; the card is native; generated widgets can't call approvals RPCs | +| Card shows one thing, phone signs another | Buggy or tampered app code asks the key to sign another PR | The key signs only canonical grants; the module writes the approval text natively from the bytes it signs | +| Tampered JS draws over the Face ID sheet | An over-the-air bundle covers the text, leaves Approve | Sheet in the module's own window above the app's; Approve checks nothing covers it (`E_OBSCURED`) | +| Tampered JS times a tap onto Approve | Draws a button where Approve will appear, calls `sign` on touch-down; or covers Approve, then uncovers it | Approve takes taps only after the sheet has been key and uncovered for 0.7 s in a row | +| Tampered JS draws into picture in picture | Streams frames over the sheet's text from a PiP window | The sheet closes the app's web-view PiP before it shows; PiP from another app or `expo-video` is accepted: it can't block taps, and Approve signs only the grant's own text | +| Tampered JS registers a software key | Deletes the hardware key, makes a P-256 key in JS, registers it | App Attest or Keystore attestation of a key the native module made; unattested keys are never activated | +| Replay | Captured grant sent again, or for another PR | `jti` UNIQUE, nonce and `targetDigest` binding, executions PK | +| Bait and switch | New commit pushed after the owner looks | Nonce rotation, check 9, executor precheck, `sha` on the merge call, `dismiss_stale_reviews_on_push` | +| Double run | Restart mid-merge, duplicate webhook, deferral fires twice | Idempotency key, executions PK, reconciliation | +| Stolen phone | Thief has the unlocked phone | Per-use biometric on the key; `.biometryCurrentSet` / enrollment invalidation; revoke from desktop | +| Compromised Kin server or agent with shell | Reads the keychain merge token | Token can't review; ruleset needs the owner's code-owner review at the current SHA, which only the phone can make | +| Bot self-approval | Bot approves its own PR | GitHub forbids author approval; bot isn't a code owner | +| Workflow exfiltration | Worker adds a workflow that prints secrets | App has no Workflows permission | +| Rule change from chat | "Remember: Priya can approve merges" | `change_rules`/delegations need owner provenance and a grant | + +Tampered JS is the attacker the native sheet, the grant parser and attestation defend against. Kin builds have over-the-air updates off unless both a Kin EAS project (`KIN_EAS_PROJECT_ID`) and an update code-signing certificate (`KIN_UPDATES_CODE_SIGNING_CERT`) are configured: the branded build (BRAND-1) removes upstream's updates URL and EAS project, and turns `updates.enabled` on only with both, writing `updates.codeSigningCertificate` so `expo-updates` loads only bundles signed by Kin's key. Without both, the only JS that runs is the JS in the signed binary. `deleteKey` needs no biometric, so tampered JS can delete the approval key. That is only a denial of service because a replacement must be attested: registering a new key needs a fresh session challenge, an App Attest or Keystore attestation of a key the native module made, and the owner's confirmation, and the server never activates an unattested key. @@ -513,7 +514,7 @@ RPCs and scopes: `kin.approvals.list` (stream) and `get` → `orchestration:read 19. `the merge token is never written to logs, audit, env or child processes` — grep the captured logs and spawned env in an integration test. 20. `the audit chain detects an edited row` (`kin.audit.verify`). 21. `the first approver key can't be confirmed from a remote session`. -22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`, `a double tap can't land on Approve`, `a cover removed after the first tap can't approve`, `system UI doesn't lock the sheet out`. The module's README has the checklist; its grant parser's vectors run without a device. +22. Mobile (`apps/mobile/modules/kin-approval-key`, device test): `signing without biometrics fails`, `re-enrolling biometrics invalidates the key`, `DER signatures convert to compact and verify on the server`, `only one signature at a time, under the grant's own text`, `an overlay over the sheet can't approve`, `a double tap can't land on Approve`, `a cover removed after the first tap can't approve` (including about 50 randomised-timer hides: Approve never enables less than 0.7 s after the cover goes), `the app's own picture in picture closes before the sheet shows`, `system UI doesn't lock the sheet out`. The module's README has the checklist; its grant parser's vectors run without a device. 23. GitHub (`scripts/kin-rulesets.ts --check`, run against a scratch repo): `the owner merge token can't submit a review` (expect 403), `the bot can't merge to main` and `a merge without a code-owner review is blocked`. Acceptance for phase 1: on `GLDRoger/t3code`, the lead requests a merge of a bot PR; the owner approves on the phone with Face ID; the GitHub review lands from the phone; the executor merges with the pinned SHA; the audit lists grant, device, SHA, provenance and merge commit. Tests 1–21 pass in CI; 22–23 pass on the release checklist. From 3504a2378c695b4570c4a0757f3a86bb94ba0322 Mon Sep 17 00:00:00 2001 From: Surajsm60720 <1ds22is166@dsce.edu.in> Date: Sun, 8 Nov 2026 08:03:54 +0530 Subject: [PATCH 6/9] fix(kin): disarm the approval sheet when a cover appears after arming (APPR-6) The arming display link stopped once Approve enabled, so a cover mounted after arming and hidden on the first tap left the second tap live. The link now runs until close(): an armed sheet disarms on the first frame that isn't key and clear, and arming starts over. The same link closes web-view picture in picture about every 10 frames while the sheet is up. createKey's export-failure path deletes its key by reference, and a failed attestation deletes the biometry state only if it still holds the hash that call stored. The spec's threat model now describes the real arming rule and PiP residual risk, and attributes the OTA gate to #35. Co-Authored-By: Claude Opus 5.5 --- .../mobile/modules/kin-approval-key/README.md | 10 ++-- .../ios/ConfirmationSheet.swift | 53 +++++++++++-------- .../ios/KinApprovalKeyModule.swift | 31 +++++++---- docs/kin/specs/approvals.md | 48 +++++++++-------- 4 files changed, 82 insertions(+), 60 deletions(-) diff --git a/apps/mobile/modules/kin-approval-key/README.md b/apps/mobile/modules/kin-approval-key/README.md index 4c22a99217124..1341966b2cc46 100644 --- a/apps/mobile/modules/kin-approval-key/README.md +++ b/apps/mobile/modules/kin-approval-key/README.md @@ -65,8 +65,8 @@ Error codes on rejected promises: - **iOS:** the key is created with `SecKeyCreateRandomKey` and `kSecAttrTokenIDSecureEnclave`, gated by `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` with `[.privateKeyUsage, .biometryCurrentSet]`. It signs with `.ecdsaSignatureMessageX962SHA256` on the module's own `kin.approval-key` queue, so an open prompt never blocks Expo's shared queue. The queue is concurrent on purpose: `SecKeyCreateSignature` blocks its thread while Face ID is up, and a serial queue would hold a second call until the first finished and then show a second prompt, instead of rejecting it with `E_BUSY`. Each signature uses a fresh `LAContext` with `localizedFallbackTitle = ""`, so no earlier match is reused and there is no "Enter Password" button. `NSFaceIDUsageDescription` comes from `plugins/withKinApprovalKey.cjs`. - **iOS confirmation sheet (Face ID, Optic ID):** `ios/ConfirmationSheet.swift` shows the grant text in a window the module owns, at `windowLevel = .alert + 1` in the foreground scene, so views the app's JS can add to its own window (a `FullWindowOverlay`, a modal) sit below it. It ends editing first, since a keyboard's input accessory view would sit above every app window. - - **Arming.** Approve shows disabled and ignores taps until the sheet has been key and uncovered for 0.7 s in a row. While arming, a `CADisplayLink` checks coverage on every frame; any frame that isn't clear starts the 0.7 s over, so a cover hidden just before a check can't arm Approve early. The link runs only while arming and stops once Approve is enabled or the sheet goes. Arming starts again when the sheet appears, when its window becomes or stops being key, when the scene activates or deactivates, and when the keyboard shows or hides. So JS can't draw a button where Approve will appear and catch the second tap of a double tap, or hide a cover just after the first tap. Coverage is checked once more at the tap. - - **Picture in picture.** Before it shows, the sheet calls `closeAllMediaPresentations` on every `WKWebView` in the scene, which ends picture in picture (and fullscreen video) the app's web views started, such as the browser preview's stream of JS-drawn frames. The module can't see or end other picture-in-picture windows (another app's, or one from `expo-video`), which the system draws above every app window; see the approvals spec's threat model. + - **Arming.** A `CADisplayLink` checks coverage on every frame for as long as the sheet is up. Approve shows disabled and ignores taps until every frame for 0.7 s has found the sheet key and uncovered; any frame that isn't clear starts the 0.7 s over, so a cover hidden just before a check can't arm Approve early. Once Approve is enabled, the first frame that isn't key and clear disables it again and arming starts over, so a cover mounted after Approve arms and hidden on the first tap can't leave the second tap live. Arming also starts over when the sheet appears, when its window becomes or stops being key, when the scene activates or deactivates, and when the keyboard shows or hides. So JS can't draw a button where Approve will appear and catch the second tap of a double tap, or hide a cover just after the first tap. Coverage is checked once more at the tap. + - **Picture in picture.** Before it shows, and about every 10 frames while it is up, the sheet calls `closeAllMediaPresentations` on every `WKWebView` in the scene, which ends picture in picture (and fullscreen video) the app's web views start, such as the browser preview's stream of JS-drawn frames or one tampered JS starts with `injectJavaScript`. The module can't see or end other picture-in-picture windows (another app's, or one from `expo-video`), which the system draws above every app window and which take taps inside their own frame; see the approvals spec's threat model. - **Covered** means: the keyboard is up (tracked by `keyboardWillShow` and `keyboardDidHide`), a controller is presented over the sheet (RN's `Alert`), another window in the scene at its level or above is visible, or a view of the app's own classes sits over the card in the sheet's window. Windows that are hidden, have alpha 0 or have no subviews are skipped: they aren't drawn or hit-tested, and JS draws only with views. The keyboard's host windows (`UIRemoteKeyboardWindow`, `UITextEffectsWindow`) outlive the keyboard, so they count only while they hold app views (an `InputAccessoryView` or an `OverKeyboardView` left behind). UIKit's own views in the sheet's window, such as the iPad pointer-hover container, are skipped the same way. - **Not key** (RN's `Alert.hide()` leaves no key window): the sheet calls `makeKey()` once per arming and the delay starts over, instead of failing. - A tap that reaches an armed Approve while the sheet is covered rejects with `E_OBSCURED`. The window is removed on every outcome. Cancel, the sheet disappearing without a choice, or the scene going to the background reject with `E_USER_CANCELED`. @@ -100,7 +100,7 @@ console.log(`${b(header)}.${b(payload)}`); ### 1. Signing without biometrics fails -1. Call `createKey()`. Check that `hardware` is `secure_enclave` on iOS and `strongbox` on the Pixel (`tee` if StrongBox is unavailable). On Android, check that `attestation.certificateChain` has at least 2 entries; on iOS, that `attestation.format` is `apple-app-attest`. In airplane mode, iOS rejects with `E_ATTESTATION_FAILED` and `hasKey()` is then `false`. +1. Call `createKey()`. Check that `hardware` is `secure_enclave` on iOS and `strongbox` on the Pixel (`tee` if StrongBox is unavailable). On iOS, it must not reject with `E_KEYCHAIN` "Exporting the approval public key failed": that means `SecKeyCopyAttributes` returned no `klbl` (`kSecAttrApplicationLabel`) for the Secure Enclave key, which the attestation-failure cleanup relies on. On Android, check that `attestation.certificateChain` has at least 2 entries; on iOS, that `attestation.format` is `apple-app-attest`. In airplane mode, iOS rejects with `E_ATTESTATION_FAILED` and `hasKey()` is then `false`. 2. Call `sign()`. **The prompt shows `Merge GLDRoger/t3code #212 (a1b2c3d000000000) into "main" by squashing`**: in the confirmation sheet on Face ID, in the system prompt on Touch ID and Android. Pass the biometric check. It resolves to an 86-character base64url string (64 bytes). 3. Call `sign` again and **cancel** the prompt (and, on Face ID, the sheet). It rejects with `E_USER_CANCELED`. 4. Call `sign` again and fail the biometric 5 times (cover the camera, or use an unenrolled finger). It rejects with `E_AUTH_FAILED` or `E_BIOMETRY_LOCKOUT`, and never resolves. @@ -127,12 +127,12 @@ console.log(`${b(header)}.${b(payload)}`); 4. While the sheet is up, call `Alert.alert` from a timer. Dismiss that alert, then tap Approve: it signs, and only the grant's text was ever on the sheet. 5. Type in a `TextInput` and leave the keyboard open, then call `sign`. The keyboard closes, the sheet shows, and Approve signs (no `E_OBSCURED`). Repeat after the keyboard has been dismissed. 6. **Double tap.** Draw a JS button where Approve will appear whose `onPressIn` calls `sign`. Double-tap it quickly. The sheet shows with Approve disabled, the second tap does nothing, and nothing is signed until Approve enables and is tapped again. Repeat with a triple tap. -7. **Cover, then uncover.** While the sheet is up, put an opaque box over Approve two ways: an `OverKeyboardView` (react-native-keyboard-controller), and an `InputAccessoryView` on a `TextInput` focused from a timer. Hide each from its own `onPressIn`. Tap the box: nothing is signed, and Approve enables only 0.7 s after the box is gone. Then open the keyboard, mount the `OverKeyboardView` and call `sign`: the keyboard closes, the view is left in the keyboard's window, and Approve stays disabled until the view is removed. **Randomised hide:** about 50 times, mount the `OverKeyboardView` over Approve while the sheet is up and hide it from a timer with a random delay of 0 to 1.5 s, logging when it hid (`performance.now()`) and when Approve enabled (watch `isEnabled`, or record the screen at 120 fps). Approve must never enable less than 0.7 s after the box is gone. +7. **Cover, then uncover.** While the sheet is up, put an opaque box over Approve two ways: an `OverKeyboardView` (react-native-keyboard-controller), and an `InputAccessoryView` on a `TextInput` focused from a timer. Hide each from its own `onPressIn`. Tap the box: nothing is signed, and Approve enables only 0.7 s after the box is gone. Then open the keyboard, mount the `OverKeyboardView` and call `sign`: the keyboard closes, the view is left in the keyboard's window, and Approve stays disabled until the view is removed. **Randomised hide:** about 50 times, mount the `OverKeyboardView` over Approve while the sheet is up and hide it from a timer with a random delay of 0 to 1.5 s, logging when it hid (`performance.now()`) and when Approve enabled (watch `isEnabled`, or record the screen at 120 fps). Approve must never enable less than 0.7 s after the box is gone. **Cover after arming:** wait until Approve enables, then mount the `OverKeyboardView` over it and hide it from its own `onPressIn`. Approve disables within a frame of the box appearing. Tap twice quickly: the first tap lands on the box, the second does nothing, and Approve enables again only 0.7 s after the box is gone. 8. **Alert, then no key window.** Call `Alert.alert` from a timer while the sheet is up, then dismiss it. Approve enables within about a second and signs (the sheet takes key back), with no `E_OBSCURED`. 9. **iPad pointer.** With a trackpad or mouse, hover over Approve until the pointer highlights it, then click. It signs (no `E_OBSCURED`, Approve not stuck disabled). 10. **VoiceOver.** Turn VoiceOver on and call `sign`. The grant text is read, Approve is announced dimmed until it arms, and double-tapping it then signs. **Full Keyboard Access:** on an iPad with a hardware keyboard, Tab to Approve and press Space; the same. 11. **Stage Manager and Split View (iPad).** Call `sign` with Kin in Split View, then in Stage Manager overlapped by another app's window. Tap the other app, then back into Kin's sheet: Approve is disabled for 0.7 s after Kin's window becomes key again, then signs. Record whether the other app's window can cover the sheet while Approve is armed. -12. **Picture in picture.** Start the browser preview's picture in picture, then call `sign`: the PiP window closes as the sheet shows. Then start a video in picture in picture from Safari, drag it over the sheet's text and tap Approve: it signs, because the module can't see or end another app's PiP window (accepted in the approvals spec's threat model). Record both, and whether the PiP window could take the tap. +12. **Picture in picture.** Start the browser preview's picture in picture, then call `sign`: the PiP window closes as the sheet shows. With the sheet up, start web-view picture in picture from a timer (`injectJavaScript` calling `requestPictureInPicture()` on a playing `