@wujiland/kit 0.0.0-stage → 1.1.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
+ `wuji-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,18 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ import type { AccessClaims, AccessResult, IncaEnv } from "./types.js";
3
+ export declare function verifyAccess(request: Request, env: IncaEnv): Promise<AccessResult>;
4
+ export declare function accessGuard(options?: {
5
+ allowEmails?: string[];
6
+ }): MiddlewareHandler;
7
+ export declare function accessClaims(c: Context): AccessClaims | null;
8
+ export declare function verifiedClaims(c: Context): AccessClaims | null;
9
+ type RouteList = {
10
+ routes: readonly {
11
+ method: string;
12
+ path: string;
13
+ handler: unknown;
14
+ }[];
15
+ };
16
+ /** Throws unless the app's first registered handler is accessGuard() on every path (03-kit.md §3). */
17
+ export declare function assertGuardFirst(app: RouteList): void;
18
+ export {};
package/dist/access.js ADDED
@@ -0,0 +1,120 @@
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
+ const LOCAL_EMAIL = "dev@localhost";
6
+ 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 {
26
+ kind: "deployed",
27
+ env: e.INCA_ENV,
28
+ public: mode === "public",
29
+ team: e.INCA_ACCESS_TEAM,
30
+ aud: e.INCA_ACCESS_AUD,
31
+ };
32
+ }
33
+ const fail = (code, reason, env) => ({
34
+ result: { ok: false, code },
35
+ reason,
36
+ env,
37
+ });
38
+ async function check(request, env) {
39
+ const config = readConfig(env);
40
+ if (config.kind === "misconfigured")
41
+ return fail("ACCESS_MISCONFIGURED", config.reason);
42
+ if (config.kind === "local") {
43
+ const email = (request.headers.get(DEV_EMAIL_HEADER) ?? "").trim().toLowerCase() || LOCAL_EMAIL;
44
+ return { result: { ok: true, claims: { email, sub: `local:${email}`, kind: "user" } } };
45
+ }
46
+ const token = request.headers.get(ACCESS_JWT_HEADER);
47
+ if (!token) {
48
+ // A public host is not checked at the edge, so no token means an anonymous visitor (INCA-25).
49
+ if (config.public)
50
+ return { result: { ok: true, claims: null } };
51
+ return fail("ACCESS_TOKEN_MISSING", "no_token", config.env);
52
+ }
53
+ const verified = await verifyToken(token, config.team, config.aud);
54
+ if (verified.ok)
55
+ return { result: { ok: true, claims: verified.claims } };
56
+ if (verified.keysUnavailable)
57
+ return fail("ACCESS_KEYS_UNAVAILABLE", verified.reason, config.env);
58
+ return fail("ACCESS_TOKEN_INVALID", verified.reason, config.env);
59
+ }
60
+ function logRefusal(code, reason, id) {
61
+ log("access.refused", { code, reason: reason ?? null, request_id: id });
62
+ }
63
+ export async function verifyAccess(request, env) {
64
+ const { result, reason } = await check(request, env);
65
+ if (!result.ok)
66
+ logRefusal(result.code, reason, request.headers.get(RAY_ID_HEADER));
67
+ return result;
68
+ }
69
+ function accessStatus(code) {
70
+ if (code === "ACCESS_MISCONFIGURED" || code === "ACCESS_KEYS_UNAVAILABLE")
71
+ return 500;
72
+ if (code === "ACCESS_NOT_ALLOWED")
73
+ return 403;
74
+ return 401;
75
+ }
76
+ export function accessGuard(options) {
77
+ const allow = options?.allowEmails ? new Set(options.allowEmails.map((e) => e.toLowerCase())) : null;
78
+ return mark(async (c, next) => {
79
+ setLogContext(c.env);
80
+ const id = requestId(c);
81
+ const { result, reason, env } = await check(c.req.raw, c.env);
82
+ if (!result.ok) {
83
+ // C-09: a webhook sender reaches a prod bypass path tokenless; the barrier's signature check guards it.
84
+ if (result.code === "ACCESS_TOKEN_MISSING" && env === "prod" && nextAfterGuardIs(c, SELF_VERIFYING)) {
85
+ c.set(CLAIMS, null);
86
+ await next();
87
+ return;
88
+ }
89
+ logRefusal(result.code, reason, id);
90
+ return c.json({ ok: false, code: result.code }, accessStatus(result.code));
91
+ }
92
+ if (allow && (!result.claims || !allow.has(result.claims.email))) {
93
+ logRefusal("ACCESS_NOT_ALLOWED", "allow_emails", id);
94
+ return c.json({ ok: false, code: "ACCESS_NOT_ALLOWED" }, 403);
95
+ }
96
+ c.set(CLAIMS, result.claims);
97
+ await next();
98
+ }, GUARD);
99
+ }
100
+ export function accessClaims(c) {
101
+ const claims = c.get(CLAIMS);
102
+ if (claims === undefined)
103
+ throw new Error("ACCESS_GUARD_NOT_RUN: accessGuard() must run before accessClaims()");
104
+ return claims;
105
+ }
106
+ export function verifiedClaims(c) {
107
+ return c.get(CLAIMS) ?? null;
108
+ }
109
+ /** Throws unless the app's first registered handler is accessGuard() on every path (03-kit.md §3). */
110
+ export function assertGuardFirst(app) {
111
+ const first = app.routes[0];
112
+ if (!first)
113
+ throw new Error("assertGuardFirst: the app registers nothing; the first middleware must be accessGuard()");
114
+ if (!isMarked(first.handler, GUARD)) {
115
+ throw new Error(`assertGuardFirst: the first handler is ${first.method} ${first.path}, not accessGuard()`);
116
+ }
117
+ if (first.method !== "ALL" || (first.path !== "*" && first.path !== "/*")) {
118
+ throw new Error(`assertGuardFirst: accessGuard() is registered on ${first.method} ${first.path}; use app.use("*", accessGuard())`);
119
+ }
120
+ }
@@ -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,5 @@
1
+ export declare function compareBytes(a: Uint8Array, b: Uint8Array): {
2
+ equal: boolean;
3
+ steps: number;
4
+ };
5
+ export declare function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean;
@@ -0,0 +1,15 @@
1
+ // Constant-time (03-kit.md §5): equal-length inputs walk every byte; `steps` lets a test prove there is no early exit.
2
+ export function compareBytes(a, b) {
3
+ if (a.length !== b.length)
4
+ return { equal: false, steps: 0 };
5
+ let diff = 0;
6
+ let steps = 0;
7
+ for (let i = 0; i < a.length; i++) {
8
+ diff |= a[i] ^ b[i];
9
+ steps++;
10
+ }
11
+ return { equal: diff === 0, steps };
12
+ }
13
+ export function constantTimeEqual(a, b) {
14
+ return compareBytes(a, b).equal;
15
+ }
@@ -0,0 +1,2 @@
1
+ import type { Handler } from "hono";
2
+ export declare function healthz(): Handler;
package/dist/health.js ADDED
@@ -0,0 +1,71 @@
1
+ import { logError } from "./log.js";
2
+ const KINDS = ["d1", "kv", "r2", "service", "durable_object"];
3
+ // Copied from 01-config.md §3: the kit must not depend on @wujiland/config.
4
+ const BINDING_NAME = /^(?!INCA_)[A-Z][A-Z0-9_]{0,62}$/;
5
+ const PROBE_KEY = "inca-healthz";
6
+ const PROBE_TIMEOUT_MS = 2000;
7
+ class HealthFailure extends Error {
8
+ code;
9
+ constructor(code) {
10
+ super(code);
11
+ this.code = code;
12
+ }
13
+ }
14
+ function readStamp(text) {
15
+ if (typeof text !== "string")
16
+ return null;
17
+ let value;
18
+ try {
19
+ value = JSON.parse(text);
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ if (typeof value !== "object" || value === null || Array.isArray(value))
25
+ return null;
26
+ const entries = Object.entries(value);
27
+ return entries.every(([name, kind]) => BINDING_NAME.test(name) && KINDS.includes(kind))
28
+ ? value
29
+ : null;
30
+ }
31
+ function within(work) {
32
+ return new Promise((resolve, reject) => {
33
+ const timer = setTimeout(() => reject(new HealthFailure("HEALTH_PROBE_TIMEOUT")), PROBE_TIMEOUT_MS);
34
+ work.then(resolve, reject).finally(() => clearTimeout(timer));
35
+ });
36
+ }
37
+ async function probe(kind, binding) {
38
+ if ((typeof binding !== "object" && typeof binding !== "function") || binding === null)
39
+ throw new HealthFailure("HEALTH_BINDING_ABSENT");
40
+ if (kind === "d1")
41
+ await within(binding.prepare("SELECT 1").first());
42
+ if (kind === "kv")
43
+ await within(binding.get(PROBE_KEY));
44
+ if (kind === "r2")
45
+ await within(binding.head(PROBE_KEY));
46
+ }
47
+ async function answer(name, kind, env) {
48
+ try {
49
+ await probe(kind, env[name]);
50
+ return "ok";
51
+ }
52
+ catch (err) {
53
+ logError("health.failed", err, { binding: name, kind });
54
+ return err instanceof HealthFailure ? err.code : "HEALTH_PROBE_FAILED";
55
+ }
56
+ }
57
+ export function healthz() {
58
+ return async (c) => {
59
+ const env = (c.env ?? {});
60
+ const kinds = readStamp(env.INCA_BINDINGS);
61
+ if (!kinds) {
62
+ logError("health.misconfigured", new Error("INCA_BINDINGS is missing or malformed"));
63
+ return c.json({ ok: false, code: "HEALTH_MISCONFIGURED" }, 500);
64
+ }
65
+ const names = Object.keys(kinds).sort();
66
+ const outcomes = await Promise.all(names.map((name) => answer(name, kinds[name], env)));
67
+ const bindings = Object.fromEntries(names.map((name, i) => [name, outcomes[i]]));
68
+ const ok = outcomes.every((o) => o === "ok");
69
+ return c.json({ ok, app: env.INCA_APP ?? null, env: env.INCA_ENV ?? null, bindings }, ok ? 200 : 503);
70
+ };
71
+ }
@@ -0,0 +1,9 @@
1
+ export { accessClaims, accessGuard, assertGuardFirst, verifyAccess } from "./access.js";
2
+ export { CallerRefused, requireCaller, requireUser } from "./caller.js";
3
+ export { healthz } from "./health.js";
4
+ export { log, logError, requestId, requestLog } from "./log.js";
5
+ export type { LogFields, LogValue } from "./log.js";
6
+ export { adminOnly, publicSite, publicWrite } from "./public.js";
7
+ export { once, webhookBarrier } from "./webhook.js";
8
+ export type { SignatureScheme, WebhookOptions } from "./webhook.js";
9
+ export type { AccessClaims, AccessResult, D1Like, D1Statement, IncaEnv, RateLimitBinding } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { accessClaims, accessGuard, assertGuardFirst, verifyAccess } from "./access.js";
2
+ export { CallerRefused, requireCaller, requireUser } from "./caller.js";
3
+ export { healthz } from "./health.js";
4
+ export { log, logError, requestId, requestLog } from "./log.js";
5
+ export { adminOnly, publicSite, publicWrite } from "./public.js";
6
+ 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
+ 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
+ export declare function verifyToken(token: string, team: string, aud: string): Promise<VerifyResult>;
14
+ export {};
package/dist/jwt.js ADDED
@@ -0,0 +1,114 @@
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, ["verify"]);
48
+ keys.set(jwk.kid, key);
49
+ }
50
+ return keys;
51
+ }
52
+ function loadKeys(team) {
53
+ const set = { at: Date.now(), keys: fetchKeys(team) };
54
+ keyCache.set(team, set);
55
+ set.keys.catch(() => {
56
+ if (keyCache.get(team) === set)
57
+ keyCache.delete(team);
58
+ });
59
+ return set;
60
+ }
61
+ async function keyFor(team, kid) {
62
+ let set = keyCache.get(team);
63
+ if (!set || Date.now() - set.at > KEYS_TTL_MS)
64
+ set = loadKeys(team);
65
+ let key = (await set.keys).get(kid);
66
+ // An unknown kid may mean the team rotated its keys; refetch, but at most once a minute.
67
+ if (!key && Date.now() - set.at > KEYS_REFRESH_MIN_MS)
68
+ key = (await loadKeys(team).keys).get(kid);
69
+ return key;
70
+ }
71
+ export async function verifyToken(token, team, aud) {
72
+ const parts = token.split(".");
73
+ if (parts.length !== 3)
74
+ return { ok: false, reason: "not_a_jwt" };
75
+ const [h, p, s] = parts;
76
+ const header = jsonObject(base64UrlDecode(h));
77
+ const payload = jsonObject(base64UrlDecode(p));
78
+ const signature = base64UrlDecode(s);
79
+ if (!header || !payload || !signature)
80
+ return { ok: false, reason: "malformed" };
81
+ if (header.alg !== "RS256")
82
+ return { ok: false, reason: "alg" };
83
+ if (typeof header.kid !== "string" || header.kid === "")
84
+ return { ok: false, reason: "no_kid" };
85
+ let key;
86
+ try {
87
+ key = await keyFor(team, header.kid);
88
+ }
89
+ catch {
90
+ return { ok: false, reason: "keys_unavailable", keysUnavailable: true };
91
+ }
92
+ if (!key)
93
+ return { ok: false, reason: "unknown_kid" };
94
+ const valid = await crypto.subtle.verify(RS256, key, signature, utf8.encode(`${h}.${p}`)).catch(() => false);
95
+ if (!valid)
96
+ return { ok: false, reason: "signature" };
97
+ if (payload.iss !== accessIssuer(team))
98
+ return { ok: false, reason: "issuer" };
99
+ const audOk = typeof payload.aud === "string" ? payload.aud === aud : Array.isArray(payload.aud) && payload.aud.includes(aud);
100
+ if (!audOk)
101
+ return { ok: false, reason: "audience" };
102
+ const now = Math.floor(Date.now() / 1000);
103
+ if (typeof payload.exp !== "number" || now > payload.exp + LEEWAY_SECONDS)
104
+ return { ok: false, reason: "expired" };
105
+ if (payload.nbf !== undefined && (typeof payload.nbf !== "number" || now < payload.nbf - LEEWAY_SECONDS)) {
106
+ return { ok: false, reason: "not_yet_valid" };
107
+ }
108
+ // C-36 is off: a service-token identity carries no email and is refused.
109
+ if (typeof payload.sub !== "string" || payload.sub === "")
110
+ return { ok: false, reason: "no_sub" };
111
+ if (typeof payload.email !== "string" || payload.email === "")
112
+ return { ok: false, reason: "no_email" };
113
+ return { ok: true, claims: { email: payload.email.toLowerCase(), sub: payload.sub, kind: "user" } };
114
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,8 @@
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 log(event: string, fields?: LogFields): void;
6
+ export declare function logError(event: string, err: unknown, fields?: LogFields): void;
7
+ export declare function requestId(c: Context): string;
8
+ export declare function requestLog(): MiddlewareHandler;
package/dist/log.js ADDED
@@ -0,0 +1,93 @@
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
+ let isolate = { app: null, env: null };
7
+ export function setLogContext(env) {
8
+ const e = (env ?? {});
9
+ isolate = {
10
+ app: typeof e.INCA_APP === "string" ? e.INCA_APP : null,
11
+ env: typeof e.INCA_ENV === "string" ? e.INCA_ENV : null,
12
+ };
13
+ }
14
+ function isSecretKey(key) {
15
+ const k = key.toLowerCase();
16
+ return (k.includes("token") || k.includes("secret") || k.includes("password") || k === "authorization" || k === "cookie");
17
+ }
18
+ function scalar(value) {
19
+ if (value === null || typeof value === "boolean")
20
+ return value;
21
+ if (typeof value === "number")
22
+ return Number.isFinite(value) ? value : String(value);
23
+ if (typeof value === "string")
24
+ return value.length > MAX_VALUE_LENGTH ? `${value.slice(0, MAX_VALUE_LENGTH)}…` : value;
25
+ return "[unsupported]";
26
+ }
27
+ function line(level, event, fields) {
28
+ const out = {
29
+ t: new Date().toISOString(),
30
+ level,
31
+ event: String(event),
32
+ app: isolate.app,
33
+ env: isolate.env,
34
+ request_id: null,
35
+ };
36
+ let redacted = false;
37
+ for (const [key, value] of Object.entries(fields ?? {})) {
38
+ if (key === "request_id") {
39
+ out.request_id = scalar(value);
40
+ continue;
41
+ }
42
+ const name = RESERVED.has(key) ? `field_${key}` : key;
43
+ if (isSecretKey(key)) {
44
+ out[name] = "[redacted]";
45
+ redacted = true;
46
+ }
47
+ else {
48
+ out[name] = scalar(value);
49
+ }
50
+ }
51
+ if (redacted)
52
+ out.redacted = true;
53
+ return JSON.stringify(out);
54
+ }
55
+ export function log(event, fields) {
56
+ console.log(line("info", event, fields));
57
+ }
58
+ export function logError(event, err, fields) {
59
+ const e = err instanceof Error ? err : null;
60
+ console.log(line("error", event, {
61
+ ...fields,
62
+ error_name: e ? e.name : "NonError",
63
+ error_message: e ? e.message : String(err),
64
+ error_stack: e?.stack ?? null,
65
+ }));
66
+ }
67
+ export function requestId(c) {
68
+ const known = c.get(REQUEST_ID);
69
+ if (known)
70
+ return known;
71
+ const id = c.req.header(RAY_ID_HEADER) || crypto.randomUUID();
72
+ c.set(REQUEST_ID, id);
73
+ return id;
74
+ }
75
+ export function requestLog() {
76
+ return async (c, next) => {
77
+ setLogContext(c.env);
78
+ const id = requestId(c);
79
+ const started = Date.now();
80
+ try {
81
+ await next();
82
+ }
83
+ finally {
84
+ log("request", {
85
+ request_id: id,
86
+ method: c.req.method,
87
+ route: routePath(c, -1) || null,
88
+ status: c.res.status,
89
+ ms: Date.now() - started,
90
+ });
91
+ }
92
+ };
93
+ }
@@ -0,0 +1,9 @@
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
+ export declare function routeHas(c: Context, symbol: symbol): boolean;
8
+ /** A tokenless request may pass the guard only into the barrier itself, never into app code registered between. */
9
+ export declare function nextAfterGuardIs(c: Context, symbol: symbol): boolean;
@@ -0,0 +1,20 @@
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
+ export function routeHas(c, symbol) {
13
+ return matchedRoutes(c).some((r) => isMarked(r.handler, symbol));
14
+ }
15
+ /** A tokenless request may pass the guard only into the barrier itself, never into app code registered between. */
16
+ export function nextAfterGuardIs(c, symbol) {
17
+ const routes = matchedRoutes(c);
18
+ const guard = routes.findIndex((r) => isMarked(r.handler, GUARD));
19
+ return guard >= 0 && isMarked(routes[guard + 1]?.handler, symbol);
20
+ }
@@ -0,0 +1,2 @@
1
+ export declare function covered(path: string, patterns: readonly string[]): boolean;
2
+ export declare const SLUG: RegExp;
package/dist/paths.js ADDED
@@ -0,0 +1,8 @@
1
+ // Path coverage (01-config.md §4), copied: the kit must not depend on @wujiland/config (02-renderer.md §3).
2
+ function covers(pattern, path) {
3
+ return pattern.endsWith("/*") ? path.startsWith(pattern.slice(0, -1)) : path === pattern;
4
+ }
5
+ export function covered(path, patterns) {
6
+ return patterns.some((p) => covers(p, path));
7
+ }
8
+ export const SLUG = /^[a-z0-9]([a-z0-9-]{0,40}[a-z0-9])?$/;
@@ -0,0 +1,5 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ export declare function publicSite(): MiddlewareHandler;
3
+ export declare function adminOnly(): MiddlewareHandler;
4
+ /** Opts one route into non-GET methods in public mode (03-kit.md §7). */
5
+ export declare function publicWrite(): MiddlewareHandler;
package/dist/public.js ADDED
@@ -0,0 +1,84 @@
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
+ const NO_ADDRESS_KEY = "no-client-address";
8
+ function pathList(text) {
9
+ if (typeof text !== "string")
10
+ return null;
11
+ try {
12
+ const v = JSON.parse(text);
13
+ return Array.isArray(v) && v.every((p) => typeof p === "string" && p.startsWith("/")) ? v : null;
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ function needsNoindex(env, host) {
20
+ if (env.INCA_ENV !== "prod")
21
+ return true;
22
+ return typeof env.INCA_CANONICAL_HOST !== "string" || host !== env.INCA_CANONICAL_HOST.toLowerCase();
23
+ }
24
+ function withNoindex(res) {
25
+ const out = new Response(res.body, res);
26
+ out.headers.set("X-Robots-Tag", NOINDEX);
27
+ return out;
28
+ }
29
+ export function publicSite() {
30
+ return async (c, next) => {
31
+ const env = (c.env ?? {});
32
+ const url = new URL(c.req.url);
33
+ const noindex = needsNoindex(env, url.hostname.toLowerCase());
34
+ const refuse = (code, status, headers) => {
35
+ log("public.refused", { code, request_id: requestId(c) });
36
+ const res = status === 404 ? c.notFound() : c.json({ ok: false, code }, status, headers);
37
+ return noindex ? withNoindex(res) : res;
38
+ };
39
+ if (env.INCA_ACCESS_MODE === "public") {
40
+ const adminPaths = pathList(env.INCA_ADMIN_PATHS);
41
+ const bypassPaths = pathList(env.INCA_BYPASS_PATHS);
42
+ const limiter = rateLimitBinding(env);
43
+ if (!adminPaths || !bypassPaths || typeof env.INCA_CANONICAL_HOST !== "string" || !limiter) {
44
+ return refuse("PUBLIC_MISCONFIGURED", 500);
45
+ }
46
+ let allowed;
47
+ try {
48
+ allowed = await rateLimitAllows(limiter, clientAddress(c.req.raw) ?? NO_ADDRESS_KEY);
49
+ }
50
+ catch {
51
+ return refuse("PUBLIC_RATE_LIMIT_FAILED", 500);
52
+ }
53
+ if (!allowed)
54
+ return refuse("RATE_LIMITED", 429, { "Retry-After": String(RATE_LIMIT_RETRY_AFTER_SECONDS) });
55
+ // INCA-25: refused by host, before any handler; a token proves nothing where the edge is not checking.
56
+ if (covered(url.pathname, adminPaths))
57
+ return refuse("ADMIN_PATH_ON_PUBLIC_HOST", 404);
58
+ const method = c.req.method;
59
+ if (method !== "GET" && method !== "HEAD" && !covered(url.pathname, bypassPaths) && !routeHas(c, PUBLIC_WRITE)) {
60
+ return refuse("METHOD_NOT_ALLOWED", 405, { Allow: "GET, HEAD" });
61
+ }
62
+ }
63
+ await next();
64
+ if (noindex)
65
+ c.header("X-Robots-Tag", NOINDEX);
66
+ };
67
+ }
68
+ export function adminOnly() {
69
+ return async (c, next) => {
70
+ const env = (c.env ?? {});
71
+ const privateHost = env.INCA_ENV === "local" || env.INCA_ACCESS_MODE === "private" || env.INCA_ACCESS_MODE === "named";
72
+ if (!privateHost || !verifiedClaims(c)) {
73
+ log("public.refused", { code: "ADMIN_ONLY", request_id: requestId(c) });
74
+ return c.notFound();
75
+ }
76
+ await next();
77
+ };
78
+ }
79
+ /** Opts one route into non-GET methods in public mode (03-kit.md §7). */
80
+ export function publicWrite() {
81
+ return mark(async (_c, next) => {
82
+ await next();
83
+ }, PUBLIC_WRITE);
84
+ }
@@ -0,0 +1,36 @@
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
+ export declare function testJwks(): Promise<{
8
+ keys: JsonWebKey[];
9
+ }>;
10
+ export type TokenOptions = {
11
+ claims?: Record<string, unknown>;
12
+ header?: Record<string, unknown>;
13
+ signWith?: "primary" | "other" | "hs256" | "none";
14
+ team?: string;
15
+ aud?: string;
16
+ };
17
+ export declare function signAccessToken(options?: TokenOptions): Promise<string>;
18
+ export declare function installTestJwks(team?: string): {
19
+ calls: string[];
20
+ restore: () => void;
21
+ };
22
+ /** The stamps of `local` render mode (02-renderer.md §5). */
23
+ export declare function localEnv(overrides?: Partial<IncaEnv> & Record<string, unknown>): IncaEnv & Record<string, unknown>;
24
+ export declare function deployedEnv(overrides?: Partial<IncaEnv> & Record<string, unknown>): IncaEnv & Record<string, unknown>;
25
+ export declare function propsStub(props?: unknown): {
26
+ props: unknown;
27
+ waitUntil(p: Promise<unknown>): void;
28
+ passThroughOnException(): void;
29
+ };
30
+ export declare function signWebhook(options: {
31
+ secret: string;
32
+ body: string;
33
+ scheme: SignatureScheme;
34
+ timestamp?: number | null;
35
+ headers?: Record<string, string>;
36
+ }): Promise<Headers>;
@@ -0,0 +1,116 @@
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, [
10
+ "sign",
11
+ "verify",
12
+ ]);
13
+ }
14
+ function keyPairs() {
15
+ pairs ??= Promise.all([makePair(), makePair()]).then(([primary, other]) => ({ primary, other }));
16
+ return pairs;
17
+ }
18
+ function b64url(bytes) {
19
+ const raw = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
20
+ let bin = "";
21
+ for (const b of raw)
22
+ bin += String.fromCharCode(b);
23
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ export async function testJwks() {
26
+ const { primary } = await keyPairs();
27
+ const jwk = (await crypto.subtle.exportKey("jwk", primary.publicKey));
28
+ return { keys: [{ kty: jwk.kty, n: jwk.n, e: jwk.e, alg: "RS256", use: "sig", kid: TEST_KID }] };
29
+ }
30
+ export async function signAccessToken(options = {}) {
31
+ const now = Math.floor(Date.now() / 1000);
32
+ const team = options.team ?? TEST_TEAM;
33
+ const signWith = options.signWith ?? "primary";
34
+ const alg = signWith === "hs256" ? "HS256" : signWith === "none" ? "none" : "RS256";
35
+ const header = { alg, kid: TEST_KID, typ: "JWT", ...options.header };
36
+ const claims = {
37
+ iss: accessIssuer(team),
38
+ aud: [options.aud ?? TEST_AUD],
39
+ sub: "00000000-0000-4000-8000-000000000001",
40
+ email: "guest@example.test",
41
+ iat: now,
42
+ nbf: now,
43
+ exp: now + 300,
44
+ type: "app",
45
+ ...options.claims,
46
+ };
47
+ for (const k of Object.keys(claims))
48
+ if (claims[k] === undefined)
49
+ delete claims[k];
50
+ const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
51
+ if (signWith === "none")
52
+ return `${input}.`;
53
+ if (signWith === "hs256") {
54
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode("shared"), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
55
+ return `${input}.${b64url(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(input))))}`;
56
+ }
57
+ const { primary, other } = await keyPairs();
58
+ const key = signWith === "other" ? other.privateKey : primary.privateKey;
59
+ return `${input}.${b64url(new Uint8Array(await crypto.subtle.sign(RS256, key, new TextEncoder().encode(input))))}`;
60
+ }
61
+ export function installTestJwks(team = TEST_TEAM) {
62
+ const original = globalThis.fetch;
63
+ const calls = [];
64
+ globalThis.fetch = (async (input) => {
65
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
66
+ calls.push(url);
67
+ if (url === accessCertsUrl(team))
68
+ return Response.json(await testJwks());
69
+ throw new Error(`installTestJwks: unexpected network request to ${url}`);
70
+ });
71
+ return { calls, restore: () => void (globalThis.fetch = original) };
72
+ }
73
+ /** The stamps of `local` render mode (02-renderer.md §5). */
74
+ export function localEnv(overrides = {}) {
75
+ return { INCA_ENV: "local", INCA_APP: "app", INCA_HOST: "localhost", ...overrides };
76
+ }
77
+ export function deployedEnv(overrides = {}) {
78
+ return {
79
+ INCA_ENV: "uat",
80
+ INCA_APP: "app",
81
+ INCA_HOST: "app-uat.example.test",
82
+ INCA_ACCESS_MODE: "private",
83
+ INCA_ACCESS_TEAM: TEST_TEAM,
84
+ INCA_ACCESS_AUD: TEST_AUD,
85
+ INCA_EXPOSES: "{}",
86
+ INCA_CALLER_AUDS: "{}",
87
+ ...overrides,
88
+ };
89
+ }
90
+ export function propsStub(props = { app: "caller" }) {
91
+ return { props, waitUntil: () => { }, passThroughOnException: () => { } };
92
+ }
93
+ export async function signWebhook(options) {
94
+ const { scheme } = options;
95
+ const ts = scheme.timestamp === null
96
+ ? null
97
+ : options.timestamp === null
98
+ ? null
99
+ : String(options.timestamp ?? Math.floor(Date.now() / 1000));
100
+ const enc = new TextEncoder();
101
+ const key = await crypto.subtle.importKey("raw", enc.encode(options.secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
102
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(scheme.signedPayload(ts, options.body))));
103
+ const sig = scheme.encoding === "hex"
104
+ ? [...mac].map((b) => b.toString(16).padStart(2, "0")).join("")
105
+ : btoa(String.fromCharCode(...mac));
106
+ const headers = new Headers(options.headers);
107
+ if (scheme.timestamp && "inSignatureHeader" in scheme.timestamp) {
108
+ headers.set(scheme.signatureHeader, `${ts !== null ? `t=${ts},` : ""}v1=${sig}`);
109
+ }
110
+ else {
111
+ headers.set(scheme.signatureHeader, `${scheme.signaturePrefix ?? ""}${sig}`);
112
+ if (scheme.timestamp && ts !== null)
113
+ headers.set(scheme.timestamp.header, ts);
114
+ }
115
+ return headers;
116
+ }
@@ -0,0 +1,45 @@
1
+ export interface RateLimitBinding {
2
+ limit(options: {
3
+ key: string;
4
+ }): Promise<{
5
+ success: boolean;
6
+ }>;
7
+ }
8
+ /** Stamps the broker sets (01-config.md §11, 02-renderer.md §5); the kit validates every one. */
9
+ export interface IncaEnv {
10
+ INCA_APP?: string;
11
+ INCA_BINDINGS?: 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
+ export interface D1Statement {
38
+ bind(...values: unknown[]): D1Statement;
39
+ first(): Promise<unknown>;
40
+ run(): Promise<unknown>;
41
+ }
42
+ export interface D1Like {
43
+ prepare(query: string): D1Statement;
44
+ batch(statements: D1Statement[]): Promise<unknown[]>;
45
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import type { IncaEnv, RateLimitBinding } from "./types.js";
2
+ export declare const ACCESS_JWT_HEADER = "Cf-Access-Jwt-Assertion";
3
+ export declare const RAY_ID_HEADER = "cf-ray";
4
+ export declare function accessIssuer(team: string): string;
5
+ export declare function accessCertsUrl(team: string): string;
6
+ export declare function bindingProps(ctx: unknown): unknown;
7
+ export declare function clientAddress(request: Request): string | null;
8
+ export declare function rateLimitBinding(env: IncaEnv): RateLimitBinding | null;
9
+ export declare function rateLimitAllows(binding: RateLimitBinding, key: string): Promise<boolean>;
10
+ /** The binding's period is not readable from the Worker; 60 s is the longest one the config allows. */
11
+ export declare const RATE_LIMIT_RETRY_AFTER_SECONDS = 60;
package/dist/vendor.js ADDED
@@ -0,0 +1,33 @@
1
+ // [verify] at A5: the Access, client-address and ray headers; the JWKS URL and shape; ctx.props; RateLimit.limit.
2
+ export const ACCESS_JWT_HEADER = "Cf-Access-Jwt-Assertion";
3
+ const CLIENT_ADDRESS_HEADER = "CF-Connecting-IP";
4
+ export const RAY_ID_HEADER = "cf-ray";
5
+ export function accessIssuer(team) {
6
+ return `https://${team}.cloudflareaccess.com`;
7
+ }
8
+ export function accessCertsUrl(team) {
9
+ return `${accessIssuer(team)}/cdn-cgi/access/certs`;
10
+ }
11
+ export function bindingProps(ctx) {
12
+ if (typeof ctx !== "object" || ctx === null)
13
+ return undefined;
14
+ return ctx.props;
15
+ }
16
+ export function clientAddress(request) {
17
+ return request.headers.get(CLIENT_ADDRESS_HEADER);
18
+ }
19
+ export function rateLimitBinding(env) {
20
+ const b = env.INCA_RATE_LIMIT;
21
+ if (typeof b !== "object" || b === null)
22
+ return null;
23
+ return typeof b.limit === "function" ? b : null;
24
+ }
25
+ export async function rateLimitAllows(binding, key) {
26
+ const outcome = await binding.limit({ key });
27
+ const success = outcome?.success;
28
+ if (typeof success !== "boolean")
29
+ throw new Error("VENDOR_SHAPE: rate-limit outcome has no boolean success");
30
+ return success;
31
+ }
32
+ /** The binding's period is not readable from the Worker; 60 s is the longest one the config allows. */
33
+ export const RATE_LIMIT_RETRY_AFTER_SECONDS = 60;
@@ -0,0 +1,24 @@
1
+ import type { Context, MiddlewareHandler } from "hono";
2
+ import type { D1Like, D1Statement } from "./types.js";
3
+ export type SignatureScheme = {
4
+ signatureHeader: string;
5
+ signaturePrefix?: string;
6
+ timestamp: {
7
+ header: string;
8
+ } | {
9
+ inSignatureHeader: true;
10
+ } | null;
11
+ signedPayload: (timestamp: string | null, rawBody: string) => string;
12
+ encoding: "hex" | "base64";
13
+ eventId: (rawBody: string, headers: Headers) => string | null;
14
+ };
15
+ export type WebhookOptions<E = any> = {
16
+ source: string;
17
+ secret: (env: E) => string;
18
+ scheme: SignatureScheme;
19
+ db: (env: E) => D1Like;
20
+ toleranceSeconds?: number;
21
+ };
22
+ export declare function webhookBarrier<E = any>(options: WebhookOptions<E>): MiddlewareHandler;
23
+ /** The event row is a plain INSERT in the same batch: a second delivery fails on the key, none of its writes land. */
24
+ export declare function once(c: Context, effect: (stmts: D1Statement[]) => void): Promise<"done" | "duplicate">;
@@ -0,0 +1,149 @@
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
+ const EVENTS_TABLE = "_inca_webhook_events";
9
+ const CREATE_TABLE = `CREATE TABLE IF NOT EXISTS ${EVENTS_TABLE} ` +
10
+ `(source TEXT NOT NULL, event_id TEXT NOT NULL, received_at INTEGER NOT NULL, PRIMARY KEY (source, event_id))`;
11
+ function decodeSignature(text, encoding) {
12
+ if (encoding === "hex") {
13
+ if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text))
14
+ return null;
15
+ const out = new Uint8Array(text.length / 2);
16
+ for (let i = 0; i < out.length; i++)
17
+ out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
18
+ return out;
19
+ }
20
+ return base64UrlDecode(text.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""));
21
+ }
22
+ function readSignatures(scheme, headers) {
23
+ const value = headers.get(scheme.signatureHeader);
24
+ if (value === null)
25
+ return { signatures: [], timestamp: null };
26
+ if (scheme.timestamp && "inSignatureHeader" in scheme.timestamp) {
27
+ let timestamp = null;
28
+ const signatures = [];
29
+ for (const part of value.split(",")) {
30
+ const eq = part.indexOf("=");
31
+ if (eq < 0)
32
+ continue;
33
+ const k = part.slice(0, eq).trim();
34
+ const v = part.slice(eq + 1).trim();
35
+ if (k === "t")
36
+ timestamp = v;
37
+ else if (k === "v1")
38
+ signatures.push(v);
39
+ }
40
+ return { signatures, timestamp };
41
+ }
42
+ const prefix = scheme.signaturePrefix ?? "";
43
+ if (!value.startsWith(prefix))
44
+ return { signatures: [], timestamp: null };
45
+ const timestamp = scheme.timestamp && "header" in scheme.timestamp ? headers.get(scheme.timestamp.header) : null;
46
+ return { signatures: [value.slice(prefix.length).trim()], timestamp };
47
+ }
48
+ async function hmac(secret, payload) {
49
+ const enc = new TextEncoder();
50
+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
51
+ "sign",
52
+ ]);
53
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(payload)));
54
+ }
55
+ export function webhookBarrier(options) {
56
+ if (!SLUG.test(options.source))
57
+ throw new Error(`webhookBarrier: source ${options.source} is not a slug`);
58
+ const tolerance = options.toleranceSeconds ?? 300;
59
+ const { source, scheme } = options;
60
+ return mark(async (c, next) => {
61
+ setLogContext(c.env);
62
+ const refuse = (code, status = 401) => {
63
+ log("hook.refused", { source, code });
64
+ return c.json({ ok: false, code }, status);
65
+ };
66
+ let secret;
67
+ let db;
68
+ try {
69
+ secret = options.secret(c.env);
70
+ db = options.db(c.env);
71
+ }
72
+ catch {
73
+ return refuse("WEBHOOK_MISCONFIGURED", 500);
74
+ }
75
+ if (typeof secret !== "string" || secret === "")
76
+ return refuse("WEBHOOK_MISCONFIGURED", 500);
77
+ if (typeof db !== "object" || db === null || typeof db.batch !== "function") {
78
+ return refuse("WEBHOOK_MISCONFIGURED", 500);
79
+ }
80
+ const rawBody = await c.req.text();
81
+ const headers = c.req.raw.headers;
82
+ const { signatures, timestamp } = readSignatures(scheme, headers);
83
+ const expected = await hmac(secret, scheme.signedPayload(timestamp, rawBody));
84
+ let match = false;
85
+ for (const sig of signatures) {
86
+ const given = decodeSignature(sig, scheme.encoding);
87
+ const equal = given !== null && constantTimeEqual(given, expected);
88
+ match = match || equal;
89
+ }
90
+ if (!match)
91
+ return refuse("WEBHOOK_SIGNATURE");
92
+ if (scheme.timestamp) {
93
+ if (timestamp === null || !/^[0-9]{1,12}$/.test(timestamp))
94
+ return refuse("WEBHOOK_STALE");
95
+ const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
96
+ if (age > tolerance)
97
+ return refuse("WEBHOOK_STALE");
98
+ }
99
+ let eventId = null;
100
+ try {
101
+ eventId = scheme.eventId(rawBody, headers);
102
+ }
103
+ catch {
104
+ eventId = null;
105
+ }
106
+ if (typeof eventId !== "string" || eventId === "" || eventId.length > MAX_EVENT_ID)
107
+ return refuse("WEBHOOK_NO_EVENT_ID");
108
+ c.set(EVENT, { source, eventId, db: db });
109
+ await next();
110
+ }, SELF_VERIFYING);
111
+ }
112
+ const tables = new WeakMap();
113
+ function ensureTable(db) {
114
+ let ready = tables.get(db);
115
+ if (!ready) {
116
+ ready = db.prepare(CREATE_TABLE).run();
117
+ tables.set(db, ready);
118
+ ready.catch(() => tables.delete(db));
119
+ }
120
+ return ready;
121
+ }
122
+ /** The event row is a plain INSERT in the same batch: a second delivery fails on the key, none of its writes land. */
123
+ export async function once(c, effect) {
124
+ const delivery = c.get(EVENT);
125
+ if (!delivery)
126
+ throw new Error("WEBHOOK_NO_BARRIER: once() runs only behind webhookBarrier()");
127
+ const { db, source, eventId } = delivery;
128
+ await ensureTable(db);
129
+ const statements = [];
130
+ effect(statements);
131
+ const insert = db
132
+ .prepare(`INSERT INTO ${EVENTS_TABLE} (source, event_id, received_at) VALUES (?1, ?2, ?3)`)
133
+ .bind(source, eventId, Math.floor(Date.now() / 1000));
134
+ try {
135
+ await db.batch([insert, ...statements]);
136
+ return "done";
137
+ }
138
+ catch (err) {
139
+ const seen = await db
140
+ .prepare(`SELECT 1 AS seen FROM ${EVENTS_TABLE} WHERE source = ?1 AND event_id = ?2`)
141
+ .bind(source, eventId)
142
+ .first();
143
+ if (seen) {
144
+ log("hook.duplicate", { source });
145
+ return "duplicate";
146
+ }
147
+ throw err;
148
+ }
149
+ }
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.1.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
+ }