Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
e29b46f
chore(kin): claim APPR-5 approver keys
Surajsm60720 Nov 8, 2026
22d6135
feat(kin): approver key registry with attestation (APPR-5)
Surajsm60720 Nov 8, 2026
fdccbdf
Merge remote-tracking branch 'origin/kin-appr-1-contracts' into kin-a…
Surajsm60720 Nov 8, 2026
c4a810d
fix(kin): match APPR-6's Android attestation rules and spec the key r…
Surajsm60720 Nov 8, 2026
7407445
fix(kin): register each approver key thumbprint once (APPR-5)
Surajsm60720 Nov 8, 2026
1f4a391
Merge remote-tracking branch 'origin/kin-appr-2-pending-actions' into…
Surajsm60720 Nov 8, 2026
8a59c87
test(kin): generate minimal DER serials in attestation fixtures (APPR-5)
Surajsm60720 Nov 8, 2026
1200526
Merge remote-tracking branch 'origin/kin-appr-2-pending-actions' into…
Surajsm60720 Nov 8, 2026
b17b754
fix(kin): anchor Android chains on the pinned root and refuse repeate…
Surajsm60720 Nov 8, 2026
fdc0446
fix(kin): accept one spelling per approver key coordinate (APPR-5)
Surajsm60720 Nov 8, 2026
41a4de9
fix(kin): reserve the approver key requester id (APPR-5)
Surajsm60720 Nov 8, 2026
de7d052
fix(kin): keep the registering DPoP key on approver keys (APPR-5)
Surajsm60720 Nov 8, 2026
e965b32
Merge remote-tracking branch 'origin/kin-appr-2-pending-actions' into…
Surajsm60720 Nov 8, 2026
fafacc6
Merge remote-tracking branch 'origin/kin-appr-2-pending-actions' into…
Surajsm60720 Nov 8, 2026
e59628d
Merge remote-tracking branch 'origin/kin-appr-2-pending-actions' into…
Surajsm60720 Nov 8, 2026
8f1a258
Merge origin/kin-appr-2-pending-actions into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
ec9b09a
Merge branch 'kin-appr-2-pending-actions' into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
dca6609
fix(kin): revoke approver keys through renewed relay sessions
Surajsm60720 Nov 8, 2026
a8e5751
fix(kin): let repaired phones register approver keys
Surajsm60720 Nov 8, 2026
df6da97
Merge branch 'kin-appr-2-pending-actions' into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
054c6ae
chore: merge kin-appr-2-pending-actions into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
b321992
fix(kin): keep approval handlers off the judge's import graph
Surajsm60720 Nov 8, 2026
79b5743
chore: merge kin-appr-2-pending-actions into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
cb03e8a
chore: merge kin-appr-2-pending-actions into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
3df4ece
Merge branch 'kin-appr-2-pending-actions' into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
018df80
fix(server): report approver key RPCs as disabled when Kin is off
Surajsm60720 Nov 8, 2026
2c0692c
test(server): call keyChallenge without input
Surajsm60720 Nov 8, 2026
86b7772
Merge branch 'kin-appr-2-pending-actions' into kin-appr-5-approver-keys
Surajsm60720 Nov 8, 2026
a34d53f
fix(kin): approver-key reconcile is per org, SQL causes are logged, h…
GLDRoger Nov 8, 2026
f2d32d5
docs(kin): state what attested means for iOS approver keys
GLDRoger Nov 8, 2026
931c85e
Merge origin/kin into kin-appr-5-approver-keys
GLDRoger Nov 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/server/src/kin/KinServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { KinChatService } from "./chat/KinChatService.ts";
import { KinChatHub } from "./chat/KinChatHub.ts";
import { KinBudget } from "./lead/KinBudget.ts";
import { KinEventQueue } from "./lead/KinEventQueue.ts";
import { ApproverKeys } from "./approvals/ApproverKeys.ts";
import { KinStop } from "./lead/KinStop.ts";
import type { KinGithubWebhookLock } from "./triggers/githubWebhooks.ts";

Expand All @@ -17,7 +18,8 @@ export type Services =
| KinEventQueue
| KinChatHub
| KinStop
| KinGithubWebhookLock;
| KinGithubWebhookLock
| ApproverKeys;

export class KinServer extends Context.Service<
KinServer,
Expand Down
526 changes: 526 additions & 0 deletions apps/server/src/kin/approvals/ApproverKeys.test.ts

Large diffs are not rendered by default.

552 changes: 552 additions & 0 deletions apps/server/src/kin/approvals/ApproverKeys.ts

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions apps/server/src/kin/approvals/PendingActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
Expand Down Expand Up @@ -111,6 +112,19 @@ describe("KinPendingActions", () => {
} as unknown as KinPendingActionCreateInput);
assert.isFalse(withExtra.created);
assert.strictEqual(withExtra.action.id, first.action.id);
// Key registration's requester id is reserved, so an agent can't pose as the phone.
for (const requestedBy of [
{ agentId: "kin-approver-keys", threadId: "thread-lead" },
{ agentId: "kin-approver-keys", threadId: "kin-approver-keys" },
]) {
const posing = yield* Effect.exit(
actions.create({
...request("webhook-delivery-2"),
requestedBy,
} as unknown as KinPendingActionCreateInput),
);
assert.isTrue(Exit.isFailure(posing));
}

const twice = yield* Effect.all(
[
Expand Down
13 changes: 12 additions & 1 deletion apps/server/src/kin/approvals/PendingActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const AWAITING_TTL_MS = 7 * 24 * 60 * 60 * 1000;
// A grant lapses at min(exp, acceptedAt + 15 min) (approvals spec section 5).
const GRANT_ACCEPTED_TTL_MS = 15 * 60 * 1000;

/** `registerKey`'s requester: the phone asked, not an agent, so no agent may use this id. */
export const KIN_APPROVER_KEYS_REQUESTER = "kin-approver-keys";
const CreateInput = Schema.Struct({
orgId: KinOrgId,
kind: KinActionKind,
Expand All @@ -51,7 +53,16 @@ const CreateInput = Schema.Struct({
requestedBy: Schema.Struct({ agentId: KinAgentId, threadId: ThreadId }),
provenance: KinProvenance,
source: KinEventId,
});
}).check(
Schema.makeFilter(
({ kind, requestedBy: { agentId, threadId } }) =>
(agentId !== KIN_APPROVER_KEYS_REQUESTER && threadId !== KIN_APPROVER_KEYS_REQUESTER) ||
(kind === "register_approver_key" &&
agentId === KIN_APPROVER_KEYS_REQUESTER &&
threadId === KIN_APPROVER_KEYS_REQUESTER),
{ expected: `a requester other than the reserved ${KIN_APPROVER_KEYS_REQUESTER}` },
),
);
export type KinPendingActionCreateInput = typeof CreateInput.Type;
const decodeCreateInput = Schema.decodeEffect(CreateInput);
const StoredAction = Schema.Struct({
Expand Down
110 changes: 110 additions & 0 deletions apps/server/src/kin/approvals/attestation/AttestationTrust.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// @effect-diagnostics nodeBuiltinImport:off -- X509Certificate for the pinned roots.
import * as NodeCrypto from "node:crypto";

import type { KinApproverKeyPlatform } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientResponse from "effect/http/HttpClientResponse";

import { APPLE_APP_ATTEST_ROOT, GOOGLE_HARDWARE_ATTESTATION_ROOTS } from "./roots.ts";
import type { AttestationTrust } from "./verify.ts";

const STATUS_URL = "https://android.googleapis.com/attestation/status";
const STATUS_TTL = Duration.hours(1);
const StatusList = Schema.Struct({
entries: Schema.Record(Schema.String, Schema.Struct({ status: Schema.String })),
});

export class KinAttestationTrustError extends Schema.TaggedError<KinAttestationTrustError>()(
"KinAttestationTrustError",
{ message: Schema.String },
) {}

export class KinAttestationTrust extends Context.Service<
KinAttestationTrust,
{
/** Android fails rather than trust a chain it couldn't check for revocation. */
readonly load: (
platform: KinApproverKeyPlatform,
) => Effect.Effect<AttestationTrust, KinAttestationTrustError>;
}
>()("t3/kin/approvals/attestation/AttestationTrust/KinAttestationTrust") {}

const hexList = (name: string) =>
Config.String(name).pipe(
Config.withDefault(""),
Config.map((value) =>
value
.split(",")
.map((entry) => entry.trim().toLowerCase().replaceAll(":", ""))
.filter((entry) => entry.length > 0),
),
);

/** Production trust: pinned roots, the release app identity from config, Google's status list. */
export const layer = Layer.effect(
KinAttestationTrust,
Effect.gen(function* () {
const config = yield* Config.all({
androidPackage: Config.String("KIN_ANDROID_PACKAGE").pipe(Config.option),
androidSigners: hexList("KIN_ANDROID_SIGNING_CERT_SHA256"),
appleAppId: Config.String("KIN_IOS_APP_ID").pipe(Config.option),
appleDevelopment: Config.Boolean("KIN_IOS_APP_ATTEST_DEVELOPMENT").pipe(
Config.withDefault(false),
),
});
const http = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
const cache = yield* Ref.make(Option.none<{ at: number; serials: ReadonlySet<string> }>());
const fixed = {
googleRoots: GOOGLE_HARDWARE_ATTESTATION_ROOTS.map(
(pem) => new NodeCrypto.X509Certificate(pem),
),
appleRoot: new NodeCrypto.X509Certificate(APPLE_APP_ATTEST_ROOT),
androidApps: Option.isSome(config.androidPackage)
? [{ packageName: config.androidPackage.value, signingCertSha256: config.androidSigners }]
: [],
appleAppIds: Option.isSome(config.appleAppId) ? [config.appleAppId.value] : [],
appleEnvironments: config.appleDevelopment
? (["production", "development"] as const)
: (["production"] as const),
};
const revoked = Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
const cached = yield* Ref.get(cache);
if (Option.isSome(cached) && now - cached.value.at < Duration.toMillis(STATUS_TTL))
return cached.value.serials;
const list = yield* http
.get(STATUS_URL)
.pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(StatusList)), Effect.scoped);
const serials = new Set(
Object.entries(list.entries)
.filter(([, entry]) => entry.status === "REVOKED" || entry.status === "SUSPENDED")
.map(([serial]) => serial.toLowerCase().replace(/^0+(?=.)/, "")),
);
yield* Ref.set(cache, Option.some({ at: now, serials }));
return serials as ReadonlySet<string>;
}).pipe(
Effect.timeout(Duration.seconds(10)),
Effect.mapError(
() =>
new KinAttestationTrustError({
message: "Couldn't load Google's attestation revocation list.",
}),
),
);
return KinAttestationTrust.of({
load: Effect.fn("KinAttestationTrust.load")(function* (platform: KinApproverKeyPlatform) {
const androidRevokedSerials = platform === "ios" ? new Set<string>() : yield* revoked;
return { ...fixed, androidRevokedSerials };
}),
});
}),
);
159 changes: 159 additions & 0 deletions apps/server/src/kin/approvals/attestation/der.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// @effect-diagnostics extendsNativeError:off -- thrown and caught inside the pure parsers only.
/**
* A strict DER reader for the few structures attestation needs. Node's X509Certificate verifies
* signatures but doesn't expose extensions. Anything not canonical DER throws.
*/
export class DerError extends Error {}

export type Tlv = {
/** 0 universal, 1 application, 2 context, 3 private. */
readonly cls: number;
readonly constructed: boolean;
readonly tag: number;
readonly value: Uint8Array;
/** The whole element, header included. */
readonly raw: Uint8Array;
};

const UNIVERSAL = 0;
export const CONTEXT = 2;
const T_BOOLEAN = 1;
const T_INTEGER = 2;
const T_OCTET_STRING = 4;
const T_OID = 6;
const T_ENUMERATED = 10;
const T_SEQUENCE = 16;
export const T_SET = 17;

const fail = (message: string): never => {
throw new DerError(message);
};

function readOne(bytes: Uint8Array, start: number): { tlv: Tlv; end: number } {
let offset = start;
const next = () => (offset < bytes.length ? bytes[offset++]! : fail("truncated DER"));
const first = next();
const cls = first >> 6;
const constructed = (first & 0x20) !== 0;
let tag = first & 0x1f;
if (tag === 0x1f) {
tag = 0;
let byte = next();
if (byte === 0x80) fail("non-minimal tag");
for (;;) {
tag = tag * 128 + (byte & 0x7f);
if (tag > 0xffff) fail("tag too large");
if ((byte & 0x80) === 0) break;
byte = next();
}
if (tag < 0x1f) fail("non-minimal tag");
}
const lengthByte = next();
let length = lengthByte;
if (lengthByte === 0x80) fail("indefinite length");
if (lengthByte > 0x80) {
const count = lengthByte & 0x7f;
if (count > 4) fail("length too large");
length = 0;
for (let i = 0; i < count; i++) length = length * 256 + next();
if (length < 0x80 || (count > 1 && length < 256 ** (count - 1))) fail("non-minimal length");
}
const end = offset + length;
if (end > bytes.length) fail("truncated DER");
return {
tlv: {
cls,
constructed,
tag,
value: bytes.subarray(offset, end),
raw: bytes.subarray(start, end),
},
end,
};
}

/** Exactly one element filling `bytes`. */
export function parse(bytes: Uint8Array): Tlv {
const { tlv, end } = readOne(bytes, 0);
if (end !== bytes.length) fail("trailing bytes after DER");
return tlv;
}

export function children(tlv: Tlv): ReadonlyArray<Tlv> {
if (!tlv.constructed) fail("expected a constructed element");
const out: Tlv[] = [];
let offset = 0;
while (offset < tlv.value.length) {
const { tlv: child, end } = readOne(tlv.value, offset);
out.push(child);
offset = end;
}
return out;
}

export function expect(tlv: Tlv | undefined, tag: number, cls = UNIVERSAL): Tlv {
if (tlv === undefined) return fail(`missing element with tag ${tag}`);
if (tlv.cls !== cls || tlv.tag !== tag)
fail(`expected tag ${cls}:${tag}, got ${tlv.cls}:${tlv.tag}`);
return tlv;
}

export function sequence(tlv: Tlv | undefined): ReadonlyArray<Tlv> {
return children(expect(tlv, T_SEQUENCE));
}

/** INTEGER or ENUMERATED as a safe non-negative number. */
export function integer(tlv: Tlv | undefined, tag = T_INTEGER): number {
const { value, constructed } = expect(tlv, tag);
if (constructed || value.length === 0) fail("bad integer");
if (value.length > 1 && value[0] === 0 && (value[1]! & 0x80) === 0) fail("non-minimal integer");
if (value.length > 1 && value[0] === 0xff && (value[1]! & 0x80) !== 0)
fail("non-minimal integer");
if ((value[0]! & 0x80) !== 0) fail("negative integer");
let n = 0;
for (const byte of value) n = n * 256 + byte;
if (!Number.isSafeInteger(n)) fail("integer too large");
return n;
}

export function enumerated(tlv: Tlv | undefined): number {
return integer(tlv, T_ENUMERATED);
}

export function octets(tlv: Tlv | undefined): Uint8Array {
const element = expect(tlv, T_OCTET_STRING);
if (element.constructed) fail("constructed octet string");
return element.value;
}

export function boolean(tlv: Tlv | undefined): boolean {
const { value } = expect(tlv, T_BOOLEAN);
if (value.length !== 1 || (value[0] !== 0 && value[0] !== 0xff)) fail("bad boolean");
return value[0] === 0xff;
}

/** An OID's content bytes in hex, for comparison with constants. */
function oidHex(tlv: Tlv | undefined): string {
return Buffer.from(expect(tlv, T_OID).value).toString("hex");
}

export type Extension = { readonly critical: boolean; readonly value: Uint8Array };

/** `tbsCertificate.extensions` keyed by OID content hex. Duplicate OIDs throw. */
export function certificateExtensions(certificateDer: Uint8Array): ReadonlyMap<string, Extension> {
const [tbs] = sequence(parse(certificateDer));
const fields = sequence(tbs);
const wrapper = fields.find((field) => field.cls === CONTEXT && field.tag === 3);
const out = new Map<string, Extension>();
if (wrapper === undefined) return out;
const [list] = children(wrapper);
for (const extension of sequence(list)) {
const parts = sequence(extension);
const oid = oidHex(parts[0]);
const critical = parts.length === 3 ? boolean(parts[1]) : false;
if (parts.length !== 2 && parts.length !== 3) fail("bad extension");
if (out.has(oid)) fail("duplicate extension");
out.set(oid, { critical, value: octets(parts[parts.length - 1]) });
}
return out;
}
Loading