@wujiland/kit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@wujiland/kit` — the Access guard, `requireCaller`/`requireUser`, the webhook barrier, the public-site rules and
4
+ logging every app imports. Spec: `docs/specs/03-kit.md`. Built at step A3.2; not yet published (npm scope:
5
+ `inca-library/docs/OPEN-QUESTIONS.md` OQ-16).
6
+
7
+ `npm test -w kit` · `npm run typecheck -w kit` (checks both DOM and Workers types).
@@ -0,0 +1,23 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ import type { AccessClaims, AccessResult, IncaEnv } from "./types.js";
3
+ export declare const LOCAL_EMAIL = "dev@localhost";
4
+ export declare const DEV_EMAIL_HEADER = "x-inca-dev-email";
5
+ export declare function verifyAccess(request: Request, env: IncaEnv): Promise<AccessResult>;
6
+ export declare function accessStatus(code: string): 401 | 403 | 500;
7
+ export declare function accessGuard(options?: {
8
+ allowEmails?: string[];
9
+ }): MiddlewareHandler;
10
+ /** The verified claims, or null for a visitor with no token (public mode, webhook route). Throws if the guard did not run. */
11
+ export declare function accessClaims(c: Context): AccessClaims | null;
12
+ /** Claims if the guard ran and verified someone, else null; never throws. */
13
+ export declare function verifiedClaims(c: Context): AccessClaims | null;
14
+ type RouteList = {
15
+ routes: readonly {
16
+ method: string;
17
+ path: string;
18
+ handler: unknown;
19
+ }[];
20
+ };
21
+ /** Throws unless the app's first registered handler is accessGuard() on every path (03-kit.md §3). */
22
+ export declare function assertGuardFirst(app: RouteList): void;
23
+ export {};
package/dist/access.js ADDED
@@ -0,0 +1,112 @@
1
+ import { AUD, TEAM, verifyToken } from "./jwt.js";
2
+ import { log, requestId, setLogContext } from "./log.js";
3
+ import { GUARD, SELF_VERIFYING, isMarked, mark, nextAfterGuardIs } from "./markers.js";
4
+ import { ACCESS_JWT_HEADER, RAY_ID_HEADER } from "./vendor.js";
5
+ export const LOCAL_EMAIL = "dev@localhost";
6
+ export const DEV_EMAIL_HEADER = "x-inca-dev-email";
7
+ const CLAIMS = "inca.claims";
8
+ function readConfig(env) {
9
+ const e = env ?? {};
10
+ if (e.INCA_ENV === "local")
11
+ return { kind: "local" };
12
+ if (e.INCA_ENV !== "uat" && e.INCA_ENV !== "prod")
13
+ return { kind: "misconfigured", reason: "INCA_ENV" };
14
+ const mode = e.INCA_ACCESS_MODE;
15
+ if (mode !== "private" && mode !== "named" && mode !== "public")
16
+ return { kind: "misconfigured", reason: "INCA_ACCESS_MODE" };
17
+ // INCA-25: the broker never stamps public on UAT.
18
+ if (mode === "public" && e.INCA_ENV !== "prod")
19
+ return { kind: "misconfigured", reason: "public_on_uat" };
20
+ // Checked before any fetch: a bad team must not point the key fetch at another host.
21
+ if (typeof e.INCA_ACCESS_TEAM !== "string" || !TEAM.test(e.INCA_ACCESS_TEAM))
22
+ return { kind: "misconfigured", reason: "INCA_ACCESS_TEAM" };
23
+ if (typeof e.INCA_ACCESS_AUD !== "string" || !AUD.test(e.INCA_ACCESS_AUD))
24
+ return { kind: "misconfigured", reason: "INCA_ACCESS_AUD" };
25
+ return { kind: "deployed", env: e.INCA_ENV, public: mode === "public", team: e.INCA_ACCESS_TEAM, aud: e.INCA_ACCESS_AUD };
26
+ }
27
+ const fail = (code, reason, env) => ({ result: { ok: false, code }, reason, env });
28
+ async function check(request, env) {
29
+ const config = readConfig(env);
30
+ if (config.kind === "misconfigured")
31
+ return fail("ACCESS_MISCONFIGURED", config.reason);
32
+ if (config.kind === "local") {
33
+ const email = (request.headers.get(DEV_EMAIL_HEADER) ?? "").trim().toLowerCase() || LOCAL_EMAIL;
34
+ return { result: { ok: true, claims: { email, sub: `local:${email}`, kind: "user" } } };
35
+ }
36
+ const token = request.headers.get(ACCESS_JWT_HEADER);
37
+ if (!token) {
38
+ // A public host is not checked at the edge, so no token means an anonymous visitor (INCA-25).
39
+ if (config.public)
40
+ return { result: { ok: true, claims: null } };
41
+ return fail("ACCESS_TOKEN_MISSING", "no_token", config.env);
42
+ }
43
+ const verified = await verifyToken(token, config.team, config.aud);
44
+ if (verified.ok)
45
+ return { result: { ok: true, claims: verified.claims } };
46
+ if (verified.keysUnavailable)
47
+ return fail("ACCESS_KEYS_UNAVAILABLE", verified.reason, config.env);
48
+ return fail("ACCESS_TOKEN_INVALID", verified.reason, config.env);
49
+ }
50
+ function logRefusal(code, reason, id) {
51
+ log("access.refused", { code, reason: reason ?? null, request_id: id });
52
+ }
53
+ export async function verifyAccess(request, env) {
54
+ const { result, reason } = await check(request, env);
55
+ if (!result.ok)
56
+ logRefusal(result.code, reason, request.headers.get(RAY_ID_HEADER));
57
+ return result;
58
+ }
59
+ export function accessStatus(code) {
60
+ if (code === "ACCESS_MISCONFIGURED" || code === "ACCESS_KEYS_UNAVAILABLE")
61
+ return 500;
62
+ if (code === "ACCESS_NOT_ALLOWED")
63
+ return 403;
64
+ return 401;
65
+ }
66
+ export function accessGuard(options) {
67
+ const allow = options?.allowEmails ? new Set(options.allowEmails.map((e) => e.toLowerCase())) : null;
68
+ return mark(async (c, next) => {
69
+ setLogContext(c.env);
70
+ const id = requestId(c);
71
+ const { result, reason, env } = await check(c.req.raw, c.env);
72
+ if (!result.ok) {
73
+ // C-09: a webhook sender reaches a production bypass path with no token; the barrier's signature check is that route's guard.
74
+ if (result.code === "ACCESS_TOKEN_MISSING" && env === "prod" && nextAfterGuardIs(c, SELF_VERIFYING)) {
75
+ c.set(CLAIMS, null);
76
+ await next();
77
+ return;
78
+ }
79
+ logRefusal(result.code, reason, id);
80
+ return c.json({ ok: false, code: result.code }, accessStatus(result.code));
81
+ }
82
+ if (allow && (!result.claims || !allow.has(result.claims.email))) {
83
+ logRefusal("ACCESS_NOT_ALLOWED", "allow_emails", id);
84
+ return c.json({ ok: false, code: "ACCESS_NOT_ALLOWED" }, 403);
85
+ }
86
+ c.set(CLAIMS, result.claims);
87
+ await next();
88
+ }, GUARD);
89
+ }
90
+ /** The verified claims, or null for a visitor with no token (public mode, webhook route). Throws if the guard did not run. */
91
+ export function accessClaims(c) {
92
+ const claims = c.get(CLAIMS);
93
+ if (claims === undefined)
94
+ throw new Error("ACCESS_GUARD_NOT_RUN: accessGuard() must run before accessClaims()");
95
+ return claims;
96
+ }
97
+ /** Claims if the guard ran and verified someone, else null; never throws. */
98
+ export function verifiedClaims(c) {
99
+ return c.get(CLAIMS) ?? null;
100
+ }
101
+ /** Throws unless the app's first registered handler is accessGuard() on every path (03-kit.md §3). */
102
+ export function assertGuardFirst(app) {
103
+ const first = app.routes[0];
104
+ if (!first)
105
+ throw new Error("assertGuardFirst: the app registers nothing; the first middleware must be accessGuard()");
106
+ if (!isMarked(first.handler, GUARD)) {
107
+ throw new Error(`assertGuardFirst: the first handler is ${first.method} ${first.path}, not accessGuard()`);
108
+ }
109
+ if (first.method !== "ALL" || (first.path !== "*" && first.path !== "/*")) {
110
+ throw new Error(`assertGuardFirst: accessGuard() is registered on ${first.method} ${first.path}; use app.use("*", accessGuard())`);
111
+ }
112
+ }
@@ -0,0 +1,13 @@
1
+ import type { AccessClaims, IncaEnv } from "./types.js";
2
+ export declare class CallerRefused extends Error {
3
+ readonly code: string;
4
+ constructor(code: string, message: string);
5
+ }
6
+ export declare function requireCaller(ctx: unknown, env: IncaEnv, entrypoint: string): {
7
+ app: string;
8
+ };
9
+ export declare function requireUser(env: IncaEnv, caller: {
10
+ app: string;
11
+ }, auth: {
12
+ userJwt?: string;
13
+ }, mode: "none" | "optional" | "required"): Promise<AccessClaims | null>;
package/dist/caller.js ADDED
@@ -0,0 +1,84 @@
1
+ // Calls between Workers (03-kit.md §4; C-32): a binding never passes Access, so requireCaller is its only gate.
2
+ import { AUD, TEAM, verifyToken } from "./jwt.js";
3
+ import { log } from "./log.js";
4
+ import { SLUG } from "./paths.js";
5
+ import { bindingProps } from "./vendor.js";
6
+ export class CallerRefused extends Error {
7
+ code;
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.name = "CallerRefused";
11
+ this.code = code;
12
+ }
13
+ }
14
+ function refuse(code, message) {
15
+ log("caller.refused", { code });
16
+ throw new CallerRefused(code, message);
17
+ }
18
+ function parseObject(text) {
19
+ if (typeof text !== "string")
20
+ return null;
21
+ try {
22
+ const v = JSON.parse(text);
23
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ export function requireCaller(ctx, env, entrypoint) {
30
+ const props = bindingProps(ctx);
31
+ if (props === undefined || props === null)
32
+ refuse("CALLER_NO_PROPS", "The call carries no binding props.");
33
+ if (typeof props !== "object" || Array.isArray(props))
34
+ refuse("CALLER_PROPS_INVALID", "The binding props are not an object.");
35
+ const keys = Reflect.ownKeys(props);
36
+ if (keys.length !== 1 || keys[0] !== "app")
37
+ refuse("CALLER_PROPS_INVALID", "The binding props must hold exactly one key, app.");
38
+ const app = props.app;
39
+ if (typeof app !== "string" || !SLUG.test(app))
40
+ refuse("CALLER_PROPS_INVALID", "The binding props' app is not a slug.");
41
+ const exposes = parseObject(env?.INCA_EXPOSES);
42
+ if (!exposes)
43
+ refuse("CALLER_EXPOSES_INVALID", "INCA_EXPOSES is missing or not a JSON object.");
44
+ for (const list of Object.values(exposes)) {
45
+ if (!Array.isArray(list) || !list.every((s) => typeof s === "string")) {
46
+ refuse("CALLER_EXPOSES_INVALID", "INCA_EXPOSES must map each entrypoint to a list of slugs.");
47
+ }
48
+ }
49
+ if (!Object.hasOwn(exposes, entrypoint))
50
+ refuse("CALLER_ENTRYPOINT_NOT_EXPOSED", `${entrypoint} is not exposed.`);
51
+ if (!exposes[entrypoint].includes(app))
52
+ refuse("CALLER_NOT_GRANTED", `${app} is not granted ${entrypoint}.`);
53
+ return { app };
54
+ }
55
+ export async function requireUser(env, caller, auth, mode) {
56
+ if (mode !== "none" && mode !== "optional" && mode !== "required")
57
+ refuse("USER_MODE_INVALID", `Unknown mode ${String(mode)}.`);
58
+ if (mode === "none")
59
+ return null;
60
+ const token = auth?.userJwt;
61
+ if (token === undefined || token === null || token === "") {
62
+ if (mode === "required")
63
+ refuse("USER_TOKEN_MISSING", "This entrypoint needs the user's token.");
64
+ return null;
65
+ }
66
+ if (typeof token !== "string")
67
+ refuse("USER_TOKEN_INVALID", "The user token is not a string.");
68
+ const team = env?.INCA_ACCESS_TEAM;
69
+ if (typeof team !== "string" || !TEAM.test(team))
70
+ refuse("ACCESS_MISCONFIGURED", "INCA_ACCESS_TEAM is missing or malformed.");
71
+ const auds = parseObject(env?.INCA_CALLER_AUDS);
72
+ if (!auds)
73
+ refuse("ACCESS_MISCONFIGURED", "INCA_CALLER_AUDS is missing or not a JSON object.");
74
+ // The caller's audience, never the callee's own: the user signed in to the caller.
75
+ const aud = Object.hasOwn(auds, caller.app) ? auds[caller.app] : undefined;
76
+ if (typeof aud !== "string" || !AUD.test(aud))
77
+ refuse("USER_AUD_UNKNOWN", `No audience is stamped for ${caller.app}.`);
78
+ const result = await verifyToken(token, team, aud);
79
+ if (!result.ok) {
80
+ log("caller.user_refused", { reason: result.reason });
81
+ refuse("USER_TOKEN_INVALID", "The user token did not verify.");
82
+ }
83
+ return result.claims;
84
+ }
@@ -0,0 +1,6 @@
1
+ /** `steps` is how many bytes were compared; it exists so a test can prove there is no early exit. */
2
+ export declare function compareBytes(a: Uint8Array, b: Uint8Array): {
3
+ equal: boolean;
4
+ steps: number;
5
+ };
6
+ export declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean;
@@ -0,0 +1,16 @@
1
+ // Constant-time comparison (03-kit.md §5): equal-length inputs always walk every byte, no early exit.
2
+ /** `steps` is how many bytes were compared; it exists so a test can prove there is no early exit. */
3
+ export function compareBytes(a, b) {
4
+ if (a.length !== b.length)
5
+ return { equal: false, steps: 0 };
6
+ let diff = 0;
7
+ let steps = 0;
8
+ for (let i = 0; i < a.length; i++) {
9
+ diff |= a[i] ^ b[i];
10
+ steps++;
11
+ }
12
+ return { equal: diff === 0, steps };
13
+ }
14
+ export function constantTimeEqual(a, b) {
15
+ return compareBytes(a, b).equal;
16
+ }
@@ -0,0 +1,8 @@
1
+ export { accessClaims, accessGuard, assertGuardFirst, verifyAccess } from "./access.js";
2
+ export { CallerRefused, requireCaller, requireUser } from "./caller.js";
3
+ export { log, logError, requestId, requestLog } from "./log.js";
4
+ export type { LogFields, LogValue } from "./log.js";
5
+ export { adminOnly, publicSite, publicWrite } from "./public.js";
6
+ export { once, webhookBarrier } from "./webhook.js";
7
+ export type { SignatureScheme, WebhookOptions } from "./webhook.js";
8
+ export type { AccessClaims, AccessResult, D1Like, D1Statement, IncaEnv, RateLimitBinding } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { accessClaims, accessGuard, assertGuardFirst, verifyAccess } from "./access.js";
2
+ export { CallerRefused, requireCaller, requireUser } from "./caller.js";
3
+ export { log, logError, requestId, requestLog } from "./log.js";
4
+ export { adminOnly, publicSite, publicWrite } from "./public.js";
5
+ export { once, webhookBarrier } from "./webhook.js";
package/dist/jwt.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { AccessClaims } from "./types.js";
2
+ export declare const TEAM: RegExp;
3
+ export declare const AUD: RegExp;
4
+ export type VerifyResult = {
5
+ ok: true;
6
+ claims: AccessClaims;
7
+ } | {
8
+ ok: false;
9
+ reason: string;
10
+ keysUnavailable?: true;
11
+ };
12
+ export declare function base64UrlDecode(text: string): Uint8Array<ArrayBuffer> | null;
13
+ /** Verifies an Access token against `team` and `aud`. Callers check that both are well formed first. */
14
+ export declare function verifyToken(token: string, team: string, aud: string): Promise<VerifyResult>;
package/dist/jwt.js ADDED
@@ -0,0 +1,117 @@
1
+ import { accessCertsUrl, accessIssuer } from "./vendor.js";
2
+ export const TEAM = /^[a-z0-9-]{1,63}$/;
3
+ export const AUD = /^[0-9a-f]{64}$/;
4
+ const LEEWAY_SECONDS = 60;
5
+ const KEYS_TTL_MS = 60 * 60 * 1000;
6
+ const KEYS_REFRESH_MIN_MS = 60 * 1000;
7
+ const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
8
+ const keyCache = new Map();
9
+ const utf8 = new TextEncoder();
10
+ export function base64UrlDecode(text) {
11
+ if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1)
12
+ return null;
13
+ const b64 = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
14
+ try {
15
+ const bin = atob(b64);
16
+ const out = new Uint8Array(bin.length);
17
+ for (let i = 0; i < bin.length; i++)
18
+ out[i] = bin.charCodeAt(i);
19
+ return out;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ function jsonObject(bytes) {
26
+ if (!bytes)
27
+ return null;
28
+ try {
29
+ const v = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes));
30
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ async function fetchKeys(team) {
37
+ const res = await fetch(accessCertsUrl(team));
38
+ if (!res.ok)
39
+ throw new Error(`certs answered ${res.status}`);
40
+ const body = (await res.json());
41
+ if (!Array.isArray(body.keys))
42
+ throw new Error("certs have no keys list");
43
+ const keys = new Map();
44
+ for (const jwk of body.keys) {
45
+ if (jwk?.kty !== "RSA" || typeof jwk.kid !== "string" || typeof jwk.n !== "string" || typeof jwk.e !== "string")
46
+ continue;
47
+ const key = await crypto.subtle.importKey("jwk", { kty: "RSA", n: jwk.n, e: jwk.e, alg: "RS256", ext: true }, RS256, false, [
48
+ "verify",
49
+ ]);
50
+ keys.set(jwk.kid, key);
51
+ }
52
+ return keys;
53
+ }
54
+ function loadKeys(team) {
55
+ const set = { at: Date.now(), keys: fetchKeys(team) };
56
+ keyCache.set(team, set);
57
+ set.keys.catch(() => {
58
+ if (keyCache.get(team) === set)
59
+ keyCache.delete(team);
60
+ });
61
+ return set;
62
+ }
63
+ async function keyFor(team, kid) {
64
+ let set = keyCache.get(team);
65
+ if (!set || Date.now() - set.at > KEYS_TTL_MS)
66
+ set = loadKeys(team);
67
+ let key = (await set.keys).get(kid);
68
+ // An unknown kid may mean the team rotated its keys; refetch, but at most once a minute.
69
+ if (!key && Date.now() - set.at > KEYS_REFRESH_MIN_MS)
70
+ key = (await loadKeys(team).keys).get(kid);
71
+ return key;
72
+ }
73
+ /** Verifies an Access token against `team` and `aud`. Callers check that both are well formed first. */
74
+ export async function verifyToken(token, team, aud) {
75
+ const parts = token.split(".");
76
+ if (parts.length !== 3)
77
+ return { ok: false, reason: "not_a_jwt" };
78
+ const [h, p, s] = parts;
79
+ const header = jsonObject(base64UrlDecode(h));
80
+ const payload = jsonObject(base64UrlDecode(p));
81
+ const signature = base64UrlDecode(s);
82
+ if (!header || !payload || !signature)
83
+ return { ok: false, reason: "malformed" };
84
+ if (header.alg !== "RS256")
85
+ return { ok: false, reason: "alg" };
86
+ if (typeof header.kid !== "string" || header.kid === "")
87
+ return { ok: false, reason: "no_kid" };
88
+ let key;
89
+ try {
90
+ key = await keyFor(team, header.kid);
91
+ }
92
+ catch {
93
+ return { ok: false, reason: "keys_unavailable", keysUnavailable: true };
94
+ }
95
+ if (!key)
96
+ return { ok: false, reason: "unknown_kid" };
97
+ const valid = await crypto.subtle.verify(RS256, key, signature, utf8.encode(`${h}.${p}`)).catch(() => false);
98
+ if (!valid)
99
+ return { ok: false, reason: "signature" };
100
+ if (payload.iss !== accessIssuer(team))
101
+ return { ok: false, reason: "issuer" };
102
+ const audOk = typeof payload.aud === "string" ? payload.aud === aud : Array.isArray(payload.aud) && payload.aud.includes(aud);
103
+ if (!audOk)
104
+ return { ok: false, reason: "audience" };
105
+ const now = Math.floor(Date.now() / 1000);
106
+ if (typeof payload.exp !== "number" || now > payload.exp + LEEWAY_SECONDS)
107
+ return { ok: false, reason: "expired" };
108
+ if (payload.nbf !== undefined && (typeof payload.nbf !== "number" || now < payload.nbf - LEEWAY_SECONDS)) {
109
+ return { ok: false, reason: "not_yet_valid" };
110
+ }
111
+ // C-36 is off: a service-token identity carries no email and is refused.
112
+ if (typeof payload.sub !== "string" || payload.sub === "")
113
+ return { ok: false, reason: "no_sub" };
114
+ if (typeof payload.email !== "string" || payload.email === "")
115
+ return { ok: false, reason: "no_email" };
116
+ return { ok: true, claims: { email: payload.email.toLowerCase(), sub: payload.sub, kind: "user" } };
117
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ export type LogValue = string | number | boolean | null;
3
+ export type LogFields = Record<string, LogValue>;
4
+ export declare function setLogContext(env: unknown): void;
5
+ export declare function isSecretKey(key: string): boolean;
6
+ export declare function log(event: string, fields?: LogFields): void;
7
+ export declare function logError(event: string, err: unknown, fields?: LogFields): void;
8
+ /** The request id the kit uses in its own lines: Cloudflare's ray id, else a fresh UUID. */
9
+ export declare function requestId(c: Context): string;
10
+ export declare function requestLog(): MiddlewareHandler;
package/dist/log.js ADDED
@@ -0,0 +1,95 @@
1
+ import { routePath } from "hono/route";
2
+ import { RAY_ID_HEADER } from "./vendor.js";
3
+ const RESERVED = new Set(["t", "level", "event", "app", "env", "request_id", "redacted"]);
4
+ const MAX_VALUE_LENGTH = 256;
5
+ const REQUEST_ID = "inca.requestId";
6
+ // App and env are the same for every request an isolate serves, so the first kit middleware records them.
7
+ let isolate = { app: null, env: null };
8
+ export function setLogContext(env) {
9
+ const e = (env ?? {});
10
+ isolate = {
11
+ app: typeof e.INCA_APP === "string" ? e.INCA_APP : null,
12
+ env: typeof e.INCA_ENV === "string" ? e.INCA_ENV : null,
13
+ };
14
+ }
15
+ export function isSecretKey(key) {
16
+ const k = key.toLowerCase();
17
+ return k.includes("token") || k.includes("secret") || k.includes("password") || k === "authorization" || k === "cookie";
18
+ }
19
+ function scalar(value) {
20
+ if (value === null || typeof value === "boolean")
21
+ return value;
22
+ if (typeof value === "number")
23
+ return Number.isFinite(value) ? value : String(value);
24
+ if (typeof value === "string")
25
+ return value.length > MAX_VALUE_LENGTH ? `${value.slice(0, MAX_VALUE_LENGTH)}…` : value;
26
+ return "[unsupported]";
27
+ }
28
+ function line(level, event, fields) {
29
+ const out = {
30
+ t: new Date().toISOString(),
31
+ level,
32
+ event: String(event),
33
+ app: isolate.app,
34
+ env: isolate.env,
35
+ request_id: null,
36
+ };
37
+ let redacted = false;
38
+ for (const [key, value] of Object.entries(fields ?? {})) {
39
+ if (key === "request_id") {
40
+ out.request_id = scalar(value);
41
+ continue;
42
+ }
43
+ const name = RESERVED.has(key) ? `field_${key}` : key;
44
+ if (isSecretKey(key)) {
45
+ out[name] = "[redacted]";
46
+ redacted = true;
47
+ }
48
+ else {
49
+ out[name] = scalar(value);
50
+ }
51
+ }
52
+ if (redacted)
53
+ out.redacted = true;
54
+ return JSON.stringify(out);
55
+ }
56
+ export function log(event, fields) {
57
+ console.log(line("info", event, fields));
58
+ }
59
+ export function logError(event, err, fields) {
60
+ const e = err instanceof Error ? err : null;
61
+ console.log(line("error", event, {
62
+ ...fields,
63
+ error_name: e ? e.name : "NonError",
64
+ error_message: e ? e.message : String(err),
65
+ error_stack: e?.stack ?? null,
66
+ }));
67
+ }
68
+ /** The request id the kit uses in its own lines: Cloudflare's ray id, else a fresh UUID. */
69
+ export function requestId(c) {
70
+ const known = c.get(REQUEST_ID);
71
+ if (known)
72
+ return known;
73
+ const id = c.req.header(RAY_ID_HEADER) || crypto.randomUUID();
74
+ c.set(REQUEST_ID, id);
75
+ return id;
76
+ }
77
+ export function requestLog() {
78
+ return async (c, next) => {
79
+ setLogContext(c.env);
80
+ const id = requestId(c);
81
+ const started = Date.now();
82
+ try {
83
+ await next();
84
+ }
85
+ finally {
86
+ log("request", {
87
+ request_id: id,
88
+ method: c.req.method,
89
+ route: routePath(c, -1) || null,
90
+ status: c.res.status,
91
+ ms: Date.now() - started,
92
+ });
93
+ }
94
+ };
95
+ }
@@ -0,0 +1,13 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ export declare const GUARD: unique symbol;
3
+ export declare const PUBLIC_WRITE: unique symbol;
4
+ export declare const SELF_VERIFYING: unique symbol;
5
+ export declare function mark<T extends MiddlewareHandler>(handler: T, symbol: symbol): T;
6
+ export declare function isMarked(handler: unknown, symbol: symbol): boolean;
7
+ /** True when any handler matched for this request carries the mark. */
8
+ export declare function routeHas(c: Context, symbol: symbol): boolean;
9
+ /**
10
+ * True when the handler matched right after the access guard carries the mark. A tokenless request may
11
+ * pass the guard only into the barrier itself, never into app code registered between the two.
12
+ */
13
+ export declare function nextAfterGuardIs(c: Context, symbol: symbol): boolean;
@@ -0,0 +1,24 @@
1
+ import { matchedRoutes } from "hono/route";
2
+ export const GUARD = Symbol.for("inca.accessGuard");
3
+ export const PUBLIC_WRITE = Symbol.for("inca.publicWrite");
4
+ export const SELF_VERIFYING = Symbol.for("inca.webhookBarrier");
5
+ export function mark(handler, symbol) {
6
+ handler[symbol] = true;
7
+ return handler;
8
+ }
9
+ export function isMarked(handler, symbol) {
10
+ return typeof handler === "function" && handler[symbol] === true;
11
+ }
12
+ /** True when any handler matched for this request carries the mark. */
13
+ export function routeHas(c, symbol) {
14
+ return matchedRoutes(c).some((r) => isMarked(r.handler, symbol));
15
+ }
16
+ /**
17
+ * True when the handler matched right after the access guard carries the mark. A tokenless request may
18
+ * pass the guard only into the barrier itself, never into app code registered between the two.
19
+ */
20
+ export function nextAfterGuardIs(c, symbol) {
21
+ const routes = matchedRoutes(c);
22
+ const guard = routes.findIndex((r) => isMarked(r.handler, GUARD));
23
+ return guard >= 0 && isMarked(routes[guard + 1]?.handler, symbol);
24
+ }
@@ -0,0 +1,3 @@
1
+ export declare function covers(pattern: string, path: string): boolean;
2
+ export declare function covered(path: string, patterns: readonly string[]): boolean;
3
+ export declare const SLUG: RegExp;
package/dist/paths.js ADDED
@@ -0,0 +1,10 @@
1
+ // Path coverage, 01-config.md §4, copied here because the kit must not depend on @wujiland/config
2
+ // (02-renderer.md §3): a pattern ending "/*" covers every path that starts with the part before the
3
+ // "*"; any other pattern covers only itself.
4
+ export function covers(pattern, path) {
5
+ return pattern.endsWith("/*") ? path.startsWith(pattern.slice(0, -1)) : path === pattern;
6
+ }
7
+ export function covered(path, patterns) {
8
+ return patterns.some((p) => covers(p, path));
9
+ }
10
+ export const SLUG = /^[a-z0-9]([a-z0-9-]{0,40}[a-z0-9])?$/;
@@ -0,0 +1,6 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ export declare function publicSite(): MiddlewareHandler;
3
+ /** Belt for a route the config forgot to list: 404 unless on a private host with verified claims. */
4
+ export declare function adminOnly(): MiddlewareHandler;
5
+ /** Opts one route into non-GET methods in public mode (03-kit.md §7). */
6
+ export declare function publicWrite(): MiddlewareHandler;
package/dist/public.js ADDED
@@ -0,0 +1,86 @@
1
+ import { verifiedClaims } from "./access.js";
2
+ import { log, requestId } from "./log.js";
3
+ import { PUBLIC_WRITE, mark, routeHas } from "./markers.js";
4
+ import { covered } from "./paths.js";
5
+ import { RATE_LIMIT_RETRY_AFTER_SECONDS, clientAddress, rateLimitAllows, rateLimitBinding } from "./vendor.js";
6
+ const NOINDEX = "noindex, nofollow";
7
+ // A request with no client address shares one counter: throttled together rather than unlimited.
8
+ const NO_ADDRESS_KEY = "no-client-address";
9
+ function pathList(text) {
10
+ if (typeof text !== "string")
11
+ return null;
12
+ try {
13
+ const v = JSON.parse(text);
14
+ return Array.isArray(v) && v.every((p) => typeof p === "string" && p.startsWith("/")) ? v : null;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ function needsNoindex(env, host) {
21
+ if (env.INCA_ENV !== "prod")
22
+ return true;
23
+ return typeof env.INCA_CANONICAL_HOST !== "string" || host !== env.INCA_CANONICAL_HOST.toLowerCase();
24
+ }
25
+ function withNoindex(res) {
26
+ const out = new Response(res.body, res);
27
+ out.headers.set("X-Robots-Tag", NOINDEX);
28
+ return out;
29
+ }
30
+ export function publicSite() {
31
+ return async (c, next) => {
32
+ const env = (c.env ?? {});
33
+ const url = new URL(c.req.url);
34
+ const noindex = needsNoindex(env, url.hostname.toLowerCase());
35
+ const refuse = (code, status, headers) => {
36
+ log("public.refused", { code, request_id: requestId(c) });
37
+ const res = status === 404 ? c.notFound() : c.json({ ok: false, code }, status, headers);
38
+ return noindex ? withNoindex(res) : res;
39
+ };
40
+ if (env.INCA_ACCESS_MODE === "public") {
41
+ const adminPaths = pathList(env.INCA_ADMIN_PATHS);
42
+ const bypassPaths = pathList(env.INCA_BYPASS_PATHS);
43
+ const limiter = rateLimitBinding(env);
44
+ if (!adminPaths || !bypassPaths || typeof env.INCA_CANONICAL_HOST !== "string" || !limiter) {
45
+ return refuse("PUBLIC_MISCONFIGURED", 500);
46
+ }
47
+ let allowed;
48
+ try {
49
+ allowed = await rateLimitAllows(limiter, clientAddress(c.req.raw) ?? NO_ADDRESS_KEY);
50
+ }
51
+ catch {
52
+ return refuse("PUBLIC_RATE_LIMIT_FAILED", 500);
53
+ }
54
+ if (!allowed)
55
+ return refuse("RATE_LIMITED", 429, { "Retry-After": String(RATE_LIMIT_RETRY_AFTER_SECONDS) });
56
+ // INCA-25: refused by host, before any handler; a token proves nothing where the edge is not checking.
57
+ if (covered(url.pathname, adminPaths))
58
+ return refuse("ADMIN_PATH_ON_PUBLIC_HOST", 404);
59
+ const method = c.req.method;
60
+ if (method !== "GET" && method !== "HEAD" && !covered(url.pathname, bypassPaths) && !routeHas(c, PUBLIC_WRITE)) {
61
+ return refuse("METHOD_NOT_ALLOWED", 405, { Allow: "GET, HEAD" });
62
+ }
63
+ }
64
+ await next();
65
+ if (noindex)
66
+ c.header("X-Robots-Tag", NOINDEX);
67
+ };
68
+ }
69
+ /** Belt for a route the config forgot to list: 404 unless on a private host with verified claims. */
70
+ export function adminOnly() {
71
+ return async (c, next) => {
72
+ const env = (c.env ?? {});
73
+ const privateHost = env.INCA_ENV === "local" || env.INCA_ACCESS_MODE === "private" || env.INCA_ACCESS_MODE === "named";
74
+ if (!privateHost || !verifiedClaims(c)) {
75
+ log("public.refused", { code: "ADMIN_ONLY", request_id: requestId(c) });
76
+ return c.notFound();
77
+ }
78
+ await next();
79
+ };
80
+ }
81
+ /** Opts one route into non-GET methods in public mode (03-kit.md §7). */
82
+ export function publicWrite() {
83
+ return mark(async (_c, next) => {
84
+ await next();
85
+ }, PUBLIC_WRITE);
86
+ }
@@ -0,0 +1,47 @@
1
+ import type { IncaEnv } from "./types.js";
2
+ import type { SignatureScheme } from "./webhook.js";
3
+ export { assertGuardFirst } from "./access.js";
4
+ export declare const TEST_TEAM = "inca-test";
5
+ export declare const TEST_AUD: string;
6
+ export declare const TEST_KID = "inca-test-key";
7
+ /** The JWKS the test team publishes: the primary key only. */
8
+ export declare function testJwks(): Promise<{
9
+ keys: JsonWebKey[];
10
+ }>;
11
+ export type TokenOptions = {
12
+ /** Claims merged over the defaults; a key set to undefined is left out. */
13
+ claims?: Record<string, unknown>;
14
+ /** Header fields merged over `{alg: "RS256", kid: TEST_KID, typ: "JWT"}`. */
15
+ header?: Record<string, unknown>;
16
+ /** "other": a second key pair under the same kid. "hs256" / "none": the algorithms a guard must refuse. */
17
+ signWith?: "primary" | "other" | "hs256" | "none";
18
+ team?: string;
19
+ aud?: string;
20
+ };
21
+ export declare function signAccessToken(options?: TokenOptions): Promise<string>;
22
+ /**
23
+ * Replaces the global `fetch` so the test team's certs URL answers with `testJwks()`; any other request
24
+ * throws. `calls` lists every URL asked for. Call `restore()` after the test.
25
+ */
26
+ export declare function installTestJwks(team?: string): {
27
+ calls: string[];
28
+ restore: () => void;
29
+ };
30
+ /** The stamps of `local` render mode (02-renderer.md §5). */
31
+ export declare function localEnv(overrides?: Partial<IncaEnv> & Record<string, unknown>): IncaEnv & Record<string, unknown>;
32
+ /** The stamps of a deployed Worker on the test team, private on UAT unless overridden. */
33
+ export declare function deployedEnv(overrides?: Partial<IncaEnv> & Record<string, unknown>): IncaEnv & Record<string, unknown>;
34
+ /** An execution context carrying binding props, as a callee receives it. */
35
+ export declare function propsStub(props?: unknown): {
36
+ props: unknown;
37
+ waitUntil(p: Promise<unknown>): void;
38
+ passThroughOnException(): void;
39
+ };
40
+ /** Signs `body` as `scheme` describes and returns the headers a sender would send. */
41
+ export declare function signWebhook(options: {
42
+ secret: string;
43
+ body: string;
44
+ scheme: SignatureScheme;
45
+ timestamp?: number | null;
46
+ headers?: Record<string, string>;
47
+ }): Promise<Headers>;
@@ -0,0 +1,115 @@
1
+ import { accessCertsUrl, accessIssuer } from "./vendor.js";
2
+ export { assertGuardFirst } from "./access.js";
3
+ export const TEST_TEAM = "inca-test";
4
+ export const TEST_AUD = "0123456789abcdef".repeat(4);
5
+ export const TEST_KID = "inca-test-key";
6
+ const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
7
+ let pairs = null;
8
+ function makePair() {
9
+ return crypto.subtle.generateKey({ ...RS256, modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]) }, true, ["sign", "verify"]);
10
+ }
11
+ function keyPairs() {
12
+ pairs ??= Promise.all([makePair(), makePair()]).then(([primary, other]) => ({ primary, other }));
13
+ return pairs;
14
+ }
15
+ function b64url(bytes) {
16
+ const raw = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
17
+ let bin = "";
18
+ for (const b of raw)
19
+ bin += String.fromCharCode(b);
20
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
21
+ }
22
+ /** The JWKS the test team publishes: the primary key only. */
23
+ export async function testJwks() {
24
+ const { primary } = await keyPairs();
25
+ const jwk = (await crypto.subtle.exportKey("jwk", primary.publicKey));
26
+ return { keys: [{ kty: jwk.kty, n: jwk.n, e: jwk.e, alg: "RS256", use: "sig", kid: TEST_KID }] };
27
+ }
28
+ export async function signAccessToken(options = {}) {
29
+ const now = Math.floor(Date.now() / 1000);
30
+ const team = options.team ?? TEST_TEAM;
31
+ const signWith = options.signWith ?? "primary";
32
+ const alg = signWith === "hs256" ? "HS256" : signWith === "none" ? "none" : "RS256";
33
+ const header = { alg, kid: TEST_KID, typ: "JWT", ...options.header };
34
+ const claims = {
35
+ iss: accessIssuer(team),
36
+ aud: [options.aud ?? TEST_AUD],
37
+ sub: "00000000-0000-4000-8000-000000000001",
38
+ email: "guest@example.test",
39
+ iat: now,
40
+ nbf: now,
41
+ exp: now + 300,
42
+ type: "app",
43
+ ...options.claims,
44
+ };
45
+ for (const k of Object.keys(claims))
46
+ if (claims[k] === undefined)
47
+ delete claims[k];
48
+ const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
49
+ if (signWith === "none")
50
+ return `${input}.`;
51
+ if (signWith === "hs256") {
52
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode("shared"), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
53
+ return `${input}.${b64url(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(input))))}`;
54
+ }
55
+ const { primary, other } = await keyPairs();
56
+ const key = signWith === "other" ? other.privateKey : primary.privateKey;
57
+ return `${input}.${b64url(new Uint8Array(await crypto.subtle.sign(RS256, key, new TextEncoder().encode(input))))}`;
58
+ }
59
+ /**
60
+ * Replaces the global `fetch` so the test team's certs URL answers with `testJwks()`; any other request
61
+ * throws. `calls` lists every URL asked for. Call `restore()` after the test.
62
+ */
63
+ export function installTestJwks(team = TEST_TEAM) {
64
+ const original = globalThis.fetch;
65
+ const calls = [];
66
+ globalThis.fetch = (async (input) => {
67
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
68
+ calls.push(url);
69
+ if (url === accessCertsUrl(team))
70
+ return Response.json(await testJwks());
71
+ throw new Error(`installTestJwks: unexpected network request to ${url}`);
72
+ });
73
+ return { calls, restore: () => void (globalThis.fetch = original) };
74
+ }
75
+ /** The stamps of `local` render mode (02-renderer.md §5). */
76
+ export function localEnv(overrides = {}) {
77
+ return { INCA_ENV: "local", INCA_APP: "app", INCA_HOST: "localhost", ...overrides };
78
+ }
79
+ /** The stamps of a deployed Worker on the test team, private on UAT unless overridden. */
80
+ export function deployedEnv(overrides = {}) {
81
+ return {
82
+ INCA_ENV: "uat",
83
+ INCA_APP: "app",
84
+ INCA_HOST: "app-uat.example.test",
85
+ INCA_ACCESS_MODE: "private",
86
+ INCA_ACCESS_TEAM: TEST_TEAM,
87
+ INCA_ACCESS_AUD: TEST_AUD,
88
+ INCA_EXPOSES: "{}",
89
+ INCA_CALLER_AUDS: "{}",
90
+ ...overrides,
91
+ };
92
+ }
93
+ /** An execution context carrying binding props, as a callee receives it. */
94
+ export function propsStub(props = { app: "caller" }) {
95
+ return { props, waitUntil: () => { }, passThroughOnException: () => { } };
96
+ }
97
+ /** Signs `body` as `scheme` describes and returns the headers a sender would send. */
98
+ export async function signWebhook(options) {
99
+ const { scheme } = options;
100
+ const ts = scheme.timestamp === null ? null : options.timestamp === null ? null : String(options.timestamp ?? Math.floor(Date.now() / 1000));
101
+ const enc = new TextEncoder();
102
+ const key = await crypto.subtle.importKey("raw", enc.encode(options.secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
103
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(scheme.signedPayload(ts, options.body))));
104
+ const sig = scheme.encoding === "hex" ? [...mac].map((b) => b.toString(16).padStart(2, "0")).join("") : btoa(String.fromCharCode(...mac));
105
+ const headers = new Headers(options.headers);
106
+ if (scheme.timestamp && "inSignatureHeader" in scheme.timestamp) {
107
+ headers.set(scheme.signatureHeader, `${ts !== null ? `t=${ts},` : ""}v1=${sig}`);
108
+ }
109
+ else {
110
+ headers.set(scheme.signatureHeader, `${scheme.signaturePrefix ?? ""}${sig}`);
111
+ if (scheme.timestamp && ts !== null)
112
+ headers.set(scheme.timestamp.header, ts);
113
+ }
114
+ return headers;
115
+ }
@@ -0,0 +1,47 @@
1
+ /** Cloudflare's rate-limit binding, as the kit uses it (vendor.ts). */
2
+ export interface RateLimitBinding {
3
+ limit(options: {
4
+ key: string;
5
+ }): Promise<{
6
+ success: boolean;
7
+ }>;
8
+ }
9
+ /** The stamps the broker sets (01-config.md §11, 02-renderer.md §5). The kit validates every one. */
10
+ export interface IncaEnv {
11
+ INCA_APP?: string;
12
+ INCA_ENV?: string;
13
+ INCA_HOST?: string;
14
+ INCA_ACCESS_MODE?: string;
15
+ INCA_ACCESS_TEAM?: string;
16
+ INCA_ACCESS_AUD?: string;
17
+ INCA_EXPOSES?: string;
18
+ INCA_CALLER_AUDS?: string;
19
+ INCA_ADMIN_PATHS?: string;
20
+ INCA_BYPASS_PATHS?: string;
21
+ INCA_CANONICAL_HOST?: string;
22
+ INCA_RATE_LIMIT?: RateLimitBinding;
23
+ }
24
+ export type AccessClaims = {
25
+ email: string;
26
+ sub: string;
27
+ kind: "user";
28
+ };
29
+ /** `claims` is null only in public mode with no token (03-kit.md §3). */
30
+ export type AccessResult = {
31
+ ok: true;
32
+ claims: AccessClaims | null;
33
+ } | {
34
+ ok: false;
35
+ code: string;
36
+ };
37
+ /** The part of a D1 prepared statement the kit uses; a real `D1PreparedStatement` satisfies it. */
38
+ export interface D1Statement {
39
+ bind(...values: unknown[]): D1Statement;
40
+ first(): Promise<unknown>;
41
+ run(): Promise<unknown>;
42
+ }
43
+ /** The part of a D1 database the kit uses; a real `D1Database` satisfies it. */
44
+ export interface D1Like {
45
+ prepare(query: string): D1Statement;
46
+ batch(statements: D1Statement[]): Promise<unknown[]>;
47
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { IncaEnv, RateLimitBinding } from "./types.js";
2
+ /** Header carrying the Access token on every request that passed Access. [verify] */
3
+ export declare const ACCESS_JWT_HEADER = "Cf-Access-Jwt-Assertion";
4
+ /** Header Cloudflare sets to the client's address on an incoming request. [verify] */
5
+ export declare const CLIENT_ADDRESS_HEADER = "CF-Connecting-IP";
6
+ /** Header Cloudflare sets to the request's ray id; used as the request id when present. [verify] */
7
+ export declare const RAY_ID_HEADER = "cf-ray";
8
+ export declare function accessIssuer(team: string): string;
9
+ /** The team's signing keys (JWKS). [verify] the URL and the JWKS shape `{keys: [{kid, kty, n, e}]}`. */
10
+ export declare function accessCertsUrl(team: string): string;
11
+ /** Binding props travel to the callee as `ctx.props` (Wrangler 4.162.0, workers-types). [verify] live at A5 */
12
+ export declare function bindingProps(ctx: unknown): unknown;
13
+ export declare function clientAddress(request: Request): string | null;
14
+ /** The rate-limit binding, or null when the Worker has none. */
15
+ export declare function rateLimitBinding(env: IncaEnv): RateLimitBinding | null;
16
+ /** `limit({key})` resolves `{success}`: true while under the limit (workers-types `RateLimit`). [verify] live */
17
+ export declare function rateLimitAllows(binding: RateLimitBinding, key: string): Promise<boolean>;
18
+ /** The binding's period is not readable from the Worker; 60 s is the longest one the config allows. */
19
+ export declare const RATE_LIMIT_RETRY_AFTER_SECONDS = 60;
package/dist/vendor.js ADDED
@@ -0,0 +1,39 @@
1
+ /** Header carrying the Access token on every request that passed Access. [verify] */
2
+ export const ACCESS_JWT_HEADER = "Cf-Access-Jwt-Assertion";
3
+ /** Header Cloudflare sets to the client's address on an incoming request. [verify] */
4
+ export const CLIENT_ADDRESS_HEADER = "CF-Connecting-IP";
5
+ /** Header Cloudflare sets to the request's ray id; used as the request id when present. [verify] */
6
+ export const RAY_ID_HEADER = "cf-ray";
7
+ export function accessIssuer(team) {
8
+ return `https://${team}.cloudflareaccess.com`;
9
+ }
10
+ /** The team's signing keys (JWKS). [verify] the URL and the JWKS shape `{keys: [{kid, kty, n, e}]}`. */
11
+ export function accessCertsUrl(team) {
12
+ return `${accessIssuer(team)}/cdn-cgi/access/certs`;
13
+ }
14
+ /** Binding props travel to the callee as `ctx.props` (Wrangler 4.162.0, workers-types). [verify] live at A5 */
15
+ export function bindingProps(ctx) {
16
+ if (typeof ctx !== "object" || ctx === null)
17
+ return undefined;
18
+ return ctx.props;
19
+ }
20
+ export function clientAddress(request) {
21
+ return request.headers.get(CLIENT_ADDRESS_HEADER);
22
+ }
23
+ /** The rate-limit binding, or null when the Worker has none. */
24
+ export function rateLimitBinding(env) {
25
+ const b = env.INCA_RATE_LIMIT;
26
+ if (typeof b !== "object" || b === null)
27
+ return null;
28
+ return typeof b.limit === "function" ? b : null;
29
+ }
30
+ /** `limit({key})` resolves `{success}`: true while under the limit (workers-types `RateLimit`). [verify] live */
31
+ export async function rateLimitAllows(binding, key) {
32
+ const outcome = await binding.limit({ key });
33
+ const success = outcome?.success;
34
+ if (typeof success !== "boolean")
35
+ throw new Error("VENDOR_SHAPE: rate-limit outcome has no boolean success");
36
+ return success;
37
+ }
38
+ /** The binding's period is not readable from the Worker; 60 s is the longest one the config allows. */
39
+ export const RATE_LIMIT_RETRY_AFTER_SECONDS = 60;
@@ -0,0 +1,30 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ import type { D1Like, D1Statement } from "./types.js";
3
+ export type SignatureScheme = {
4
+ signatureHeader: string;
5
+ /** Stripped from the header value before decoding, e.g. "sha256=". */
6
+ signaturePrefix?: string;
7
+ /** `inSignatureHeader`: the header is `t=<timestamp>,v1=<signature>[,v1=…]`. */
8
+ timestamp: {
9
+ header: string;
10
+ } | {
11
+ inSignatureHeader: true;
12
+ } | null;
13
+ signedPayload: (timestamp: string | null, rawBody: string) => string;
14
+ encoding: "hex" | "base64";
15
+ eventId: (rawBody: string, headers: Headers) => string | null;
16
+ };
17
+ export type WebhookOptions<E = any> = {
18
+ source: string;
19
+ secret: (env: E) => string;
20
+ scheme: SignatureScheme;
21
+ db: (env: E) => D1Like;
22
+ toleranceSeconds?: number;
23
+ };
24
+ export declare const EVENTS_TABLE = "_inca_webhook_events";
25
+ export declare function webhookBarrier<E = any>(options: WebhookOptions<E>): MiddlewareHandler;
26
+ /**
27
+ * Runs the effect's statements once per event. The event row is a plain INSERT in the same batch, so a
28
+ * second delivery's batch fails on the primary key and none of its writes land.
29
+ */
30
+ export declare function once(c: Context, effect: (stmts: D1Statement[]) => void): Promise<"done" | "duplicate">;
@@ -0,0 +1,148 @@
1
+ import { base64UrlDecode } from "./jwt.js";
2
+ import { constantTimeEqual } from "./compare.js";
3
+ import { log, setLogContext } from "./log.js";
4
+ import { SELF_VERIFYING, mark } from "./markers.js";
5
+ import { SLUG } from "./paths.js";
6
+ const EVENT = "inca.webhook";
7
+ const MAX_EVENT_ID = 512;
8
+ export const EVENTS_TABLE = "_inca_webhook_events";
9
+ const CREATE_TABLE = `CREATE TABLE IF NOT EXISTS ${EVENTS_TABLE} (source TEXT NOT NULL, event_id TEXT NOT NULL, received_at INTEGER NOT NULL, PRIMARY KEY (source, event_id))`;
10
+ function decodeSignature(text, encoding) {
11
+ if (encoding === "hex") {
12
+ if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text))
13
+ return null;
14
+ const out = new Uint8Array(text.length / 2);
15
+ for (let i = 0; i < out.length; i++)
16
+ out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
17
+ return out;
18
+ }
19
+ return base64UrlDecode(text.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""));
20
+ }
21
+ function readSignatures(scheme, headers) {
22
+ const value = headers.get(scheme.signatureHeader);
23
+ if (value === null)
24
+ return { signatures: [], timestamp: null };
25
+ if (scheme.timestamp && "inSignatureHeader" in scheme.timestamp) {
26
+ let timestamp = null;
27
+ const signatures = [];
28
+ for (const part of value.split(",")) {
29
+ const eq = part.indexOf("=");
30
+ if (eq < 0)
31
+ continue;
32
+ const k = part.slice(0, eq).trim();
33
+ const v = part.slice(eq + 1).trim();
34
+ if (k === "t")
35
+ timestamp = v;
36
+ else if (k === "v1")
37
+ signatures.push(v);
38
+ }
39
+ return { signatures, timestamp };
40
+ }
41
+ const prefix = scheme.signaturePrefix ?? "";
42
+ if (!value.startsWith(prefix))
43
+ return { signatures: [], timestamp: null };
44
+ const timestamp = scheme.timestamp && "header" in scheme.timestamp ? headers.get(scheme.timestamp.header) : null;
45
+ return { signatures: [value.slice(prefix.length).trim()], timestamp };
46
+ }
47
+ async function hmac(secret, payload) {
48
+ const enc = new TextEncoder();
49
+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
50
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(payload)));
51
+ }
52
+ export function webhookBarrier(options) {
53
+ if (!SLUG.test(options.source))
54
+ throw new Error(`webhookBarrier: source ${options.source} is not a slug`);
55
+ const tolerance = options.toleranceSeconds ?? 300;
56
+ const { source, scheme } = options;
57
+ return mark(async (c, next) => {
58
+ setLogContext(c.env);
59
+ const refuse = (code, status = 401) => {
60
+ log("hook.refused", { source, code });
61
+ return c.json({ ok: false, code }, status);
62
+ };
63
+ let secret;
64
+ let db;
65
+ try {
66
+ secret = options.secret(c.env);
67
+ db = options.db(c.env);
68
+ }
69
+ catch {
70
+ return refuse("WEBHOOK_MISCONFIGURED", 500);
71
+ }
72
+ if (typeof secret !== "string" || secret === "")
73
+ return refuse("WEBHOOK_MISCONFIGURED", 500);
74
+ if (typeof db !== "object" || db === null || typeof db.batch !== "function") {
75
+ return refuse("WEBHOOK_MISCONFIGURED", 500);
76
+ }
77
+ // Nothing parses the body before the signature is checked.
78
+ const rawBody = await c.req.text();
79
+ const headers = c.req.raw.headers;
80
+ const { signatures, timestamp } = readSignatures(scheme, headers);
81
+ const expected = await hmac(secret, scheme.signedPayload(timestamp, rawBody));
82
+ let match = false;
83
+ for (const sig of signatures) {
84
+ const given = decodeSignature(sig, scheme.encoding);
85
+ const equal = given !== null && constantTimeEqual(given, expected);
86
+ match = match || equal;
87
+ }
88
+ if (!match)
89
+ return refuse("WEBHOOK_SIGNATURE");
90
+ if (scheme.timestamp) {
91
+ if (timestamp === null || !/^[0-9]{1,12}$/.test(timestamp))
92
+ return refuse("WEBHOOK_STALE");
93
+ const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
94
+ if (age > tolerance)
95
+ return refuse("WEBHOOK_STALE");
96
+ }
97
+ let eventId = null;
98
+ try {
99
+ eventId = scheme.eventId(rawBody, headers);
100
+ }
101
+ catch {
102
+ eventId = null;
103
+ }
104
+ if (typeof eventId !== "string" || eventId === "" || eventId.length > MAX_EVENT_ID)
105
+ return refuse("WEBHOOK_NO_EVENT_ID");
106
+ c.set(EVENT, { source, eventId, db: db });
107
+ await next();
108
+ }, SELF_VERIFYING);
109
+ }
110
+ // One CREATE TABLE IF NOT EXISTS per database per isolate.
111
+ const tables = new WeakMap();
112
+ function ensureTable(db) {
113
+ let ready = tables.get(db);
114
+ if (!ready) {
115
+ ready = db.prepare(CREATE_TABLE).run();
116
+ tables.set(db, ready);
117
+ ready.catch(() => tables.delete(db));
118
+ }
119
+ return ready;
120
+ }
121
+ /**
122
+ * Runs the effect's statements once per event. The event row is a plain INSERT in the same batch, so a
123
+ * second delivery's batch fails on the primary key and none of its writes land.
124
+ */
125
+ export async function once(c, effect) {
126
+ const delivery = c.get(EVENT);
127
+ if (!delivery)
128
+ throw new Error("WEBHOOK_NO_BARRIER: once() runs only behind webhookBarrier()");
129
+ const { db, source, eventId } = delivery;
130
+ await ensureTable(db);
131
+ const statements = [];
132
+ effect(statements);
133
+ const insert = db
134
+ .prepare(`INSERT INTO ${EVENTS_TABLE} (source, event_id, received_at) VALUES (?1, ?2, ?3)`)
135
+ .bind(source, eventId, Math.floor(Date.now() / 1000));
136
+ try {
137
+ await db.batch([insert, ...statements]);
138
+ return "done";
139
+ }
140
+ catch (err) {
141
+ const seen = await db.prepare(`SELECT 1 AS seen FROM ${EVENTS_TABLE} WHERE source = ?1 AND event_id = ?2`).bind(source, eventId).first();
142
+ if (seen) {
143
+ log("hook.duplicate", { source });
144
+ return "duplicate";
145
+ }
146
+ throw err;
147
+ }
148
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@wujiland/kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "The Inca kit: Access guard, caller guard, webhook barrier, public-site rules and logging for Inca apps.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./testing": {
13
+ "types": "./dist/testing.d.ts",
14
+ "default": "./dist/testing.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "scripts": {
21
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.workers.json",
22
+ "test": "vitest run",
23
+ "build": "rm -rf dist && tsc -p tsconfig.build.json"
24
+ },
25
+ "peerDependencies": {
26
+ "hono": "4.13.18"
27
+ },
28
+ "devDependencies": {
29
+ "hono": "4.13.18"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }