diff --git a/apps/server/src/kin/approvals/rpcHandlers.ts b/apps/server/src/kin/approvals/rpcHandlers.ts new file mode 100644 index 0000000000000..0b07100bddb46 --- /dev/null +++ b/apps/server/src/kin/approvals/rpcHandlers.ts @@ -0,0 +1,30 @@ +import { KinApprovalError, KinApprovalRpcs } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as RpcGroup from "effect/rpc/RpcGroup"; + +import type { AuthenticatedSession } from "../../auth/EnvironmentAuth.ts"; + +const group = RpcGroup.make(...KinApprovalRpcs); +// Every method refuses until its task lands (APPR-3, -4, -5, -10); nothing here can approve. +const unavailable = Effect.fail( + new KinApprovalError({ reason: "unavailable", message: "Kin approvals are unavailable." }), +); + +export const makeKinApprovalHandlers = (_session: AuthenticatedSession) => + Effect.sync(() => + group.of({ + "kin.approvals.list": () => Stream.fromEffect(unavailable), + "kin.approvals.get": () => unavailable, + "kin.approvals.challenge": () => unavailable, + "kin.approvals.submitGrant": () => unavailable, + "kin.approvals.reject": () => unavailable, + "kin.approvals.keyChallenge": () => unavailable, + "kin.approvals.registerKey": () => unavailable, + "kin.approvals.confirmKey": () => unavailable, + "kin.approvals.listKeys": () => unavailable, + "kin.approvals.revokeKey": () => unavailable, + "kin.audit.list": () => unavailable, + "kin.audit.verify": () => unavailable, + }), + ); diff --git a/apps/server/src/kin/chat/rpcHandlers.test.ts b/apps/server/src/kin/chat/rpcHandlers.test.ts index 88cd07d9aea04..0d2d2c49fa0b0 100644 --- a/apps/server/src/kin/chat/rpcHandlers.test.ts +++ b/apps/server/src/kin/chat/rpcHandlers.test.ts @@ -20,7 +20,7 @@ import { KinAgentId, KinChatId, KinMessageId, - KinRpcs, + KinChatAndBudgetRpcs, KinOrgId, ThreadId, RpcScopeAuthorization, @@ -76,7 +76,7 @@ const probe = WsRpcGroup.omit( tag !== WS_METHODS.serverProbe, ), ); -const group = RpcGroup.make(...KinRpcs, ...probe.requests.values()).middleware( +const group = RpcGroup.make(...KinChatAndBudgetRpcs, ...probe.requests.values()).middleware( RpcScopeAuthorization, ); const seed = Effect.gen(function* () { diff --git a/apps/server/src/kin/rpcHandlers.ts b/apps/server/src/kin/rpcHandlers.ts index 1cf89ddebea30..9aca38a00947f 100644 --- a/apps/server/src/kin/rpcHandlers.ts +++ b/apps/server/src/kin/rpcHandlers.ts @@ -2,6 +2,7 @@ import { KinRpcs } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as RpcGroup from "effect/rpc/RpcGroup"; import type { AuthenticatedSession } from "../auth/EnvironmentAuth.ts"; +import { makeKinApprovalHandlers } from "./approvals/rpcHandlers.ts"; import { makeKinChatHandlers } from "./chat/rpcHandlers.ts"; const group = RpcGroup.make(...KinRpcs); @@ -11,5 +12,6 @@ export const makeKinHandlers = Effect.fn("makeKinHandlers")(function* ( ) { return group.of({ ...(yield* makeKinChatHandlers(session)), + ...(yield* makeKinApprovalHandlers(session)), }); }); diff --git a/docs/kin/specs/approvals.md b/docs/kin/specs/approvals.md index d2dd1d1a9652b..72a69c40217ab 100644 --- a/docs/kin/specs/approvals.md +++ b/docs/kin/specs/approvals.md @@ -275,7 +275,7 @@ export const KinGrantPayload = Schema.Struct({ 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). 7. `kind`, `target`, `targetDigest`, `headSha`, `base`, `mergeMethod` equal the server's record → `target_mismatch`. -8. `|now − iat| ≤ 300` and `exp − iat ≤ 900` → `time_window`. +8. `now` is a finite number, `|now − iat| ≤ 300`, `iat < exp`, `exp − iat ≤ 900` and `now < exp` → `time_window`. 9. Re-read the PR from GitHub with the bot token; head and base still match → `head_moved` (rotate nonce, refresh card). 10. In one transaction: insert `kin_grants` (`jti` UNIQUE, `(action_id, approver)` UNIQUE) and CAS the action to `approved` → `replayed` on conflict. diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 5dcb4ab545a8b..7e37688b3a5b1 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -76,5 +76,6 @@ export * from "./clientRpcPermissions.ts"; export * from "./kinChat.ts"; export * from "./kinLead.ts"; export * from "./kinTriggers.ts"; +export * from "./kinApprovals.ts"; export * from "./kinRpcs.ts"; diff --git a/packages/contracts/src/kinApprovals.test.ts b/packages/contracts/src/kinApprovals.test.ts new file mode 100644 index 0000000000000..6457e4a7173b0 --- /dev/null +++ b/packages/contracts/src/kinApprovals.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { BranchName, KinApprovalsRegisterKeyInput, KinContentPath } from "./kinApprovals.ts"; + +const accepts = (schema: Schema.Top, value: unknown) => + Schema.is(schema as Schema.Codec)(value); + +describe("approval names", () => { + it.each(["main", "feature/kin-1", "release/v1.2", "a+b_c-d"])("accepts branch %s", (name) => { + expect(accepts(BranchName, name)).toBe(true); + }); + it.each([ + "../../x", + "x/../y", + "/main", + "main/", + "a//b", + ".hidden", + "a/.b", + "x.lock", + "a/b.lock", + "main.", + ])("refuses branch %s", (name) => { + expect(accepts(BranchName, name)).toBe(false); + }); + it.each(["rules.md", "memory/people/priya.md", ".kin/rules.md"])("accepts path %s", (path) => { + expect(accepts(KinContentPath, path)).toBe(true); + }); + it.each(["../../.ssh/authorized_keys", "a/../b", "/etc/passwd", "a//b", "./rules.md", "a/"])( + "refuses path %s", + (path) => { + expect(accepts(KinContentPath, path)).toBe(false); + }, + ); + it("caps each attestation certificate", () => { + const input = (cert: string) => ({ + orgId: "org_01", + publicJwk: { kty: "EC", crv: "P-256", x: "x".repeat(43), y: "y".repeat(43) }, + platform: "android", + challenge: "abc", + attestation: { certificateChain: [cert] }, + deviceLabel: "Phone", + }); + const decode = Schema.decodeUnknownExit(KinApprovalsRegisterKeyInput); + expect(decode(input("A".repeat(8192)))._tag).toBe("Success"); + expect(decode(input("A".repeat(8193)))._tag).toBe("Failure"); + }); +}); diff --git a/packages/contracts/src/kinApprovals.ts b/packages/contracts/src/kinApprovals.ts new file mode 100644 index 0000000000000..22cf0a9f596c5 --- /dev/null +++ b/packages/contracts/src/kinApprovals.ts @@ -0,0 +1,623 @@ +import * as Schema from "effect/Schema"; +import * as Rpc from "effect/rpc/Rpc"; + +import { + AuthAccessWriteScope, + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + EnvironmentAuthorizationError, + type AuthEnvironmentScope, +} from "./auth.ts"; +import { + AuthSessionId, + NonNegativeInt, + PositiveInt, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; +import { + KinAgentId, + KinChatId, + KinMessageId, + KinOrgId, + KinPersonId, + KinText, + KinTrimmedText, +} from "./kinChat.ts"; +import { CanonicalUtcTimestamp, KinLevel } from "./kinLead.ts"; +import { PullRequestMergeMethod } from "./pullRequest.ts"; + +const pattern = (regex: RegExp, expected: string) => + Schema.String.check(Schema.makeFilter((value: string) => regex.test(value), { expected })); + +export const Hex64 = pattern(/^[0-9a-f]{64}$/, "64 lowercase hex characters"); +export type Hex64 = typeof Hex64.Type; +export const Sha40 = pattern(/^[0-9a-f]{40}$/, "a 40-character lowercase commit SHA"); +export type Sha40 = typeof Sha40.Type; +export const RepoSlug = pattern( + /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/, + "an owner/name repository slug", +); +export type RepoSlug = typeof RepoSlug.Type; +// The approval key refuses to show anything outside this set (approvals spec section 5), +// so the server refuses it before a card exists. +const SHOWN_PATH = /^[A-Za-z0-9._/+-]{1,255}$/; +// Downstream code builds GitHub URLs and file paths from these, so no segment may climb or be empty. +const segmentsOf = (value: string) => value.split("/"); +// git check-ref-format: no empty, dot-led or `.lock` component, no `..`, no trailing dot. +const isRefName = (value: string) => + !value.includes("..") && + !value.endsWith(".") && + segmentsOf(value).every( + (part) => part !== "" && !part.startsWith(".") && !part.endsWith(".lock"), + ); +const isRelativePath = (value: string) => + segmentsOf(value).every((part) => part !== "" && part !== "." && part !== ".."); +export const BranchName = pattern( + SHOWN_PATH, + "a branch name of letters, digits and . _ - / +", +).check(Schema.makeFilter(isRefName, { expected: "a valid git branch name" })); +export type BranchName = typeof BranchName.Type; +export const KinContentPath = pattern(SHOWN_PATH, "a path of letters, digits and . _ - / +").check( + Schema.makeFilter(isRelativePath, { expected: "a relative path without . or .. segments" }), +); +export type KinContentPath = typeof KinContentPath.Type; +/** RFC 7638 SHA-256 thumbprint of a P-256 JWK, base64url without padding. */ +export const KinKeyThumbprint = pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url JWK thumbprint"); +export type KinKeyThumbprint = typeof KinKeyThumbprint.Type; +// Ids the phone shows in a prompt take only the device's id characters (§5). +const shownId = Schema.makeFilter((value: string) => /^[A-Za-z0-9._-]+$/.test(value), { + expected: "an id of letters, digits and . _ -", +}); +const Base64UrlString = pattern(/^[A-Za-z0-9_-]+$/, "unpadded base64url"); + +export const KinActionId = TrimmedNonEmptyString.pipe(Schema.brand("KinActionId")); +export type KinActionId = typeof KinActionId.Type; +export const KinGrantId = TrimmedNonEmptyString.pipe(Schema.brand("KinGrantId")); +export type KinGrantId = typeof KinGrantId.Type; + +export const KinActionClass = Schema.Literals(["read", "talk", "work", "privileged"]); +export type KinActionClass = typeof KinActionClass.Type; + +export const KinActionKind = Schema.Literals([ + "merge_pull_request", + "delete_branch", + "set_level", + "change_rules", + "memory_purge", + "register_approver_key", + "deploy", + "release", + "spend", + "use_secret", + "set_delegation", + "set_next_of_kin", + "admit_outside_agent", +]); +export type KinActionKind = typeof KinActionKind.Type; + +export const KinActionTarget = Schema.Union([ + Schema.TaggedStruct("pull_request", { + host: Schema.Literal("github.com"), + repo: RepoSlug, + number: PositiveInt, + mergeMethod: PullRequestMergeMethod, + deleteBranchAfter: Schema.Boolean, + }), + Schema.TaggedStruct("branch", { + host: Schema.Literal("github.com"), + repo: RepoSlug, + ref: BranchName, + }), + Schema.TaggedStruct("content", { path: KinContentPath, sha256: Hex64 }), + Schema.TaggedStruct("level", { + agentId: KinAgentId.check(shownId), + chatId: Schema.optional(KinChatId.check(shownId)), + level: KinLevel, + }), + // Only an attested hardware key can be activated, so a grant never targets any other (§4). + Schema.TaggedStruct("device_key", { + thumbprint: KinKeyThumbprint, + hardware: Schema.Literals(["secure_enclave", "strongbox", "tee"]), + attested: Schema.Literal(true), + }), +]); +export type KinActionTarget = typeof KinActionTarget.Type; + +/** The target each kind takes. Kinds missing here have no target yet and can't be requested. */ +const KIN_ACTION_TARGET_TAG = { + merge_pull_request: "pull_request", + delete_branch: "branch", + set_level: "level", + change_rules: "content", + memory_purge: "content", + register_approver_key: "device_key", +} as const satisfies Partial>; + +export const KinCheckRun = Schema.Struct({ + name: KinTrimmedText, + required: Schema.Boolean, + status: Schema.Literals(["passed", "failed", "pending", "skipped"]), +}); +export type KinCheckRun = typeof KinCheckRun.Type; + +/** Facts the server read itself (GitHub, the memory repo). The agent never supplies them. */ +export const KinResolvedTarget = Schema.Union([ + Schema.TaggedStruct("pull_request", { + headSha: Sha40, + base: BranchName, + head: BranchName, + title: KinText, + additions: NonNegativeInt, + deletions: NonNegativeInt, + files: NonNegativeInt, + checks: Schema.Array(KinCheckRun), + }), + Schema.TaggedStruct("branch", { headSha: Sha40 }), + Schema.TaggedStruct("none", {}), +]); +export type KinResolvedTarget = typeof KinResolvedTarget.Type; + +export const KinPendingActionState = Schema.Literals([ + "awaiting_approval", + "approved", + "executing", + "succeeded", + "failed", + "interrupted", + "rejected", + "expired", + "voided", + "cancelled", +]); +export type KinPendingActionState = typeof KinPendingActionState.Type; + +export const KinProvenanceRole = Schema.Literals(["owner", "member", "guest", "none"]); +export type KinProvenanceRole = typeof KinProvenanceRole.Type; +export const KinHumanRef = Schema.Struct({ humanId: KinPersonId }); +export type KinHumanRef = typeof KinHumanRef.Type; + +export const KinProvenance = Schema.Struct({ + startedBy: Schema.Union([KinHumanRef, Schema.Literal("schedule"), Schema.Literal("github")]), + startedByRole: KinProvenanceRole, + chain: Schema.Array( + Schema.Struct({ + kind: TrimmedNonEmptyString, + id: TrimmedNonEmptyString, + authorRole: KinProvenanceRole, + }), + ), + afterNonOwnerMessage: Schema.optional( + Schema.Struct({ humanId: KinPersonId, messageId: KinMessageId }), + ), +}); +export type KinProvenance = typeof KinProvenance.Type; + +// Phase 5 two-key approvals and phase 3 next of kin add members here, not a migration. +export const KinApproverRequirement = Schema.Struct({ role: Schema.Literal("owner") }); +export type KinApproverRequirement = typeof KinApproverRequirement.Type; + +export const KinPendingAction = Schema.Struct({ + id: KinActionId, + orgId: KinOrgId, + idempotencyKey: Hex64, + kind: KinActionKind, + target: KinActionTarget, + resolved: KinResolvedTarget, + targetDigest: Hex64, + nonce: Base64UrlString, + revision: NonNegativeInt, + reason: KinText.check(Schema.isMaxLength(500)), + requestedBy: Schema.Struct({ agentId: KinAgentId, threadId: ThreadId }), + provenance: KinProvenance, + requiredApprovers: Schema.Array(KinApproverRequirement), + state: KinPendingActionState, + stateReason: Schema.optional(KinText), + createdAt: CanonicalUtcTimestamp, + updatedAt: CanonicalUtcTimestamp, + expiresAt: CanonicalUtcTimestamp, +}); +export type KinPendingAction = typeof KinPendingAction.Type; + +export const KinApproverPublicJwk = Schema.Struct({ + kty: Schema.Literal("EC"), + crv: Schema.Literal("P-256"), + x: pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url P-256 coordinate"), + y: pattern(/^[A-Za-z0-9_-]{43}$/, "a base64url P-256 coordinate"), +}); +export type KinApproverPublicJwk = typeof KinApproverPublicJwk.Type; + +export const KinApproverKeyState = Schema.Literals(["pending", "active", "revoked"]); +export type KinApproverKeyState = typeof KinApproverKeyState.Type; +export const KinApproverKeyPlatform = Schema.Literals(["ios", "android"]); +export type KinApproverKeyPlatform = typeof KinApproverKeyPlatform.Type; +export const KinApproverKeyHardware = Schema.Literals([ + "secure_enclave", + "strongbox", + "tee", + "software", +]); +export type KinApproverKeyHardware = typeof KinApproverKeyHardware.Type; + +export const KinApproverKey = Schema.Struct({ + orgId: KinOrgId, + thumbprint: KinKeyThumbprint, + publicJwk: KinApproverPublicJwk, + humanId: KinPersonId, + deviceLabel: KinTrimmedText.check(Schema.isMaxLength(80)), + platform: KinApproverKeyPlatform, + hardware: KinApproverKeyHardware, + attested: Schema.Boolean, + sessionId: Schema.optional(AuthSessionId), + state: KinApproverKeyState, + createdAt: CanonicalUtcTimestamp, + confirmedAt: Schema.optional(CanonicalUtcTimestamp), + revokedAt: Schema.optional(CanonicalUtcTimestamp), +}); +export type KinApproverKey = typeof KinApproverKey.Type; + +const KIN_GRANT_TYP = "kin-grant+jws"; +export const KIN_GRANT_MAX_LIFETIME_SECONDS = 900; +export const KIN_GRANT_MAX_CLOCK_SKEW_SECONDS = 300; + +export const KinGrantHeader = Schema.Struct({ + typ: Schema.Literal(KIN_GRANT_TYP), + alg: Schema.Literal("ES256"), + kid: KinKeyThumbprint, +}); +export type KinGrantHeader = typeof KinGrantHeader.Type; + +const SignedInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); + +const KinGrantPayloadFields = { + v: Schema.Literal(1), + orgId: KinOrgId, + actionId: KinActionId, + revision: SignedInt, + nonce: Base64UrlString, + jti: Base64UrlString, + kind: KinActionKind, + targetDigest: Hex64, + target: KinActionTarget, + headSha: Schema.optional(Sha40), + base: Schema.optional(BranchName), + mergeMethod: Schema.optional(PullRequestMergeMethod), + approver: Schema.Struct({ humanId: KinPersonId, kid: KinKeyThumbprint }), + decision: Schema.Literal("approve"), + iat: SignedInt, + exp: SignedInt, +}; + +type GrantFacts = { + readonly kind: KinActionKind; + readonly target: KinActionTarget; + readonly headSha?: string | undefined; + readonly base?: string | undefined; + readonly mergeMethod?: string | undefined; +}; + +/** Field presence per kind (approvals spec section 5), shared by the payload and the challenge. */ +const grantFactsMatchKind = Schema.makeFilter( + (grant: GrantFacts) => { + const tag = (KIN_ACTION_TARGET_TAG as Partial>)[grant.kind]; + if (tag === undefined) return `kind ${grant.kind} can't be granted yet`; + if (grant.target._tag !== tag) return `kind ${grant.kind} needs a ${tag} target`; + const pinsHead = grant.kind === "merge_pull_request" || grant.kind === "delete_branch"; + if (pinsHead !== (grant.headSha !== undefined)) return "headSha presence doesn't match kind"; + const isMerge = grant.kind === "merge_pull_request"; + if (isMerge !== (grant.base !== undefined)) return "base presence doesn't match kind"; + if (isMerge !== (grant.mergeMethod !== undefined)) + return "mergeMethod presence doesn't match kind"; + if (grant.target._tag === "pull_request" && grant.mergeMethod !== grant.target.mergeMethod) + return "mergeMethod differs from the target"; + return true; + }, + { expected: "grant fields that match its kind" }, +); + +// The iat/exp windows are checked by `verifyKinGrant` so they fail as `time_window`. +export const KinGrantPayload = Schema.Struct(KinGrantPayloadFields).check(grantFactsMatchKind); +export type KinGrantPayload = typeof KinGrantPayload.Type; + +const { jti: _jti, iat: _iat, exp: _exp, ...unsignedFields } = KinGrantPayloadFields; +/** What `challenge` returns: the payload minus the fields the device adds (`jti`, `iat`, `exp`). */ +export const KinGrantUnsignedPayload = Schema.Struct(unsignedFields).check(grantFactsMatchKind); +export type KinGrantUnsignedPayload = typeof KinGrantUnsignedPayload.Type; + +export const KinGrantRejectionReason = Schema.Literals([ + "malformed", + "unknown_key", + "revoked_key", + "bad_signature", + "not_owner", + "session_mismatch", + "stale", + "target_mismatch", + "time_window", + "head_moved", + "replayed", +]); +export type KinGrantRejectionReason = typeof KinGrantRejectionReason.Type; + +export const KinGrant = Schema.Struct({ + id: KinGrantId, + orgId: KinOrgId, + actionId: KinActionId, + revision: NonNegativeInt, + jti: Base64UrlString, + approverHumanId: KinPersonId, + keyThumbprint: KinKeyThumbprint, + compact: Schema.String, + iat: SignedInt, + exp: SignedInt, + acceptedAt: CanonicalUtcTimestamp, + consumedAt: Schema.NullOr(CanonicalUtcTimestamp), +}); +export type KinGrant = typeof KinGrant.Type; + +export const KinAuditEvent = Schema.Literals([ + "action_requested", + "action_refreshed", + "grant_accepted", + "grant_rejected", + "action_rejected", + "action_voided", + "execution_started", + "execution_finished", + "execution_reconciled", + "key_registered", + "key_confirmed", + "key_revoked", + "credential_check_failed", +]); +export type KinAuditEvent = typeof KinAuditEvent.Type; + +export const KinAuditEntry = Schema.Struct({ + id: TrimmedNonEmptyString, + orgId: KinOrgId, + seq: PositiveInt, + at: CanonicalUtcTimestamp, + event: KinAuditEvent, + actionId: Schema.optional(KinActionId), + kind: Schema.optional(KinActionKind), + target: Schema.optional(KinActionTarget), + headSha: Schema.optional(Sha40), + grantJti: Schema.optional(KinText), + keyThumbprint: Schema.optional(KinKeyThumbprint), + deviceLabel: Schema.optional(KinText), + sessionId: Schema.optional(AuthSessionId), + provenance: Schema.optional(KinProvenance), + result: Schema.optional(KinText), + prevHash: Hex64, + hash: Hex64, +}); +export type KinAuditEntry = typeof KinAuditEntry.Type; + +/** What `get` and `list` show. Non-owners get the redacted card and never a challenge. */ +export const KinApprovalView = Schema.Union([ + Schema.TaggedStruct("full", { + action: KinPendingAction, + canApprove: Schema.Literal(true), + }), + Schema.TaggedStruct("redacted", { + actionId: KinActionId, + orgId: KinOrgId, + kind: KinActionKind, + repo: Schema.NullOr(RepoSlug), + number: Schema.NullOr(PositiveInt), + title: Schema.NullOr(KinText), + state: KinPendingActionState, + waitingOn: KinText, + canApprove: Schema.Literal(false), + }), +]); +export type KinApprovalView = typeof KinApprovalView.Type; + +export const KinApprovalListEvent = Schema.Union([ + Schema.TaggedStruct("snapshot", { actions: Schema.Array(KinApprovalView) }), + Schema.TaggedStruct("action", { action: KinApprovalView }), +]); +export type KinApprovalListEvent = typeof KinApprovalListEvent.Type; + +export const KinApprovalsListInput = Schema.Struct({ orgId: Schema.optional(KinOrgId) }); +export type KinApprovalsListInput = typeof KinApprovalsListInput.Type; +export const KinApprovalsActionInput = Schema.Struct({ actionId: KinActionId }); +export type KinApprovalsActionInput = typeof KinApprovalsActionInput.Type; +export const KinApprovalsChallengeResult = Schema.Struct({ + payload: KinGrantUnsignedPayload, + resolved: KinResolvedTarget, +}); +export type KinApprovalsChallengeResult = typeof KinApprovalsChallengeResult.Type; +export const KinApprovalsSubmitGrantInput = Schema.Struct({ + compact: Schema.String.check(Schema.isMaxLength(16_384)), +}); +export type KinApprovalsSubmitGrantInput = typeof KinApprovalsSubmitGrantInput.Type; +export const KinApprovalsRejectInput = Schema.Struct({ + actionId: KinActionId, + revision: NonNegativeInt, +}); +export type KinApprovalsRejectInput = typeof KinApprovalsRejectInput.Type; +export const KinApprovalsDecisionResult = Schema.Struct({ + actionId: KinActionId, + state: KinPendingActionState, +}); +export type KinApprovalsDecisionResult = typeof KinApprovalsDecisionResult.Type; + +export const KinApprovalsKeyChallengeInput = Schema.Struct({}); +export type KinApprovalsKeyChallengeInput = typeof KinApprovalsKeyChallengeInput.Type; +export const KinApprovalsKeyChallengeResult = Schema.Struct({ + challenge: Base64UrlString, + expiresAt: CanonicalUtcTimestamp, +}); +export type KinApprovalsKeyChallengeResult = typeof KinApprovalsKeyChallengeResult.Type; +export const KinApprovalsRegisterKeyInput = Schema.Struct({ + orgId: KinOrgId, + publicJwk: KinApproverPublicJwk, + platform: KinApproverKeyPlatform, + challenge: Base64UrlString, + // Base64 DER certificates, leaf first. Required on Android; the server derives `hardware`. + attestation: Schema.optional( + Schema.Struct({ + certificateChain: Schema.Array(Schema.String.check(Schema.isMaxLength(8192))).check( + Schema.isMaxLength(10), + ), + }), + ), + deviceLabel: KinTrimmedText.check(Schema.isMaxLength(80)), +}); +export type KinApprovalsRegisterKeyInput = typeof KinApprovalsRegisterKeyInput.Type; +export const KinApprovalsRegisterKeyResult = Schema.Struct({ + key: KinApproverKey, + code: pattern(/^\d{6}$/, "a 6-digit code"), +}); +export type KinApprovalsRegisterKeyResult = typeof KinApprovalsRegisterKeyResult.Type; +export const KinApprovalsKeyInput = Schema.Struct({ + orgId: KinOrgId, + thumbprint: KinKeyThumbprint, +}); +export type KinApprovalsKeyInput = typeof KinApprovalsKeyInput.Type; +export const KinApprovalsConfirmKeyInput = Schema.Struct({ + ...KinApprovalsKeyInput.fields, + code: pattern(/^\d{6}$/, "a 6-digit code"), +}); +export type KinApprovalsConfirmKeyInput = typeof KinApprovalsConfirmKeyInput.Type; +export const KinApprovalsOrgInput = Schema.Struct({ orgId: KinOrgId }); +export type KinApprovalsOrgInput = typeof KinApprovalsOrgInput.Type; +export const KinApprovalsListKeysResult = Schema.Struct({ keys: Schema.Array(KinApproverKey) }); +export type KinApprovalsListKeysResult = typeof KinApprovalsListKeysResult.Type; + +export const KinAuditListInput = Schema.Struct({ + orgId: KinOrgId, + afterSeq: Schema.optional(NonNegativeInt), + limit: PositiveInt.check(Schema.isLessThanOrEqualTo(200)), +}); +export type KinAuditListInput = typeof KinAuditListInput.Type; +export const KinAuditListResult = Schema.Struct({ + entries: Schema.Array(KinAuditEntry), + hasMore: Schema.Boolean, +}); +export type KinAuditListResult = typeof KinAuditListResult.Type; +export const KinAuditVerifyResult = Schema.Struct({ + ok: Schema.Boolean, + checked: NonNegativeInt, + firstBadSeq: Schema.NullOr(PositiveInt), +}); +export type KinAuditVerifyResult = typeof KinAuditVerifyResult.Type; + +export class KinApprovalError extends Schema.TaggedError()("KinApprovalError", { + reason: Schema.Union([ + KinGrantRejectionReason, + Schema.Literals([ + "not_found", + "unavailable", + "disabled", + "invalid_state", + "unsupported_kind", + "not_a_lead", + "bad_challenge", + "bad_code", + "not_local", + ]), + ]), + message: Schema.String, +}) {} + +export const KIN_APPROVAL_WS_METHODS = { + list: "kin.approvals.list", + get: "kin.approvals.get", + challenge: "kin.approvals.challenge", + submitGrant: "kin.approvals.submitGrant", + reject: "kin.approvals.reject", + keyChallenge: "kin.approvals.keyChallenge", + registerKey: "kin.approvals.registerKey", + confirmKey: "kin.approvals.confirmKey", + listKeys: "kin.approvals.listKeys", + revokeKey: "kin.approvals.revokeKey", + auditList: "kin.audit.list", + auditVerify: "kin.audit.verify", +} as const; + +const error = Schema.Union([KinApprovalError, EnvironmentAuthorizationError]); + +export const KinApprovalRpcs = [ + Rpc.make(KIN_APPROVAL_WS_METHODS.list, { + payload: KinApprovalsListInput, + success: KinApprovalListEvent, + error, + stream: true, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.get, { + payload: KinApprovalsActionInput, + success: KinApprovalView, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.challenge, { + payload: KinApprovalsActionInput, + success: KinApprovalsChallengeResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.submitGrant, { + payload: KinApprovalsSubmitGrantInput, + success: KinApprovalsDecisionResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.reject, { + payload: KinApprovalsRejectInput, + success: KinApprovalsDecisionResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.keyChallenge, { + payload: KinApprovalsKeyChallengeInput, + success: KinApprovalsKeyChallengeResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.registerKey, { + payload: KinApprovalsRegisterKeyInput, + success: KinApprovalsRegisterKeyResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.confirmKey, { + payload: KinApprovalsConfirmKeyInput, + success: KinApproverKey, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.listKeys, { + payload: KinApprovalsOrgInput, + success: KinApprovalsListKeysResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.revokeKey, { + payload: KinApprovalsKeyInput, + success: KinApproverKey, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.auditList, { + payload: KinAuditListInput, + success: KinAuditListResult, + error, + }), + Rpc.make(KIN_APPROVAL_WS_METHODS.auditVerify, { + payload: KinApprovalsOrgInput, + success: KinAuditVerifyResult, + error, + }), +] as const; + +/** The outer gate only; person, key and signature checks are the real ones. */ +export const KIN_APPROVAL_RPC_SCOPES = { + [KIN_APPROVAL_WS_METHODS.list]: AuthOrchestrationReadScope, + [KIN_APPROVAL_WS_METHODS.get]: AuthOrchestrationReadScope, + [KIN_APPROVAL_WS_METHODS.challenge]: AuthOrchestrationOperateScope, + [KIN_APPROVAL_WS_METHODS.submitGrant]: AuthOrchestrationOperateScope, + [KIN_APPROVAL_WS_METHODS.reject]: AuthOrchestrationOperateScope, + [KIN_APPROVAL_WS_METHODS.keyChallenge]: AuthAccessWriteScope, + [KIN_APPROVAL_WS_METHODS.registerKey]: AuthAccessWriteScope, + [KIN_APPROVAL_WS_METHODS.confirmKey]: AuthAccessWriteScope, + [KIN_APPROVAL_WS_METHODS.listKeys]: AuthAccessWriteScope, + [KIN_APPROVAL_WS_METHODS.revokeKey]: AuthAccessWriteScope, + [KIN_APPROVAL_WS_METHODS.auditList]: AuthAccessWriteScope, + [KIN_APPROVAL_WS_METHODS.auditVerify]: AuthAccessWriteScope, +} as const satisfies Record< + (typeof KIN_APPROVAL_WS_METHODS)[keyof typeof KIN_APPROVAL_WS_METHODS], + AuthEnvironmentScope +>; diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index f9aaf7228d157..cb0f3117836ae 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -1,6 +1,7 @@ import * as Rpc from "effect/rpc/Rpc"; import * as Schema from "effect/Schema"; import { KinBudget, KinBudgetGetInput, KinBudgetSetInput } from "./kinLead.ts"; +import { KinApprovalRpcs, KIN_APPROVAL_RPC_SCOPES } from "./kinApprovals.ts"; import { KinChatError, KinChatRpcs, KIN_CHAT_RPC_SCOPES } from "./kinChat.ts"; import { EnvironmentAuthorizationError, @@ -21,9 +22,10 @@ const KinBudgetRpcs = [ }), ] as const; export const KinChatAndBudgetRpcs = [...KinChatRpcs, ...KinBudgetRpcs] as const; -export const KinRpcs = [...KinChatAndBudgetRpcs] as const; +export const KinRpcs = [...KinChatAndBudgetRpcs, ...KinApprovalRpcs] as const; export const KIN_RPC_SCOPES = { ...KIN_CHAT_RPC_SCOPES, + ...KIN_APPROVAL_RPC_SCOPES, "kin.budget.get": AuthOrchestrationReadScope, "kin.budget.set": AuthSettingsWriteScope, } as const; @@ -39,4 +41,16 @@ export const KIN_RPC_AGGREGATES = { "kin.messages.send": "kin-chat", "kin.messages.markRead": "kin-chat", "kin.widgets.act": "kin-chat", + "kin.approvals.list": "kin-approvals", + "kin.approvals.get": "kin-approvals", + "kin.approvals.challenge": "kin-approvals", + "kin.approvals.submitGrant": "kin-approvals", + "kin.approvals.reject": "kin-approvals", + "kin.approvals.keyChallenge": "kin-approvals", + "kin.approvals.registerKey": "kin-approvals", + "kin.approvals.confirmKey": "kin-approvals", + "kin.approvals.listKeys": "kin-approvals", + "kin.approvals.revokeKey": "kin-approvals", + "kin.audit.list": "kin-approvals", + "kin.audit.verify": "kin-approvals", } as const; diff --git a/packages/shared/package.json b/packages/shared/package.json index 5d9a87ac7719d..1b32445bb264d 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -187,6 +187,10 @@ "types": "./src/dpop.ts", "import": "./src/dpop.ts" }, + "./kinGrant": { + "types": "./src/kinGrant.ts", + "import": "./src/kinGrant.ts" + }, "./desktopBootstrapToken": { "types": "./src/desktopBootstrapToken.ts", "import": "./src/desktopBootstrapToken.ts" diff --git a/packages/shared/src/kinGrant.test.ts b/packages/shared/src/kinGrant.test.ts new file mode 100644 index 0000000000000..845023e6b9361 --- /dev/null +++ b/packages/shared/src/kinGrant.test.ts @@ -0,0 +1,266 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no KeyObject, generateKeyPairSync, or sign. +import * as NodeCrypto from "node:crypto"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- reads the APPR-6 fixture synchronously at collection time. +import * as NodeFS from "node:fs"; + +import { assert, describe, it } from "@effect/vitest"; +import type { KinApproverPublicJwk, KinGrantHeader, KinGrantPayload } from "@t3tools/contracts"; + +import { computeDpopJwkThumbprint } from "./dpop.ts"; +import { + decodeKinGrant, + encodeGrantSigningInput, + verifyKinGrant, + type KinGrantVerification, +} from "./kinGrant.ts"; +import { stableStringify } from "./relaySigning.ts"; + +const P256_N = BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); +const NOW = 1_798_761_600; + +function makeKey() { + const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + const jwk = publicKey.export({ format: "jwk" }); + const publicJwk = { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y } as KinApproverPublicJwk; + return { privateKey, publicJwk, kid: computeDpopJwkThumbprint(publicJwk) }; +} + +const toBigInt = (bytes: Uint8Array) => BigInt(`0x${Buffer.from(bytes).toString("hex")}`); +const fromBigInt = (value: bigint) => Buffer.from(value.toString(16).padStart(64, "0"), "hex"); + +/** r‖s with s forced low or high; Node itself returns either. */ +function signRaw(privateKey: NodeCrypto.KeyObject, signingInput: string, high = false) { + const raw = NodeCrypto.sign("sha256", Buffer.from(signingInput), { + key: privateKey, + dsaEncoding: "ieee-p1363", + }); + const s = toBigInt(raw.subarray(32)); + const low = s > P256_N / 2n ? P256_N - s : s; + return Buffer.concat([raw.subarray(0, 32), fromBigInt(high ? P256_N - low : low)]).toString( + "base64url", + ); +} + +const b64 = (text: string) => Buffer.from(text).toString("base64url"); +const signText = (privateKey: NodeCrypto.KeyObject, header: string, payload: string) => { + const input = `${b64(header)}.${b64(payload)}`; + return `${input}.${signRaw(privateKey, input)}`; +}; + +function grantFor(kid: string, overrides: Partial = {}) { + const header = { typ: "kin-grant+jws", alg: "ES256", kid } as KinGrantHeader; + const payload = { + v: 1, + orgId: "org_01", + actionId: "act_01JD7Z00000000000000000000", + revision: 2, + nonce: "c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA", + jti: "ZGV2aWNlLWp0aS0xNi1ieXRlcw", + kind: "merge_pull_request", + targetDigest: "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + target: { + _tag: "pull_request", + host: "github.com", + repo: "GLDRoger/t3code", + number: 212, + mergeMethod: "squash", + deleteBranchAfter: false, + }, + headSha: "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678", + base: "main", + mergeMethod: "squash", + approver: { humanId: "h_owner", kid }, + decision: "approve", + iat: NOW - 10, + exp: NOW + 590, + ...overrides, + } as KinGrantPayload; + return { header, payload }; +} + +function signedGrant(key: ReturnType, overrides: Partial = {}) { + const { header, payload } = grantFor(key.kid, overrides); + const signingInput = encodeGrantSigningInput(header, payload); + return { + header, + payload, + signingInput, + compact: `${signingInput}.${signRaw(key.privateKey, signingInput)}`, + }; +} + +describe("verifyKinGrant", () => { + const key = makeKey(); + const verify = (compact: string, nowEpochSeconds = NOW, publicJwk = key.publicJwk) => + verifyKinGrant({ compact, publicJwk, nowEpochSeconds }); + + it("accepts a grant signed with a P-256 key and returns its payload", () => { + const { compact, payload } = signedGrant(key); + const result = verify(compact); + assert.isTrue(result.ok); + if (result.ok) assert.deepStrictEqual(result.grant.payload, payload); + }); + + it("signs canonical JSON with sorted keys in both parts", () => { + const { signingInput } = signedGrant(key); + const [header, payload] = signingInput.split(".") as [string, string]; + assert.strictEqual( + Buffer.from(header, "base64url").toString(), + `{"alg":"ES256","kid":"${key.kid}","typ":"kin-grant+jws"}`, + ); + assert.match(Buffer.from(payload, "base64url").toString(), /^\{"actionId":.*,"v":1\}$/); + }); + + it("rejects tampering with typed reasons", () => { + const other = makeKey(); + const { compact, payload, signingInput } = signedGrant(key); + const [headerPart, , signature] = compact.split(".") as [string, string, string]; + const headerText = Buffer.from(headerPart, "base64url").toString(); + const jwkHeader = stableStringify({ ...JSON.parse(headerText), jwk: key.publicJwk }); + const sortedPayload = Buffer.from(signingInput.split(".")[1]!, "base64url").toString(); + + const cases: ReadonlyArray< + readonly [string, string, Extract["reason"], number?] + > = [ + [ + "a payload byte", + `${headerPart}.${b64(sortedPayload.replace("212", "213"))}.${signature}`, + "bad_signature", + ], + ["a header carrying a jwk", signText(key.privateKey, jwkHeader, sortedPayload), "malformed"], + [ + "the wrong typ", + signText(key.privateKey, headerText.replace("kin-grant+jws", "dpop+jwt"), sortedPayload), + "malformed", + ], + [ + "non-canonical whitespace", + signText(key.privateKey, headerText, JSON.stringify(JSON.parse(sortedPayload), null, 1)), + "malformed", + ], + [ + "unsorted payload keys", + signText( + key.privateKey, + headerText, + JSON.stringify({ v: 1, ...JSON.parse(sortedPayload) }), + ), + "malformed", + ], + [ + "approver.kid differing from the header kid", + signedGrant(key, { approver: { humanId: payload.approver.humanId, kid: other.kid } }) + .compact, + "unknown_key", + ], + [ + "a high-S twin of a valid signature", + `${signingInput}.${signRaw(key.privateKey, signingInput, true)}`, + "bad_signature", + ], + ["an expired grant", compact, "time_window", payload.exp], + ["an iat more than 300 s off", compact, "time_window", payload.iat + 301], + [ + "exp more than 900 s after iat", + signedGrant(key, { exp: NOW - 10 + 901 }).compact, + "time_window", + ], + ["exp not after iat", signedGrant(key, { exp: NOW - 10 }).compact, "time_window"], + [ + "exp already past, with iat and lifetime in range", + signedGrant(key, { iat: NOW - 100, exp: NOW + 50 }).compact, + "time_window", + NOW + 100, + ], + [ + "exp before iat, with now before both", + signedGrant(key, { iat: NOW + 100, exp: NOW + 50 }).compact, + "time_window", + ], + ["a clock that isn't a number", compact, "time_window", Number.NaN], + [ + "an id that decodes differently from its signed bytes", + signedGrant(key, { orgId: " org_01" as KinGrantPayload["orgId"] }).compact, + "malformed", + ], + [ + "an extra field nested in approver", + signText( + key.privateKey, + headerText, + stableStringify({ ...payload, approver: { ...payload.approver, extra: "x" } }), + ), + "malformed", + ], + ]; + for (const [name, tampered, reason, now] of cases) { + assert.deepStrictEqual(verify(tampered, now), { ok: false, reason }, name); + } + }); + + it("rejects a grant checked against another key", () => { + assert.deepStrictEqual(verify(signedGrant(key).compact, NOW, makeKey().publicJwk), { + ok: false, + reason: "unknown_key", + }); + }); + + it("rejects a valid signature from a key whose thumbprint is in the header but not the signer", () => { + const other = makeKey(); + const { signingInput } = signedGrant(key); + assert.deepStrictEqual(verify(`${signingInput}.${signRaw(other.privateKey, signingInput)}`), { + ok: false, + reason: "bad_signature", + }); + }); +}); + +type GrantVector = { + readonly name: string; + readonly header?: string; + readonly payload?: string; + readonly signingInput?: string; + readonly error?: string; +}; + +describe("APPR-6 grant vectors", () => { + const vectors: { readonly now: number; readonly cases: ReadonlyArray } = JSON.parse( + NodeFS.readFileSync( + new URL( + "../../../apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json", + import.meta.url, + ), + "utf8", + ), + ); + const zeroSignature = Buffer.alloc(64).toString("base64url"); + // Where the server's decoder rightly differs from the device's parser. + const DEVICE_ONLY = new Set([ + // Prompt length is a display rule; the server shows no prompt. + "a long repo and branch over 200 characters are refused", + "a prompt of 201 characters is refused, not cut", + // Time windows fail in verifyKinGrant as time_window, not in the decoder. + "exp more than 900 s after iat", + "exp not after iat", + "iat 301 s ahead of the device clock", + ]); + + it("encodes every accepted grant to the exact bytes the device signs", () => { + for (const vector of vectors.cases.filter((c) => !c.error)) { + const input = encodeGrantSigningInput( + JSON.parse(vector.header!), + JSON.parse(vector.payload!), + ); + assert.strictEqual(input, `${b64(vector.header!)}.${b64(vector.payload!)}`, vector.name); + } + }); + + it("decodes what the device signs and refuses what it refuses", () => { + for (const vector of vectors.cases) { + const input = vector.signingInput ?? `${b64(vector.header!)}.${b64(vector.payload!)}`; + const decoded = decodeKinGrant(`${input}.${zeroSignature}`) !== null; + const expected = DEVICE_ONLY.has(vector.name) || !vector.error; + assert.strictEqual(decoded, expected, vector.name); + } + }); +}); diff --git a/packages/shared/src/kinGrant.ts b/packages/shared/src/kinGrant.ts new file mode 100644 index 0000000000000..3c37ddf705d98 --- /dev/null +++ b/packages/shared/src/kinGrant.ts @@ -0,0 +1,149 @@ +import { p256 } from "@noble/curves/nist"; +import { sha256 } from "@noble/hashes/sha2"; +import { + KIN_GRANT_MAX_CLOCK_SKEW_SECONDS, + KIN_GRANT_MAX_LIFETIME_SECONDS, + KinGrantHeader, + KinGrantPayload, + type KinApproverPublicJwk, + type KinGrantRejectionReason, +} from "@t3tools/contracts"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Exit from "effect/Exit"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import { computeDpopJwkThumbprint } from "./dpop.ts"; +import { stableStringify } from "./relaySigning.ts"; + +const MAX_COMPACT_LENGTH = 16_384; +const BASE64URL = /^[A-Za-z0-9_-]+$/; +const strict = { onExcessProperty: "error" } as const; +const decodeHeader = Schema.decodeUnknownExit(KinGrantHeader, strict); +const decodePayload = Schema.decodeUnknownExit(KinGrantPayload, strict); +const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); +const encoder = new TextEncoder(); + +const encodePart = (value: unknown) => Base64Url.encode(encoder.encode(stableStringify(value))); + +/** The ASCII JWS signing input `b64url(header).b64url(payload)`, each part canonical JSON. */ +export function encodeGrantSigningInput(header: KinGrantHeader, payload: KinGrantPayload): string { + return `${encodePart(header)}.${encodePart(payload)}`; +} + +/** Unpadded base64url with zero trailing bits only: one byte string has one spelling. */ +function strictBase64Url(segment: string): Uint8Array | null { + if (!BASE64URL.test(segment)) return null; + const decoded = Base64Url.decode(segment); + if (Result.isFailure(decoded) || Base64Url.encode(decoded.success) !== segment) return null; + return decoded.success; +} + +/** Bytes that are UTF-8 JSON equal to their own `stableStringify`, or null. */ +function canonicalJson(segment: string): unknown { + const bytes = strictBase64Url(segment); + if (bytes === null) return null; + try { + const text = utf8.decode(bytes); + const value: unknown = JSON.parse(text); + return stableStringify(value) === text ? value : null; + } catch { + return null; + } +} + +export type DecodedKinGrant = { + readonly header: KinGrantHeader; + readonly payload: KinGrantPayload; + readonly signingInput: string; + readonly signature: Uint8Array; +}; + +/** Approvals spec section 5 check 1: shape and canonical bytes. Null means `malformed`. */ +export function decodeKinGrant(compact: string): DecodedKinGrant | null { + if (compact.length > MAX_COMPACT_LENGTH) return null; + const parts = compact.split("."); + if (parts.length !== 3) return null; + const [headerPart, payloadPart, signaturePart] = parts as [string, string, string]; + const header = decodeHeader(canonicalJson(headerPart)); + const payload = decodePayload(canonicalJson(payloadPart)); + const signature = strictBase64Url(signaturePart); + if (Exit.isFailure(header) || Exit.isFailure(payload) || signature?.length !== 64) return null; + const signingInput = `${headerPart}.${payloadPart}`; + // A schema that trims or otherwise transforms a value would make the decoded grant differ from + // the signed bytes; one signed string must have exactly one meaning. + if (encodeGrantSigningInput(header.value, payload.value) !== signingInput) return null; + return { + header: header.value, + payload: payload.value, + signingInput, + signature, + }; +} + +function publicKeyBytes(jwk: KinApproverPublicJwk): Uint8Array | null { + const x = strictBase64Url(jwk.x); + const y = strictBase64Url(jwk.y); + if (x?.length !== 32 || y?.length !== 32) return null; + const key = new Uint8Array(65); + key[0] = 0x04; + key.set(x, 1); + key.set(y, 33); + return key; +} + +export type KinGrantVerification = + | { readonly ok: true; readonly grant: DecodedKinGrant } + | { + readonly ok: false; + readonly reason: Extract< + KinGrantRejectionReason, + "malformed" | "unknown_key" | "bad_signature" | "time_window" + >; + }; + +/** + * Spec section 5 checks 1, 3, 8 and check 2's kid binding: pure, `now` comes in. Passing isn't + * approval: APPR-4's GrantVerifier looks the kid up in the key registry (active, same org) and + * runs checks 4-7, 9 and 10 (owner, session, action state and nonce, live head, jti replay). + */ +export function verifyKinGrant(input: { + readonly compact: string; + readonly publicJwk: KinApproverPublicJwk; + readonly nowEpochSeconds: number; +}): KinGrantVerification { + const grant = decodeKinGrant(input.compact); + if (grant === null) return { ok: false, reason: "malformed" }; + const { header, payload } = grant; + if ( + header.kid !== computeDpopJwkThumbprint(input.publicJwk) || + payload.approver.kid !== header.kid + ) { + return { ok: false, reason: "unknown_key" }; + } + const key = publicKeyBytes(input.publicJwk); + let verified = false; + try { + verified = + key !== null && + p256.verify(grant.signature, sha256(encoder.encode(grant.signingInput)), key, { + prehash: false, + format: "compact", + lowS: true, + }); + } catch { + verified = false; + } + if (!verified) return { ok: false, reason: "bad_signature" }; + const now = input.nowEpochSeconds; + if ( + !Number.isFinite(now) || + Math.abs(now - payload.iat) > KIN_GRANT_MAX_CLOCK_SKEW_SECONDS || + payload.exp <= payload.iat || + payload.exp - payload.iat > KIN_GRANT_MAX_LIFETIME_SECONDS || + now >= payload.exp + ) { + return { ok: false, reason: "time_window" }; + } + return { ok: true, grant }; +}