@leed-ai/git-gateway-worker 0.0.0-stage → 0.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.
Files changed (269) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +49 -2
  3. package/dist/audit/audit-recorder.d.ts +2 -0
  4. package/dist/audit/audit-recorder.js +53 -0
  5. package/dist/audit/audit-recorder.js.map +1 -0
  6. package/dist/audit/push-report.d.ts +13 -0
  7. package/dist/audit/push-report.js +66 -0
  8. package/dist/audit/push-report.js.map +1 -0
  9. package/dist/audit-recorder-K1Ns3tfC.d.ts +31 -0
  10. package/dist/auth/authenticate.d.ts +14 -0
  11. package/dist/auth/authenticate.js +59 -0
  12. package/dist/auth/authenticate.js.map +1 -0
  13. package/dist/auth/authorize.d.ts +12 -0
  14. package/dist/auth/authorize.js +57 -0
  15. package/dist/auth/authorize.js.map +1 -0
  16. package/dist/auth/read-token-auth.d.ts +60 -0
  17. package/dist/auth/read-token-auth.js +83 -0
  18. package/dist/auth/read-token-auth.js.map +1 -0
  19. package/dist/cache/decision-cache.d.ts +2 -0
  20. package/dist/cache/decision-cache.js +45 -0
  21. package/dist/cache/decision-cache.js.map +1 -0
  22. package/dist/commit-workflow-schemas-BWlg7bZR.d.ts +95 -0
  23. package/dist/decision-cache-87U32iSj.d.ts +24 -0
  24. package/dist/gateway-app.d.ts +69 -0
  25. package/dist/gateway-app.js +80 -0
  26. package/dist/gateway-app.js.map +1 -0
  27. package/dist/gateway-context-Boh9I0mk.d.ts +54 -0
  28. package/dist/gateway-env-DnsBU4Pq.d.ts +40 -0
  29. package/dist/gateway-worker.d.ts +13 -0
  30. package/dist/gateway-worker.js +22 -0
  31. package/dist/gateway-worker.js.map +1 -0
  32. package/dist/git-route-Spxi09Rm.d.ts +22 -0
  33. package/dist/health.d.ts +6 -0
  34. package/dist/health.js +16 -0
  35. package/dist/health.js.map +1 -0
  36. package/dist/logger-BZ1zyKLb.d.ts +27 -0
  37. package/dist/logging/logger.d.ts +2 -0
  38. package/dist/logging/logger.js +15 -0
  39. package/dist/logging/logger.js.map +1 -0
  40. package/dist/on-push-DTREOB__.d.ts +62 -0
  41. package/dist/policy/branch-policy.d.ts +24 -0
  42. package/dist/policy/branch-policy.js +125 -0
  43. package/dist/policy/branch-policy.js.map +1 -0
  44. package/dist/policy/enforce-branch-policy.d.ts +30 -0
  45. package/dist/policy/enforce-branch-policy.js +214 -0
  46. package/dist/policy/enforce-branch-policy.js.map +1 -0
  47. package/dist/policy/fast-forward.d.ts +32 -0
  48. package/dist/policy/fast-forward.js +95 -0
  49. package/dist/policy/fast-forward.js.map +1 -0
  50. package/dist/policy/ref-pattern.d.ts +7 -0
  51. package/dist/policy/ref-pattern.js +25 -0
  52. package/dist/policy/ref-pattern.js.map +1 -0
  53. package/dist/policy/rule-branch-policy.d.ts +17 -0
  54. package/dist/policy/rule-branch-policy.js +69 -0
  55. package/dist/policy/rule-branch-policy.js.map +1 -0
  56. package/dist/proxy/defer.d.ts +8 -0
  57. package/dist/proxy/defer.js +15 -0
  58. package/dist/proxy/defer.js.map +1 -0
  59. package/dist/proxy/forward-read.d.ts +11 -0
  60. package/dist/proxy/forward-read.js +53 -0
  61. package/dist/proxy/forward-read.js.map +1 -0
  62. package/dist/proxy/gateway-deps.d.ts +39 -0
  63. package/dist/proxy/gateway-deps.js +0 -0
  64. package/dist/proxy/gateway-env.d.ts +2 -0
  65. package/dist/proxy/gateway-env.js +0 -0
  66. package/dist/proxy/git-responses.d.ts +25 -0
  67. package/dist/proxy/git-responses.js +83 -0
  68. package/dist/proxy/git-responses.js.map +1 -0
  69. package/dist/proxy/git-route.d.ts +2 -0
  70. package/dist/proxy/git-route.js +34 -0
  71. package/dist/proxy/git-route.js.map +1 -0
  72. package/dist/proxy/push-events.d.ts +28 -0
  73. package/dist/proxy/push-events.js +65 -0
  74. package/dist/proxy/push-events.js.map +1 -0
  75. package/dist/proxy/push-guard.d.ts +43 -0
  76. package/dist/proxy/push-guard.js +81 -0
  77. package/dist/proxy/push-guard.js.map +1 -0
  78. package/dist/proxy/push-options.d.ts +16 -0
  79. package/dist/proxy/push-options.js +33 -0
  80. package/dist/proxy/push-options.js.map +1 -0
  81. package/dist/proxy/receive-pack.d.ts +17 -0
  82. package/dist/proxy/receive-pack.js +244 -0
  83. package/dist/proxy/receive-pack.js.map +1 -0
  84. package/dist/proxy/request-log.d.ts +13 -0
  85. package/dist/proxy/request-log.js +41 -0
  86. package/dist/proxy/request-log.js.map +1 -0
  87. package/dist/proxy/resolve-route.d.ts +9 -0
  88. package/dist/proxy/resolve-route.js +22 -0
  89. package/dist/proxy/resolve-route.js.map +1 -0
  90. package/dist/proxy/upstream-call.d.ts +23 -0
  91. package/dist/proxy/upstream-call.js +63 -0
  92. package/dist/proxy/upstream-call.js.map +1 -0
  93. package/dist/proxy/upstream.d.ts +2 -0
  94. package/dist/proxy/upstream.js +68 -0
  95. package/dist/proxy/upstream.js.map +1 -0
  96. package/dist/push-event-f-5TsFUY.d.ts +15 -0
  97. package/dist/push-policy/changed-paths.d.ts +26 -0
  98. package/dist/push-policy/changed-paths.js +117 -0
  99. package/dist/push-policy/changed-paths.js.map +1 -0
  100. package/dist/push-policy/pushed-objects.d.ts +30 -0
  101. package/dist/push-policy/pushed-objects.js +76 -0
  102. package/dist/push-policy/pushed-objects.js.map +1 -0
  103. package/dist/push-policy/run-push-policy.d.ts +35 -0
  104. package/dist/push-policy/run-push-policy.js +77 -0
  105. package/dist/push-policy/run-push-policy.js.map +1 -0
  106. package/dist/push-policy/tree-diff.d.ts +21 -0
  107. package/dist/push-policy/tree-diff.js +78 -0
  108. package/dist/push-policy/tree-diff.js.map +1 -0
  109. package/dist/push-policy/uncheckable.d.ts +14 -0
  110. package/dist/push-policy/uncheckable.js +25 -0
  111. package/dist/push-policy/uncheckable.js.map +1 -0
  112. package/dist/rpc/branch-methods.d.ts +16 -0
  113. package/dist/rpc/branch-methods.js +43 -0
  114. package/dist/rpc/branch-methods.js.map +1 -0
  115. package/dist/rpc/commit-attempt.d.ts +27 -0
  116. package/dist/rpc/commit-attempt.js +85 -0
  117. package/dist/rpc/commit-attempt.js.map +1 -0
  118. package/dist/rpc/commit-graph.d.ts +20 -0
  119. package/dist/rpc/commit-graph.js +38 -0
  120. package/dist/rpc/commit-graph.js.map +1 -0
  121. package/dist/rpc/commit-method.d.ts +13 -0
  122. package/dist/rpc/commit-method.js +30 -0
  123. package/dist/rpc/commit-method.js.map +1 -0
  124. package/dist/rpc/commit-source.d.ts +12 -0
  125. package/dist/rpc/commit-source.js +9 -0
  126. package/dist/rpc/commit-source.js.map +1 -0
  127. package/dist/rpc/gateway-context.d.ts +2 -0
  128. package/dist/rpc/gateway-context.js +30 -0
  129. package/dist/rpc/gateway-context.js.map +1 -0
  130. package/dist/rpc/gateway-rpc.d.ts +10 -0
  131. package/dist/rpc/gateway-rpc.js +48 -0
  132. package/dist/rpc/gateway-rpc.js.map +1 -0
  133. package/dist/rpc/gateway-service.d.ts +24 -0
  134. package/dist/rpc/gateway-service.js +63 -0
  135. package/dist/rpc/gateway-service.js.map +1 -0
  136. package/dist/rpc/history-page.d.ts +35 -0
  137. package/dist/rpc/history-page.js +122 -0
  138. package/dist/rpc/history-page.js.map +1 -0
  139. package/dist/rpc/lifecycle-methods.d.ts +12 -0
  140. package/dist/rpc/lifecycle-methods.js +39 -0
  141. package/dist/rpc/lifecycle-methods.js.map +1 -0
  142. package/dist/rpc/paint-down.d.ts +17 -0
  143. package/dist/rpc/paint-down.js +96 -0
  144. package/dist/rpc/paint-down.js.map +1 -0
  145. package/dist/rpc/promote-attempt.d.ts +21 -0
  146. package/dist/rpc/promote-attempt.js +55 -0
  147. package/dist/rpc/promote-attempt.js.map +1 -0
  148. package/dist/rpc/push-ref.d.ts +21 -0
  149. package/dist/rpc/push-ref.js +47 -0
  150. package/dist/rpc/push-ref.js.map +1 -0
  151. package/dist/rpc/read-methods.d.ts +17 -0
  152. package/dist/rpc/read-methods.js +94 -0
  153. package/dist/rpc/read-methods.js.map +1 -0
  154. package/dist/rpc/read-token.d.ts +39 -0
  155. package/dist/rpc/read-token.js +107 -0
  156. package/dist/rpc/read-token.js.map +1 -0
  157. package/dist/rpc/repo-access.d.ts +36 -0
  158. package/dist/rpc/repo-access.js +75 -0
  159. package/dist/rpc/repo-access.js.map +1 -0
  160. package/dist/rpc/sync-attempt.d.ts +23 -0
  161. package/dist/rpc/sync-attempt.js +105 -0
  162. package/dist/rpc/sync-attempt.js.map +1 -0
  163. package/dist/sync-workflow-schemas-DCNmNE5-.d.ts +57 -0
  164. package/dist/upstream-DvqMCj5N.d.ts +15 -0
  165. package/dist/workflow-starter-BqhwX6oA.d.ts +45 -0
  166. package/dist/workflows/commit-workflow-schemas.d.ts +2 -0
  167. package/dist/workflows/commit-workflow-schemas.js +84 -0
  168. package/dist/workflows/commit-workflow-schemas.js.map +1 -0
  169. package/dist/workflows/commit-workflow.d.ts +16 -0
  170. package/dist/workflows/commit-workflow.js +22 -0
  171. package/dist/workflows/commit-workflow.js.map +1 -0
  172. package/dist/workflows/on-push.d.ts +2 -0
  173. package/dist/workflows/on-push.js +90 -0
  174. package/dist/workflows/on-push.js.map +1 -0
  175. package/dist/workflows/push-event.d.ts +2 -0
  176. package/dist/workflows/push-event.js +28 -0
  177. package/dist/workflows/push-event.js.map +1 -0
  178. package/dist/workflows/run-commit-workflow.d.ts +15 -0
  179. package/dist/workflows/run-commit-workflow.js +49 -0
  180. package/dist/workflows/run-commit-workflow.js.map +1 -0
  181. package/dist/workflows/run-sync-workflow.d.ts +14 -0
  182. package/dist/workflows/run-sync-workflow.js +67 -0
  183. package/dist/workflows/run-sync-workflow.js.map +1 -0
  184. package/dist/workflows/step-errors.d.ts +15 -0
  185. package/dist/workflows/step-errors.js +24 -0
  186. package/dist/workflows/step-errors.js.map +1 -0
  187. package/dist/workflows/step-runner.d.ts +31 -0
  188. package/dist/workflows/step-runner.js +6 -0
  189. package/dist/workflows/step-runner.js.map +1 -0
  190. package/dist/workflows/sync-branch-workflow.d.ts +15 -0
  191. package/dist/workflows/sync-branch-workflow.js +21 -0
  192. package/dist/workflows/sync-branch-workflow.js.map +1 -0
  193. package/dist/workflows/sync-workflow-schemas.d.ts +2 -0
  194. package/dist/workflows/sync-workflow-schemas.js +104 -0
  195. package/dist/workflows/sync-workflow-schemas.js.map +1 -0
  196. package/dist/workflows/workflow-instance-id.d.ts +12 -0
  197. package/dist/workflows/workflow-instance-id.js +33 -0
  198. package/dist/workflows/workflow-instance-id.js.map +1 -0
  199. package/dist/workflows/workflow-runtime.d.ts +7 -0
  200. package/dist/workflows/workflow-runtime.js +11 -0
  201. package/dist/workflows/workflow-runtime.js.map +1 -0
  202. package/dist/workflows/workflow-starter.d.ts +2 -0
  203. package/dist/workflows/workflow-starter.js +40 -0
  204. package/dist/workflows/workflow-starter.js.map +1 -0
  205. package/package.json +381 -4
  206. package/src/audit/audit-recorder.ts +74 -0
  207. package/src/audit/push-report.ts +60 -0
  208. package/src/auth/authenticate.ts +68 -0
  209. package/src/auth/authorize.ts +57 -0
  210. package/src/auth/read-token-auth.ts +119 -0
  211. package/src/cache/decision-cache.ts +57 -0
  212. package/src/gateway-app.ts +147 -0
  213. package/src/gateway-worker.ts +32 -0
  214. package/src/health.ts +12 -0
  215. package/src/logging/logger.ts +40 -0
  216. package/src/policy/branch-policy.ts +119 -0
  217. package/src/policy/enforce-branch-policy.ts +213 -0
  218. package/src/policy/fast-forward.ts +136 -0
  219. package/src/policy/ref-pattern.ts +24 -0
  220. package/src/policy/rule-branch-policy.ts +76 -0
  221. package/src/proxy/defer.ts +18 -0
  222. package/src/proxy/forward-read.ts +52 -0
  223. package/src/proxy/gateway-deps.ts +43 -0
  224. package/src/proxy/gateway-env.ts +43 -0
  225. package/src/proxy/git-responses.ts +89 -0
  226. package/src/proxy/git-route.ts +49 -0
  227. package/src/proxy/push-events.ts +91 -0
  228. package/src/proxy/push-guard.ts +109 -0
  229. package/src/proxy/push-options.ts +38 -0
  230. package/src/proxy/receive-pack.ts +257 -0
  231. package/src/proxy/request-log.ts +44 -0
  232. package/src/proxy/resolve-route.ts +24 -0
  233. package/src/proxy/upstream-call.ts +71 -0
  234. package/src/proxy/upstream.ts +76 -0
  235. package/src/push-policy/changed-paths.ts +143 -0
  236. package/src/push-policy/pushed-objects.ts +88 -0
  237. package/src/push-policy/run-push-policy.ts +99 -0
  238. package/src/push-policy/tree-diff.ts +107 -0
  239. package/src/push-policy/uncheckable.ts +27 -0
  240. package/src/rpc/branch-methods.ts +57 -0
  241. package/src/rpc/commit-attempt.ts +87 -0
  242. package/src/rpc/commit-graph.ts +44 -0
  243. package/src/rpc/commit-method.ts +36 -0
  244. package/src/rpc/commit-source.ts +15 -0
  245. package/src/rpc/gateway-context.ts +77 -0
  246. package/src/rpc/gateway-rpc.ts +65 -0
  247. package/src/rpc/gateway-service.ts +85 -0
  248. package/src/rpc/history-page.ts +163 -0
  249. package/src/rpc/lifecycle-methods.ts +50 -0
  250. package/src/rpc/paint-down.ts +120 -0
  251. package/src/rpc/promote-attempt.ts +52 -0
  252. package/src/rpc/push-ref.ts +54 -0
  253. package/src/rpc/read-methods.ts +111 -0
  254. package/src/rpc/read-token.ts +135 -0
  255. package/src/rpc/repo-access.ts +112 -0
  256. package/src/rpc/sync-attempt.ts +84 -0
  257. package/src/workflows/commit-workflow-schemas.ts +95 -0
  258. package/src/workflows/commit-workflow.ts +39 -0
  259. package/src/workflows/on-push.ts +128 -0
  260. package/src/workflows/push-event.ts +41 -0
  261. package/src/workflows/run-commit-workflow.ts +45 -0
  262. package/src/workflows/run-sync-workflow.ts +52 -0
  263. package/src/workflows/step-errors.ts +26 -0
  264. package/src/workflows/step-runner.ts +36 -0
  265. package/src/workflows/sync-branch-workflow.ts +40 -0
  266. package/src/workflows/sync-workflow-schemas.ts +122 -0
  267. package/src/workflows/workflow-instance-id.ts +26 -0
  268. package/src/workflows/workflow-runtime.ts +13 -0
  269. package/src/workflows/workflow-starter.ts +69 -0
@@ -0,0 +1,60 @@
1
+ import { Principal, PrincipalInput } from "@leed-ai/git-gateway-contract/proxy/principal";
2
+ import { Authenticator, Authorizer } from "@leed-ai/git-gateway-contract/proxy/gateway-hooks";
3
+ /**
4
+ * Every principal established from a read token has a subject starting with this prefix
5
+ * (`read-token:<jti>`). {@link withReadTokens} refuses any other authenticator's principal that
6
+ * claims it, so the subject cannot be forged by a deployment's own credentials.
7
+ */
8
+ export declare const READ_TOKEN_SUBJECT_PREFIX = "read-token:";
9
+ /** The role a read token grants: read access to `repo` and nothing else. */
10
+ export declare function readTokenRole(repo: string): string;
11
+ /** Whether a principal was established from a read token. */
12
+ export declare function isReadTokenPrincipal(principal: Pick<Principal, 'subject'>): boolean;
13
+ /** Options of {@link ReadTokenAuthenticator}. */
14
+ export interface ReadTokenAuthenticatorOptions {
15
+ /** The HMAC key mintReadToken() signs with (the RPC service's `readTokenSecret`). */
16
+ readonly secret: string;
17
+ /** The clock tokens are checked against; default the system clock. */
18
+ readonly now?: () => Date;
19
+ }
20
+ /**
21
+ * Accepts the read tokens mintReadToken() issues (`ggr_…`), sent as the HTTP Basic password (any
22
+ * username) or as a Bearer token. A valid token becomes a principal with subject
23
+ * `read-token:<jti>`, the single role `read:<repo>` and `expiresAt` the token's expiry; anything
24
+ * else — another kind of credential, a forged, expired or malformed token — is null. It grants
25
+ * nothing by itself: pair it with {@link readTokenAuthorizer}, or use {@link withReadTokens}, which
26
+ * composes both with a deployment's own authenticator and authorizer.
27
+ */
28
+ export declare class ReadTokenAuthenticator implements Authenticator {
29
+ #private;
30
+ constructor(options: ReadTokenAuthenticatorOptions);
31
+ authenticate(request: Request): Promise<PrincipalInput | null>;
32
+ }
33
+ /**
34
+ * An authorizer for read-token principals: one may read (clone, fetch) the repository its token
35
+ * names and nothing else — never push, never another repository. Every other principal is
36
+ * decided by `fallback`. Use it only behind an authenticator that keeps other principals out of
37
+ * the `read-token:` subject namespace, as {@link withReadTokens} does.
38
+ */
39
+ export declare function readTokenAuthorizer(fallback: Authorizer): Authorizer;
40
+ /** Options of {@link withReadTokens}. */
41
+ export interface WithReadTokensOptions extends ReadTokenAuthenticatorOptions {
42
+ /** The deployment's own authenticator, asked about every credential that is not a read token. */
43
+ readonly authenticator: Authenticator;
44
+ /** The deployment's own authorizer, asked about every principal not established from a read token. */
45
+ readonly authorizer: Authorizer;
46
+ }
47
+ /**
48
+ * Chains read tokens in front of a deployment's own authentication: a `ggr_` credential is checked
49
+ * by {@link ReadTokenAuthenticator} alone (an invalid one is refused, never handed on), any other
50
+ * credential goes to `authenticator`, whose principals may not use the `read-token:` subject
51
+ * prefix (such a principal is refused). The returned authorizer limits read-token principals to
52
+ * reading their one repository and leaves every other decision to `authorizer`. Pass both results
53
+ * to createGatewayApp, and the RPC service's `readTokenSecret` as `secret`, so a token from
54
+ * mintReadToken() clones `remoteUrl`.
55
+ */
56
+ export declare function withReadTokens(options: WithReadTokensOptions): {
57
+ readonly authenticator: Authenticator;
58
+ readonly authorizer: Authorizer;
59
+ };
60
+ //# sourceMappingURL=read-token-auth.d.ts.map
@@ -0,0 +1,83 @@
1
+ import { ReadTokenSecret, verifyReadToken } from "../rpc/read-token.js";
2
+ import { readCredential } from "@leed-ai/git-gateway-contract/proxy/request-credential";
3
+ // src/auth/read-token-auth.ts
4
+ /**
5
+ * Every principal established from a read token has a subject starting with this prefix
6
+ * (`read-token:<jti>`). {@link withReadTokens} refuses any other authenticator's principal that
7
+ * claims it, so the subject cannot be forged by a deployment's own credentials.
8
+ */
9
+ const READ_TOKEN_SUBJECT_PREFIX = "read-token:";
10
+ /** The role a read token grants: read access to `repo` and nothing else. */
11
+ function readTokenRole(repo) {
12
+ return `read:${repo}`;
13
+ }
14
+ /** Whether a principal was established from a read token. */
15
+ function isReadTokenPrincipal(principal) {
16
+ return principal.subject.startsWith(READ_TOKEN_SUBJECT_PREFIX);
17
+ }
18
+ /**
19
+ * Accepts the read tokens mintReadToken() issues (`ggr_…`), sent as the HTTP Basic password (any
20
+ * username) or as a Bearer token. A valid token becomes a principal with subject
21
+ * `read-token:<jti>`, the single role `read:<repo>` and `expiresAt` the token's expiry; anything
22
+ * else — another kind of credential, a forged, expired or malformed token — is null. It grants
23
+ * nothing by itself: pair it with {@link readTokenAuthorizer}, or use {@link withReadTokens}, which
24
+ * composes both with a deployment's own authenticator and authorizer.
25
+ */
26
+ var ReadTokenAuthenticator = class {
27
+ #secret;
28
+ #now;
29
+ constructor(options) {
30
+ this.#secret = ReadTokenSecret.parse(options.secret);
31
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
32
+ }
33
+ async authenticate(request) {
34
+ const credential = readCredential(request);
35
+ if (credential === null || !credential.secret.startsWith("ggr_")) return null;
36
+ const claims = await verifyReadToken(credential.secret, this.#secret, this.#now());
37
+ if (claims === null) return null;
38
+ return {
39
+ subject: `${READ_TOKEN_SUBJECT_PREFIX}${claims.jti}`,
40
+ name: null,
41
+ email: null,
42
+ roles: [readTokenRole(claims.repo)],
43
+ expiresAt: (/* @__PURE__ */ new Date(claims.exp * 1e3)).toISOString()
44
+ };
45
+ }
46
+ };
47
+ /**
48
+ * An authorizer for read-token principals: one may read (clone, fetch) the repository its token
49
+ * names and nothing else — never push, never another repository. Every other principal is
50
+ * decided by `fallback`. Use it only behind an authenticator that keeps other principals out of
51
+ * the `read-token:` subject namespace, as {@link withReadTokens} does.
52
+ */
53
+ function readTokenAuthorizer(fallback) {
54
+ return { authorize: async (principal, repo, operation) => {
55
+ if (!isReadTokenPrincipal(principal)) return fallback.authorize(principal, repo, operation);
56
+ return operation === "read" && principal.roles.length === 1 && principal.roles[0] === readTokenRole(repo);
57
+ } };
58
+ }
59
+ /**
60
+ * Chains read tokens in front of a deployment's own authentication: a `ggr_` credential is checked
61
+ * by {@link ReadTokenAuthenticator} alone (an invalid one is refused, never handed on), any other
62
+ * credential goes to `authenticator`, whose principals may not use the `read-token:` subject
63
+ * prefix (such a principal is refused). The returned authorizer limits read-token principals to
64
+ * reading their one repository and leaves every other decision to `authorizer`. Pass both results
65
+ * to createGatewayApp, and the RPC service's `readTokenSecret` as `secret`, so a token from
66
+ * mintReadToken() clones `remoteUrl`.
67
+ */
68
+ function withReadTokens(options) {
69
+ const readTokens = new ReadTokenAuthenticator(options);
70
+ const own = options.authenticator;
71
+ return {
72
+ authenticator: { authenticate: async (request) => {
73
+ if (readCredential(request)?.secret.startsWith("ggr_") === true) return readTokens.authenticate(request);
74
+ const principal = await own.authenticate(request);
75
+ if (principal === null) return null;
76
+ return principal.subject.startsWith("read-token:") ? null : principal;
77
+ } },
78
+ authorizer: readTokenAuthorizer(options.authorizer)
79
+ };
80
+ }
81
+ export { READ_TOKEN_SUBJECT_PREFIX, ReadTokenAuthenticator, isReadTokenPrincipal, readTokenAuthorizer, readTokenRole, withReadTokens };
82
+
83
+ //# sourceMappingURL=read-token-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read-token-auth.js","names":[],"sources":["../../src/auth/read-token-auth.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type { Authenticator, Authorizer } from '@leed-ai/git-gateway-contract/proxy/gateway-hooks';\nimport type { Principal, PrincipalInput } from '@leed-ai/git-gateway-contract/proxy/principal';\nimport { readCredential } from '@leed-ai/git-gateway-contract/proxy/request-credential';\nimport type { RepoName } from '@leed-ai/git-gateway-contract/schemas/names';\n\nimport { READ_TOKEN_PREFIX, ReadTokenSecret, verifyReadToken } from '../rpc/read-token.ts';\n\n/**\n * Every principal established from a read token has a subject starting with this prefix\n * (`read-token:<jti>`). {@link withReadTokens} refuses any other authenticator's principal that\n * claims it, so the subject cannot be forged by a deployment's own credentials.\n */\nexport const READ_TOKEN_SUBJECT_PREFIX = 'read-token:';\n\n/** The role a read token grants: read access to `repo` and nothing else. */\nexport function readTokenRole(repo: string): string {\n return `read:${repo}`;\n}\n\n/** Whether a principal was established from a read token. */\nexport function isReadTokenPrincipal(principal: Pick<Principal, 'subject'>): boolean {\n return principal.subject.startsWith(READ_TOKEN_SUBJECT_PREFIX);\n}\n\n/** Options of {@link ReadTokenAuthenticator}. */\nexport interface ReadTokenAuthenticatorOptions {\n /** The HMAC key mintReadToken() signs with (the RPC service's `readTokenSecret`). */\n readonly secret: string;\n /** The clock tokens are checked against; default the system clock. */\n readonly now?: () => Date;\n}\n\n/**\n * Accepts the read tokens mintReadToken() issues (`ggr_…`), sent as the HTTP Basic password (any\n * username) or as a Bearer token. A valid token becomes a principal with subject\n * `read-token:<jti>`, the single role `read:<repo>` and `expiresAt` the token's expiry; anything\n * else — another kind of credential, a forged, expired or malformed token — is null. It grants\n * nothing by itself: pair it with {@link readTokenAuthorizer}, or use {@link withReadTokens}, which\n * composes both with a deployment's own authenticator and authorizer.\n */\nexport class ReadTokenAuthenticator implements Authenticator {\n readonly #secret: string;\n readonly #now: () => Date;\n\n constructor(options: ReadTokenAuthenticatorOptions) {\n this.#secret = ReadTokenSecret.parse(options.secret);\n this.#now = options.now ?? (() => new Date());\n }\n\n async authenticate(request: Request): Promise<PrincipalInput | null> {\n const credential = readCredential(request);\n if (credential === null || !credential.secret.startsWith(READ_TOKEN_PREFIX)) return null;\n const claims = await verifyReadToken(credential.secret, this.#secret, this.#now());\n if (claims === null) return null;\n return {\n subject: `${READ_TOKEN_SUBJECT_PREFIX}${claims.jti}`,\n name: null,\n email: null,\n roles: [readTokenRole(claims.repo)],\n expiresAt: new Date(claims.exp * 1000).toISOString(),\n };\n }\n}\n\n/**\n * An authorizer for read-token principals: one may read (clone, fetch) the repository its token\n * names and nothing else — never push, never another repository. Every other principal is\n * decided by `fallback`. Use it only behind an authenticator that keeps other principals out of\n * the `read-token:` subject namespace, as {@link withReadTokens} does.\n */\nexport function readTokenAuthorizer(fallback: Authorizer): Authorizer {\n return {\n authorize: async (principal: Principal, repo: RepoName, operation) => {\n if (!isReadTokenPrincipal(principal)) return fallback.authorize(principal, repo, operation);\n return (\n operation === 'read' && principal.roles.length === 1 && principal.roles[0] === readTokenRole(repo)\n );\n },\n };\n}\n\n/** Options of {@link withReadTokens}. */\nexport interface WithReadTokensOptions extends ReadTokenAuthenticatorOptions {\n /** The deployment's own authenticator, asked about every credential that is not a read token. */\n readonly authenticator: Authenticator;\n /** The deployment's own authorizer, asked about every principal not established from a read token. */\n readonly authorizer: Authorizer;\n}\n\n/**\n * Chains read tokens in front of a deployment's own authentication: a `ggr_` credential is checked\n * by {@link ReadTokenAuthenticator} alone (an invalid one is refused, never handed on), any other\n * credential goes to `authenticator`, whose principals may not use the `read-token:` subject\n * prefix (such a principal is refused). The returned authorizer limits read-token principals to\n * reading their one repository and leaves every other decision to `authorizer`. Pass both results\n * to createGatewayApp, and the RPC service's `readTokenSecret` as `secret`, so a token from\n * mintReadToken() clones `remoteUrl`.\n */\nexport function withReadTokens(options: WithReadTokensOptions): {\n readonly authenticator: Authenticator;\n readonly authorizer: Authorizer;\n} {\n const readTokens = new ReadTokenAuthenticator(options);\n const own = options.authenticator;\n return {\n authenticator: {\n authenticate: async (request) => {\n const credential = readCredential(request);\n if (credential?.secret.startsWith(READ_TOKEN_PREFIX) === true)\n return readTokens.authenticate(request);\n const principal = await own.authenticate(request);\n if (principal === null) return null;\n return principal.subject.startsWith(READ_TOKEN_SUBJECT_PREFIX) ? null : principal;\n },\n },\n authorizer: readTokenAuthorizer(options.authorizer),\n };\n}\n"],"mappings":";;;;;;;;AAaA,MAAa,4BAA4B;;AAGzC,SAAgB,cAAc,MAAsB;CAClD,OAAO,QAAQ;AACjB;;AAGA,SAAgB,qBAAqB,WAAgD;CACnF,OAAO,UAAU,QAAQ,WAAW,yBAAyB;AAC/D;;;;;;;;;AAkBA,IAAa,yBAAb,MAA6D;CAC3D;CACA;CAEA,YAAY,SAAwC;EAClD,KAAK,UAAU,gBAAgB,MAAM,QAAQ,MAAM;EACnD,KAAK,OAAO,QAAQ,8BAAc,IAAI,KAAK;CAC7C;CAEA,MAAM,aAAa,SAAkD;EACnE,MAAM,aAAa,eAAe,OAAO;EACzC,IAAI,eAAe,QAAQ,CAAC,WAAW,OAAO,WAAA,MAA4B,GAAG,OAAO;EACpF,MAAM,SAAS,MAAM,gBAAgB,WAAW,QAAQ,KAAK,SAAS,KAAK,KAAK,CAAC;EACjF,IAAI,WAAW,MAAM,OAAO;EAC5B,OAAO;GACL,SAAS,GAAG,4BAA4B,OAAO;GAC/C,MAAM;GACN,OAAO;GACP,OAAO,CAAC,cAAc,OAAO,IAAI,CAAC;GAClC,4BAAW,IAAI,KAAK,OAAO,MAAM,GAAI,EAAA,CAAE,YAAY;EACrD;CACF;AACF;;;;;;;AAQA,SAAgB,oBAAoB,UAAkC;CACpE,OAAO,EACL,WAAW,OAAO,WAAsB,MAAgB,cAAc;EACpE,IAAI,CAAC,qBAAqB,SAAS,GAAG,OAAO,SAAS,UAAU,WAAW,MAAM,SAAS;EAC1F,OACE,cAAc,UAAU,UAAU,MAAM,WAAW,KAAK,UAAU,MAAM,OAAO,cAAc,IAAI;CAErG,EACF;AACF;;;;;;;;;;AAmBA,SAAgB,eAAe,SAG7B;CACA,MAAM,aAAa,IAAI,uBAAuB,OAAO;CACrD,MAAM,MAAM,QAAQ;CACpB,OAAO;EACL,eAAe,EACb,cAAc,OAAO,YAAY;GAE/B,IADmB,eAAe,OACrB,CAAC,EAAE,OAAO,WAAA,MAA4B,MAAM,MACvD,OAAO,WAAW,aAAa,OAAO;GACxC,MAAM,YAAY,MAAM,IAAI,aAAa,OAAO;GAChD,IAAI,cAAc,MAAM,OAAO;GAC/B,OAAO,UAAU,QAAQ,WAAA,aAAoC,IAAI,OAAO;EAC1E,EACF;EACA,YAAY,oBAAoB,QAAQ,UAAU;CACpD;AACF"}
@@ -0,0 +1,2 @@
1
+ import { n as DecisionCacheOptions, t as DecisionCache } from "../decision-cache-87U32iSj.js";
2
+ export { DecisionCache, DecisionCacheOptions };
@@ -0,0 +1,45 @@
1
+ // src/cache/decision-cache.ts
2
+ /**
3
+ * A small per-isolate cache of authentication and authorization decisions: each entry lives for
4
+ * its own TTL, and once full the least recently used entry is evicted. Keys are built by the
5
+ * caller from credential fingerprints and principal subjects — never from a credential itself.
6
+ */
7
+ var DecisionCache = class {
8
+ #entries = /* @__PURE__ */ new Map();
9
+ #maxEntries;
10
+ #now;
11
+ constructor(options) {
12
+ this.#maxEntries = options.maxEntries;
13
+ this.#now = options.now ?? Date.now;
14
+ }
15
+ /** How many entries are held (expired ones included until they are next touched). */
16
+ get size() {
17
+ return this.#entries.size;
18
+ }
19
+ /** The live value for `key`, or undefined when absent or expired. */
20
+ get(key) {
21
+ const entry = this.#entries.get(key);
22
+ if (entry === void 0) return void 0;
23
+ this.#entries.delete(key);
24
+ if (entry.expiresAt <= this.#now()) return void 0;
25
+ this.#entries.set(key, entry);
26
+ return entry.value;
27
+ }
28
+ /** Stores `value` for `ttlMs` milliseconds; a TTL of 0 or less stores nothing. */
29
+ set(key, value, ttlMs) {
30
+ if (this.#maxEntries === 0 || ttlMs <= 0) return;
31
+ this.#entries.delete(key);
32
+ this.#entries.set(key, {
33
+ value,
34
+ expiresAt: this.#now() + ttlMs
35
+ });
36
+ while (this.#entries.size > this.#maxEntries) {
37
+ const oldest = this.#entries.keys().next();
38
+ if (oldest.done === true) break;
39
+ this.#entries.delete(oldest.value);
40
+ }
41
+ }
42
+ };
43
+ export { DecisionCache };
44
+
45
+ //# sourceMappingURL=decision-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decision-cache.js","names":[],"sources":["../../src/cache/decision-cache.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\ninterface Entry<V> {\n readonly value: V;\n readonly expiresAt: number;\n}\n\n/** Options of a {@link DecisionCache}. */\nexport interface DecisionCacheOptions {\n /** Most entries held; the least recently used is evicted first. 0 disables the cache. */\n readonly maxEntries: number;\n /** The clock, in milliseconds since the epoch; default `Date.now`. */\n readonly now?: () => number;\n}\n\n/**\n * A small per-isolate cache of authentication and authorization decisions: each entry lives for\n * its own TTL, and once full the least recently used entry is evicted. Keys are built by the\n * caller from credential fingerprints and principal subjects — never from a credential itself.\n */\nexport class DecisionCache<V> {\n readonly #entries = new Map<string, Entry<V>>();\n readonly #maxEntries: number;\n readonly #now: () => number;\n\n constructor(options: DecisionCacheOptions) {\n this.#maxEntries = options.maxEntries;\n this.#now = options.now ?? Date.now;\n }\n\n /** How many entries are held (expired ones included until they are next touched). */\n get size(): number {\n return this.#entries.size;\n }\n\n /** The live value for `key`, or undefined when absent or expired. */\n get(key: string): V | undefined {\n const entry = this.#entries.get(key);\n if (entry === undefined) return undefined;\n this.#entries.delete(key);\n if (entry.expiresAt <= this.#now()) return undefined;\n this.#entries.set(key, entry);\n return entry.value;\n }\n\n /** Stores `value` for `ttlMs` milliseconds; a TTL of 0 or less stores nothing. */\n set(key: string, value: V, ttlMs: number): void {\n if (this.#maxEntries === 0 || ttlMs <= 0) return;\n this.#entries.delete(key);\n this.#entries.set(key, { value, expiresAt: this.#now() + ttlMs });\n while (this.#entries.size > this.#maxEntries) {\n const oldest = this.#entries.keys().next();\n if (oldest.done === true) break;\n this.#entries.delete(oldest.value);\n }\n }\n}\n"],"mappings":";;;;;;AAoBA,IAAa,gBAAb,MAA8B;CAC5B,2BAAoB,IAAI,IAAsB;CAC9C;CACA;CAEA,YAAY,SAA+B;EACzC,KAAK,cAAc,QAAQ;EAC3B,KAAK,OAAO,QAAQ,OAAO,KAAK;CAClC;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK,SAAS;CACvB;;CAGA,IAAI,KAA4B;EAC9B,MAAM,QAAQ,KAAK,SAAS,IAAI,GAAG;EACnC,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;EAChC,KAAK,SAAS,OAAO,GAAG;EACxB,IAAI,MAAM,aAAa,KAAK,KAAK,GAAG,OAAO,KAAA;EAC3C,KAAK,SAAS,IAAI,KAAK,KAAK;EAC5B,OAAO,MAAM;CACf;;CAGA,IAAI,KAAa,OAAU,OAAqB;EAC9C,IAAI,KAAK,gBAAgB,KAAK,SAAS,GAAG;EAC1C,KAAK,SAAS,OAAO,GAAG;EACxB,KAAK,SAAS,IAAI,KAAK;GAAE;GAAO,WAAW,KAAK,KAAK,IAAI;EAAM,CAAC;EAChE,OAAO,KAAK,SAAS,OAAO,KAAK,aAAa;GAC5C,MAAM,SAAS,KAAK,SAAS,KAAK,CAAC,CAAC,KAAK;GACzC,IAAI,OAAO,SAAS,MAAM;GAC1B,KAAK,SAAS,OAAO,OAAO,KAAK;EACnC;CACF;AACF"}
@@ -0,0 +1,95 @@
1
+ import { z } from "zod";
2
+ /** What a CommitWorkflow instance is started with: the commit() input, unchanged. */
3
+ declare const CommitWorkflowParams: z.ZodObject<{
4
+ repo: z.ZodString;
5
+ branch: z.ZodString;
6
+ startBranch: z.ZodOptional<z.ZodString>;
7
+ expectedHead: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
+ message: z.ZodString;
9
+ author: z.ZodObject<{
10
+ name: z.ZodString;
11
+ email: z.ZodEmail;
12
+ }, z.core.$strict>;
13
+ committer: z.ZodOptional<z.ZodObject<{
14
+ name: z.ZodString;
15
+ email: z.ZodEmail;
16
+ }, z.core.$strict>>;
17
+ actions: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
18
+ action: z.ZodLiteral<"create">;
19
+ path: z.ZodString;
20
+ content: z.ZodString;
21
+ encoding: z.ZodDefault<z.ZodEnum<{
22
+ base64: "base64";
23
+ text: "text";
24
+ }>>;
25
+ }, z.core.$strict>, z.ZodObject<{
26
+ action: z.ZodLiteral<"update">;
27
+ path: z.ZodString;
28
+ content: z.ZodString;
29
+ encoding: z.ZodDefault<z.ZodEnum<{
30
+ base64: "base64";
31
+ text: "text";
32
+ }>>;
33
+ }, z.core.$strict>, z.ZodObject<{
34
+ action: z.ZodLiteral<"upsert">;
35
+ path: z.ZodString;
36
+ content: z.ZodString;
37
+ encoding: z.ZodDefault<z.ZodEnum<{
38
+ base64: "base64";
39
+ text: "text";
40
+ }>>;
41
+ }, z.core.$strict>, z.ZodObject<{
42
+ action: z.ZodLiteral<"delete">;
43
+ path: z.ZodString;
44
+ }, z.core.$strict>, z.ZodObject<{
45
+ action: z.ZodLiteral<"move">;
46
+ path: z.ZodString;
47
+ previousPath: z.ZodString;
48
+ content: z.ZodOptional<z.ZodString>;
49
+ encoding: z.ZodDefault<z.ZodEnum<{
50
+ base64: "base64";
51
+ text: "text";
52
+ }>>;
53
+ }, z.core.$strict>, z.ZodObject<{
54
+ action: z.ZodLiteral<"chmod">;
55
+ path: z.ZodString;
56
+ executeFilemode: z.ZodBoolean;
57
+ }, z.core.$strict>], "action">>;
58
+ idempotencyKey: z.ZodString;
59
+ }, z.core.$strict>;
60
+ /** CommitWorkflow params after parsing (defaults applied). */
61
+ type CommitWorkflowParams = z.output<typeof CommitWorkflowParams>;
62
+ /** The workflow wrote the commit. */
63
+ declare const CommitStepCommitted: z.ZodObject<{
64
+ status: z.ZodLiteral<"committed">;
65
+ sha: z.ZodString;
66
+ }, z.core.$strict>;
67
+ /** A commit with the same idempotency key was already on the branch. */
68
+ declare const CommitStepReplayed: z.ZodObject<{
69
+ status: z.ZodLiteral<"replayed">;
70
+ sha: z.ZodString;
71
+ }, z.core.$strict>;
72
+ /** The actions changed nothing. */
73
+ declare const CommitStepNoop: z.ZodObject<{
74
+ status: z.ZodLiteral<"noop">;
75
+ head: z.ZodNullable<z.ZodString>;
76
+ }, z.core.$strict>;
77
+ /**
78
+ * What the CommitWorkflow's commit step stores and the instance returns. Ids and a status only:
79
+ * never file content, a message or a credential, because step results are persisted by the
80
+ * Workflows engine and shown in its dashboard.
81
+ */
82
+ declare const CommitStepResult: z.ZodDiscriminatedUnion<[z.ZodObject<{
83
+ status: z.ZodLiteral<"committed">;
84
+ sha: z.ZodString;
85
+ }, z.core.$strict>, z.ZodObject<{
86
+ status: z.ZodLiteral<"replayed">;
87
+ sha: z.ZodString;
88
+ }, z.core.$strict>, z.ZodObject<{
89
+ status: z.ZodLiteral<"noop">;
90
+ head: z.ZodNullable<z.ZodString>;
91
+ }, z.core.$strict>], "status">;
92
+ /** A CommitWorkflow result, inferred from {@link CommitStepResult}. */
93
+ type CommitStepResult = z.infer<typeof CommitStepResult>;
94
+ export { CommitWorkflowParams as a, CommitStepResult as i, CommitStepNoop as n, CommitStepReplayed as r, CommitStepCommitted as t };
95
+ //# sourceMappingURL=commit-workflow-schemas-BWlg7bZR.d.ts.map
@@ -0,0 +1,24 @@
1
+ /** Options of a {@link DecisionCache}. */
2
+ interface DecisionCacheOptions {
3
+ /** Most entries held; the least recently used is evicted first. 0 disables the cache. */
4
+ readonly maxEntries: number;
5
+ /** The clock, in milliseconds since the epoch; default `Date.now`. */
6
+ readonly now?: () => number;
7
+ }
8
+ /**
9
+ * A small per-isolate cache of authentication and authorization decisions: each entry lives for
10
+ * its own TTL, and once full the least recently used entry is evicted. Keys are built by the
11
+ * caller from credential fingerprints and principal subjects — never from a credential itself.
12
+ */
13
+ declare class DecisionCache<V> {
14
+ #private;
15
+ constructor(options: DecisionCacheOptions);
16
+ /** How many entries are held (expired ones included until they are next touched). */
17
+ get size(): number;
18
+ /** The live value for `key`, or undefined when absent or expired. */
19
+ get(key: string): V | undefined;
20
+ /** Stores `value` for `ttlMs` milliseconds; a TTL of 0 or less stores nothing. */
21
+ set(key: string, value: V, ttlMs: number): void;
22
+ }
23
+ export { DecisionCacheOptions as n, DecisionCache as t };
24
+ //# sourceMappingURL=decision-cache-87U32iSj.d.ts.map
@@ -0,0 +1,69 @@
1
+ import { r as Logger } from "./logger-BZ1zyKLb.js";
2
+ import { n as GatewayEnv } from "./gateway-env-DnsBU4Pq.js";
3
+ import { t as UpstreamFetch } from "./upstream-DvqMCj5N.js";
4
+ import { t as OnPushHook } from "./on-push-DTREOB__.js";
5
+ import { t as SyncBranchWorkflowParams } from "./sync-workflow-schemas-DCNmNE5-.js";
6
+ import { r as WorkflowStarter } from "./workflow-starter-BqhwX6oA.js";
7
+ import { SmartHttpConfigInput } from "@leed-ai/git-gateway-contract/proxy/smart-http-config";
8
+ import { GatewayConfigInput } from "@leed-ai/git-gateway-contract/schemas/gateway-config";
9
+ import { Hono } from "hono";
10
+ import { AuditHook, Authenticator, Authorizer, BranchPolicy, PushPolicy } from "@leed-ai/git-gateway-contract/proxy/gateway-hooks";
11
+ import { StorageBackend } from "@leed-ai/git-gateway-contract/storage/storage-backend";
12
+ /** What a deployment composes the gateway from. */
13
+ export interface GatewayAppOptions {
14
+ /** Where the repositories are stored; mints the per-request upstream credential. */
15
+ readonly backend: StorageBackend;
16
+ /** Establishes who each request acts for (e.g. `JwtAuthenticator`). */
17
+ readonly authenticator: Authenticator;
18
+ /** Decides read and write access per principal and repository. */
19
+ readonly authorizer: Authorizer;
20
+ /** Decides which refs a push may update (e.g. `RuleBranchPolicy`). */
21
+ readonly branchPolicy: BranchPolicy;
22
+ /**
23
+ * The deployment's own rules over what a push changes (paths, file types, sizes), run after the
24
+ * branch policy on every push it allows; optional. When it asks for changed paths the gateway
25
+ * reads the pushed pack as it streams, bounded by `smartHttp.maxPushPolicy*` and
26
+ * `maxChangedPaths`.
27
+ */
28
+ readonly pushPolicy?: PushPolicy;
29
+ /** Receives every authenticated operation; optional. */
30
+ readonly audit?: AuditHook;
31
+ /**
32
+ * Called after every push the storage host accepted through the proxy, with the refs its
33
+ * report-status marked "ok" (refused refs are left out; a push refused outright sends nothing),
34
+ * beside the sync rules, e.g. to send the event to a Queue. It runs after the response is under
35
+ * way (through `waitUntil`); a failure is logged, passed to {@link onPushError} and never
36
+ * changes the response.
37
+ */
38
+ readonly onPush?: OnPushHook;
39
+ /** Receives onPush failures after they are logged, e.g. to count them; default: nothing more. */
40
+ readonly onPushError?: (error: unknown) => void;
41
+ /**
42
+ * The SyncBranchWorkflow binding `gateway.syncRules` start instances of after every accepted
43
+ * push to a rule's `from` branch; required when there are sync rules.
44
+ */
45
+ readonly syncWorkflow?: WorkflowStarter<SyncBranchWorkflowParams>;
46
+ /** Structured logs; default none (pass `consoleLogger` in a Worker). */
47
+ readonly logger?: Logger;
48
+ /** Shared gateway settings; `authCacheSeconds` sets how long decisions are cached. */
49
+ readonly gateway?: GatewayConfigInput;
50
+ /** Smart-HTTP limits and the auth realm. */
51
+ readonly smartHttp?: SmartHttpConfigInput;
52
+ /** Name reported by GET /health; default "git-gateway". */
53
+ readonly serviceName?: string;
54
+ /** How requests reach the storage host; default the global `fetch`. */
55
+ readonly fetch?: UpstreamFetch;
56
+ /** The clock; default the system clock. */
57
+ readonly now?: () => Date;
58
+ }
59
+ /**
60
+ * The gateway as a Hono app: GET /health, and git smart HTTP at `/<repo>.git/info/refs`,
61
+ * `/<repo>.git/git-upload-pack` and `/<repo>.git/git-receive-pack`, each running route
62
+ * resolution → authentication → authorization (→ branch policy for pushes) as middleware before
63
+ * the request is proxied, streamed, to the storage host with a credential minted for it alone.
64
+ * Accepted pushes are delivered to the onPush hook and the sync rules after the response. Throws
65
+ * a TypeError when `gateway.syncRules` are set without a `syncWorkflow`. Create it once per
66
+ * isolate: it holds the decision cache.
67
+ */
68
+ export declare function createGatewayApp(options: GatewayAppOptions): Hono<GatewayEnv>;
69
+ //# sourceMappingURL=gateway-app.d.ts.map
@@ -0,0 +1,80 @@
1
+ import { AuditRecorder } from "./audit/audit-recorder.js";
2
+ import { authenticate } from "./auth/authenticate.js";
3
+ import { authorize } from "./auth/authorize.js";
4
+ import { DecisionCache } from "./cache/decision-cache.js";
5
+ import { healthRoutes } from "./health.js";
6
+ import { silentLogger } from "./logging/logger.js";
7
+ import { enforceBranchPolicy } from "./policy/enforce-branch-policy.js";
8
+ import { forwardRead } from "./proxy/forward-read.js";
9
+ import { textResponse } from "./proxy/git-responses.js";
10
+ import { receivePack } from "./proxy/receive-pack.js";
11
+ import { requestLog } from "./proxy/request-log.js";
12
+ import { resolveRoute } from "./proxy/resolve-route.js";
13
+ import { composeOnPush } from "./workflows/on-push.js";
14
+ import { SmartHttpConfig } from "@leed-ai/git-gateway-contract/proxy/smart-http-config";
15
+ import { GatewayConfig } from "@leed-ai/git-gateway-contract/schemas/gateway-config";
16
+ import { Hono } from "hono";
17
+ // src/gateway-app.ts
18
+ /**
19
+ * The gateway as a Hono app: GET /health, and git smart HTTP at `/<repo>.git/info/refs`,
20
+ * `/<repo>.git/git-upload-pack` and `/<repo>.git/git-receive-pack`, each running route
21
+ * resolution → authentication → authorization (→ branch policy for pushes) as middleware before
22
+ * the request is proxied, streamed, to the storage host with a credential minted for it alone.
23
+ * Accepted pushes are delivered to the onPush hook and the sync rules after the response. Throws
24
+ * a TypeError when `gateway.syncRules` are set without a `syncWorkflow`. Create it once per
25
+ * isolate: it holds the decision cache.
26
+ */
27
+ function createGatewayApp(options) {
28
+ const logger = options.logger ?? silentLogger;
29
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
30
+ const config = SmartHttpConfig.parse(options.smartHttp ?? {});
31
+ const gateway = GatewayConfig.parse(options.gateway ?? {});
32
+ const deps = {
33
+ backend: options.backend,
34
+ authenticator: options.authenticator,
35
+ authorizer: options.authorizer,
36
+ branchPolicy: options.branchPolicy,
37
+ pushPolicy: options.pushPolicy,
38
+ audit: new AuditRecorder(options.audit, logger, now),
39
+ logger,
40
+ cache: new DecisionCache({
41
+ maxEntries: config.decisionCacheEntries,
42
+ now: () => now().getTime()
43
+ }),
44
+ config,
45
+ cacheTtlMs: gateway.authCacheSeconds * 1e3,
46
+ fetch: options.fetch ?? (async (request) => fetch(request)),
47
+ now,
48
+ onPush: composeOnPush({
49
+ syncRules: gateway.syncRules,
50
+ syncWorkflow: options.syncWorkflow,
51
+ onPush: options.onPush
52
+ }),
53
+ onPushError: options.onPushError ?? (() => void 0)
54
+ };
55
+ const app = new Hono();
56
+ app.use("*", requestLog(logger, now));
57
+ app.route("/", healthRoutes(options.serviceName ?? "git-gateway"));
58
+ const git = new Hono();
59
+ const policy = enforceBranchPolicy(deps);
60
+ const read = forwardRead(deps);
61
+ const write = receivePack(deps);
62
+ git.use("*", resolveRoute(), authenticate(deps), authorize(deps));
63
+ git.use("*", async (context, next) => context.get("git").endpoint === "receive-pack" ? policy(context, next) : next());
64
+ git.all("*", async (context, next) => context.get("git").endpoint === "receive-pack" ? write(context, next) : read(context, next));
65
+ app.route("/", git);
66
+ app.notFound(() => textResponse(404, "Not found"));
67
+ app.onError((error, context) => {
68
+ logger.log({
69
+ level: "error",
70
+ message: "unhandled error",
71
+ requestId: context.get("requestId"),
72
+ error: error instanceof Error ? error.message : String(error)
73
+ });
74
+ return textResponse(500, "Internal error", { "X-Request-Id": context.get("requestId") });
75
+ });
76
+ return app;
77
+ }
78
+ export { createGatewayApp };
79
+
80
+ //# sourceMappingURL=gateway-app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway-app.js","names":[],"sources":["../src/gateway-app.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\nimport type {\n AuditHook,\n Authenticator,\n Authorizer,\n BranchPolicy,\n PushPolicy,\n} from '@leed-ai/git-gateway-contract/proxy/gateway-hooks';\nimport {\n SmartHttpConfig,\n type SmartHttpConfigInput,\n} from '@leed-ai/git-gateway-contract/proxy/smart-http-config';\nimport { GatewayConfig, type GatewayConfigInput } from '@leed-ai/git-gateway-contract/schemas/gateway-config';\nimport type { StorageBackend } from '@leed-ai/git-gateway-contract/storage/storage-backend';\nimport { Hono } from 'hono';\n\nimport { AuditRecorder } from './audit/audit-recorder.ts';\nimport { authenticate } from './auth/authenticate.ts';\nimport { authorize } from './auth/authorize.ts';\nimport { DecisionCache } from './cache/decision-cache.ts';\nimport { DEFAULT_SERVICE_NAME, healthRoutes } from './health.ts';\nimport { silentLogger, type Logger } from './logging/logger.ts';\nimport { enforceBranchPolicy } from './policy/enforce-branch-policy.ts';\nimport { forwardRead } from './proxy/forward-read.ts';\nimport type { CachedDecision, GatewayDeps } from './proxy/gateway-deps.ts';\nimport type { GatewayEnv } from './proxy/gateway-env.ts';\nimport { textResponse } from './proxy/git-responses.ts';\nimport { receivePack } from './proxy/receive-pack.ts';\nimport { requestLog } from './proxy/request-log.ts';\nimport { resolveRoute } from './proxy/resolve-route.ts';\nimport type { UpstreamFetch } from './proxy/upstream.ts';\nimport { composeOnPush, type OnPushHook } from './workflows/on-push.ts';\nimport type { SyncBranchWorkflowParams } from './workflows/sync-workflow-schemas.ts';\nimport type { WorkflowStarter } from './workflows/workflow-starter.ts';\n\n/** What a deployment composes the gateway from. */\nexport interface GatewayAppOptions {\n /** Where the repositories are stored; mints the per-request upstream credential. */\n readonly backend: StorageBackend;\n /** Establishes who each request acts for (e.g. `JwtAuthenticator`). */\n readonly authenticator: Authenticator;\n /** Decides read and write access per principal and repository. */\n readonly authorizer: Authorizer;\n /** Decides which refs a push may update (e.g. `RuleBranchPolicy`). */\n readonly branchPolicy: BranchPolicy;\n /**\n * The deployment's own rules over what a push changes (paths, file types, sizes), run after the\n * branch policy on every push it allows; optional. When it asks for changed paths the gateway\n * reads the pushed pack as it streams, bounded by `smartHttp.maxPushPolicy*` and\n * `maxChangedPaths`.\n */\n readonly pushPolicy?: PushPolicy;\n /** Receives every authenticated operation; optional. */\n readonly audit?: AuditHook;\n /**\n * Called after every push the storage host accepted through the proxy, with the refs its\n * report-status marked \"ok\" (refused refs are left out; a push refused outright sends nothing),\n * beside the sync rules, e.g. to send the event to a Queue. It runs after the response is under\n * way (through `waitUntil`); a failure is logged, passed to {@link onPushError} and never\n * changes the response.\n */\n readonly onPush?: OnPushHook;\n /** Receives onPush failures after they are logged, e.g. to count them; default: nothing more. */\n readonly onPushError?: (error: unknown) => void;\n /**\n * The SyncBranchWorkflow binding `gateway.syncRules` start instances of after every accepted\n * push to a rule's `from` branch; required when there are sync rules.\n */\n readonly syncWorkflow?: WorkflowStarter<SyncBranchWorkflowParams>;\n /** Structured logs; default none (pass `consoleLogger` in a Worker). */\n readonly logger?: Logger;\n /** Shared gateway settings; `authCacheSeconds` sets how long decisions are cached. */\n readonly gateway?: GatewayConfigInput;\n /** Smart-HTTP limits and the auth realm. */\n readonly smartHttp?: SmartHttpConfigInput;\n /** Name reported by GET /health; default \"git-gateway\". */\n readonly serviceName?: string;\n /** How requests reach the storage host; default the global `fetch`. */\n readonly fetch?: UpstreamFetch;\n /** The clock; default the system clock. */\n readonly now?: () => Date;\n}\n\n/**\n * The gateway as a Hono app: GET /health, and git smart HTTP at `/<repo>.git/info/refs`,\n * `/<repo>.git/git-upload-pack` and `/<repo>.git/git-receive-pack`, each running route\n * resolution → authentication → authorization (→ branch policy for pushes) as middleware before\n * the request is proxied, streamed, to the storage host with a credential minted for it alone.\n * Accepted pushes are delivered to the onPush hook and the sync rules after the response. Throws\n * a TypeError when `gateway.syncRules` are set without a `syncWorkflow`. Create it once per\n * isolate: it holds the decision cache.\n */\nexport function createGatewayApp(options: GatewayAppOptions): Hono<GatewayEnv> {\n const logger = options.logger ?? silentLogger;\n const now = options.now ?? (() => new Date());\n const config = SmartHttpConfig.parse(options.smartHttp ?? {});\n const gateway = GatewayConfig.parse(options.gateway ?? {});\n const deps: GatewayDeps = {\n backend: options.backend,\n authenticator: options.authenticator,\n authorizer: options.authorizer,\n branchPolicy: options.branchPolicy,\n pushPolicy: options.pushPolicy,\n audit: new AuditRecorder(options.audit, logger, now),\n logger,\n cache: new DecisionCache<CachedDecision>({\n maxEntries: config.decisionCacheEntries,\n now: () => now().getTime(),\n }),\n config,\n cacheTtlMs: gateway.authCacheSeconds * 1000,\n fetch: options.fetch ?? (async (request) => fetch(request)),\n now,\n onPush: composeOnPush({\n syncRules: gateway.syncRules,\n syncWorkflow: options.syncWorkflow,\n onPush: options.onPush,\n }),\n onPushError: options.onPushError ?? (() => undefined),\n };\n const app = new Hono<GatewayEnv>();\n app.use('*', requestLog(logger, now));\n app.route('/', healthRoutes(options.serviceName ?? DEFAULT_SERVICE_NAME));\n const git = new Hono<GatewayEnv>();\n const policy = enforceBranchPolicy(deps);\n const read = forwardRead(deps);\n const write = receivePack(deps);\n git.use('*', resolveRoute(), authenticate(deps), authorize(deps));\n git.use('*', async (context, next) =>\n context.get('git').endpoint === 'receive-pack' ? policy(context, next) : next(),\n );\n git.all('*', async (context, next) =>\n context.get('git').endpoint === 'receive-pack' ? write(context, next) : read(context, next),\n );\n app.route('/', git);\n app.notFound(() => textResponse(404, 'Not found'));\n app.onError((error, context) => {\n logger.log({\n level: 'error',\n message: 'unhandled error',\n requestId: context.get('requestId'),\n error: error instanceof Error ? error.message : String(error),\n });\n return textResponse(500, 'Internal error', { 'X-Request-Id': context.get('requestId') });\n });\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,SAAgB,iBAAiB,SAA8C;CAC7E,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,MAAM,QAAQ,8BAAc,IAAI,KAAK;CAC3C,MAAM,SAAS,gBAAgB,MAAM,QAAQ,aAAa,CAAC,CAAC;CAC5D,MAAM,UAAU,cAAc,MAAM,QAAQ,WAAW,CAAC,CAAC;CACzD,MAAM,OAAoB;EACxB,SAAS,QAAQ;EACjB,eAAe,QAAQ;EACvB,YAAY,QAAQ;EACpB,cAAc,QAAQ;EACtB,YAAY,QAAQ;EACpB,OAAO,IAAI,cAAc,QAAQ,OAAO,QAAQ,GAAG;EACnD;EACA,OAAO,IAAI,cAA8B;GACvC,YAAY,OAAO;GACnB,WAAW,IAAI,CAAC,CAAC,QAAQ;EAC3B,CAAC;EACD;EACA,YAAY,QAAQ,mBAAmB;EACvC,OAAO,QAAQ,UAAU,OAAO,YAAY,MAAM,OAAO;EACzD;EACA,QAAQ,cAAc;GACpB,WAAW,QAAQ;GACnB,cAAc,QAAQ;GACtB,QAAQ,QAAQ;EAClB,CAAC;EACD,aAAa,QAAQ,sBAAsB,KAAA;CAC7C;CACA,MAAM,MAAM,IAAI,KAAiB;CACjC,IAAI,IAAI,KAAK,WAAW,QAAQ,GAAG,CAAC;CACpC,IAAI,MAAM,KAAK,aAAa,QAAQ,eAAA,aAAmC,CAAC;CACxE,MAAM,MAAM,IAAI,KAAiB;CACjC,MAAM,SAAS,oBAAoB,IAAI;CACvC,MAAM,OAAO,YAAY,IAAI;CAC7B,MAAM,QAAQ,YAAY,IAAI;CAC9B,IAAI,IAAI,KAAK,aAAa,GAAG,aAAa,IAAI,GAAG,UAAU,IAAI,CAAC;CAChE,IAAI,IAAI,KAAK,OAAO,SAAS,SAC3B,QAAQ,IAAI,KAAK,CAAC,CAAC,aAAa,iBAAiB,OAAO,SAAS,IAAI,IAAI,KAAK,CAChF;CACA,IAAI,IAAI,KAAK,OAAO,SAAS,SAC3B,QAAQ,IAAI,KAAK,CAAC,CAAC,aAAa,iBAAiB,MAAM,SAAS,IAAI,IAAI,KAAK,SAAS,IAAI,CAC5F;CACA,IAAI,MAAM,KAAK,GAAG;CAClB,IAAI,eAAe,aAAa,KAAK,WAAW,CAAC;CACjD,IAAI,SAAS,OAAO,YAAY;EAC9B,OAAO,IAAI;GACT,OAAO;GACP,SAAS;GACT,WAAW,QAAQ,IAAI,WAAW;GAClC,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;EACD,OAAO,aAAa,KAAK,kBAAkB,EAAE,gBAAgB,QAAQ,IAAI,WAAW,EAAE,CAAC;CACzF,CAAC;CACD,OAAO;AACT"}
@@ -0,0 +1,54 @@
1
+ import { a as CommitWorkflowParams } from "./commit-workflow-schemas-BWlg7bZR.js";
2
+ import { t as OnPushHook } from "./on-push-DTREOB__.js";
3
+ import { t as SyncBranchWorkflowParams } from "./sync-workflow-schemas-DCNmNE5-.js";
4
+ import { r as WorkflowStarter } from "./workflow-starter-BqhwX6oA.js";
5
+ import { GatewayConfig, GatewayConfigInput } from "@leed-ai/git-gateway-contract/schemas/gateway-config";
6
+ import { FetchLike } from "@leed-ai/git-gateway-core/smart-http/git-http-client";
7
+ import { StorageBackend } from "@leed-ai/git-gateway-contract/storage/storage-backend";
8
+ /** How a deployment composes the RPC service and its Workflows. */
9
+ interface GatewayOptions {
10
+ /** Where the repositories live. */
11
+ readonly backend: StorageBackend;
12
+ /** Gateway configuration; every field has a default. */
13
+ readonly config?: GatewayConfigInput;
14
+ /** HMAC key read tokens are signed with (see {@link ReadTokenSecret}). */
15
+ readonly readTokenSecret: string;
16
+ /** How pushes reach the backend's git remote; default the global `fetch`. */
17
+ readonly fetch?: FetchLike;
18
+ /** The clock for commit dates, token expiry and the idempotency window; default the system clock. */
19
+ readonly now?: () => Date;
20
+ /** The CommitWorkflow binding commits are handed to when inline retries run out. */
21
+ readonly commitWorkflow?: WorkflowStarter<CommitWorkflowParams>;
22
+ /**
23
+ * The SyncBranchWorkflow binding `config.syncRules` start instances of after every ref update
24
+ * the RPC API pushes; required when there are sync rules.
25
+ */
26
+ readonly syncWorkflow?: WorkflowStarter<SyncBranchWorkflowParams>;
27
+ /**
28
+ * Called after every ref update the RPC API or its Workflows push (commits, syncs, promotions),
29
+ * beside the sync rules, e.g. to send the event to a Queue. The write has
30
+ * already happened, so a failure is reported to {@link onPushError} and does not fail the call.
31
+ */
32
+ readonly onPush?: OnPushHook;
33
+ /** Receives onPush failures, e.g. to log or count them; default: they are dropped. */
34
+ readonly onPushError?: (error: unknown) => void;
35
+ }
36
+ /** {@link GatewayOptions} validated, with defaults applied; what every method works with. */
37
+ interface GatewayContext {
38
+ readonly backend: StorageBackend;
39
+ readonly config: GatewayConfig;
40
+ readonly readTokenSecret: string;
41
+ readonly fetch: FetchLike | undefined;
42
+ readonly now: () => Date;
43
+ readonly commitWorkflow: WorkflowStarter<CommitWorkflowParams> | undefined;
44
+ /** The sync rules and the deployment's own hook, composed (see composeOnPush). */
45
+ readonly onPush: OnPushHook | undefined;
46
+ readonly onPushError: (error: unknown) => void;
47
+ }
48
+ /**
49
+ * Validates options (the configuration and the secret, with Zod) and applies the defaults. Throws
50
+ * a TypeError when sync rules are configured without a `syncWorkflow`.
51
+ */
52
+ declare function gatewayContext(options: GatewayOptions): GatewayContext;
53
+ export { GatewayOptions as n, gatewayContext as r, GatewayContext as t };
54
+ //# sourceMappingURL=gateway-context-Boh9I0mk.d.ts.map
@@ -0,0 +1,40 @@
1
+ import { t as GitRequest } from "./git-route-Spxi09Rm.js";
2
+ import { Principal } from "@leed-ai/git-gateway-contract/proxy/principal";
3
+ import { RefUpdate } from "@leed-ai/git-gateway-contract/schemas/ref-update";
4
+ import { ReceivePackRequest } from "@leed-ai/git-gateway-core/schemas/receive-pack";
5
+ /** A fast-forward-only update whose ancestry is proven only once the pushed pack has been scanned. */
6
+ interface PendingFastForward {
7
+ readonly update: RefUpdate;
8
+ /** The policy's reason, shown to the user if the update turns out not to be a fast-forward. */
9
+ readonly reason: string;
10
+ }
11
+ /** A push the branch policy let through, ready to forward. */
12
+ interface AllowedPush {
13
+ readonly request: ReceivePackRequest;
14
+ /** The whole request body from its first byte. */
15
+ readonly body: ReadableStream<Uint8Array>;
16
+ /** Where the pack starts in `body`. */
17
+ readonly headLength: number;
18
+ /** Updates still to be proven fast-forwards from the pack as it streams past. */
19
+ readonly pending: readonly PendingFastForward[];
20
+ /**
21
+ * Every update of the push, when the push policy is still to check them with changed paths
22
+ * computed from the pack; null when there is nothing left for it to check.
23
+ */
24
+ readonly policyUpdates: readonly RefUpdate[] | null;
25
+ }
26
+ /** The Hono environment of the gateway app: what each middleware leaves for the next. */
27
+ interface GatewayEnv {
28
+ Variables: {
29
+ /** Set first: the id of this request, also returned as X-Request-Id. */
30
+ requestId: string;
31
+ /** Set by route resolution: the repository and endpoint addressed. */
32
+ git: GitRequest;
33
+ /** Set by authentication. */
34
+ principal: Principal;
35
+ /** Set by the branch-policy middleware on a receive-pack request it lets through. */
36
+ push: AllowedPush;
37
+ };
38
+ }
39
+ export { GatewayEnv as n, PendingFastForward as r, AllowedPush as t };
40
+ //# sourceMappingURL=gateway-env-DnsBU4Pq.d.ts.map
@@ -0,0 +1,13 @@
1
+ import { GatewayAppOptions } from "./gateway-app.js";
2
+ /** The fetch handler a Worker module exports. */
3
+ export interface GatewayWorker<Env> {
4
+ fetch(request: Request, env: Env, context: ExecutionContext): Promise<Response>;
5
+ }
6
+ /**
7
+ * A Worker module's fetch handler that composes the gateway from its bindings: `setup` turns the
8
+ * environment into the app options (backend from `env.ARTIFACTS`, authenticator from JWKS
9
+ * settings, and so on). The app is built once per environment object, so the decision cache
10
+ * lives as long as the isolate.
11
+ */
12
+ export declare function createGatewayWorker<Env extends object>(setup: (env: Env) => GatewayAppOptions): GatewayWorker<Env>;
13
+ //# sourceMappingURL=gateway-worker.d.ts.map
@@ -0,0 +1,22 @@
1
+ import { createGatewayApp } from "./gateway-app.js";
2
+ // src/gateway-worker.ts
3
+ /**
4
+ * A Worker module's fetch handler that composes the gateway from its bindings: `setup` turns the
5
+ * environment into the app options (backend from `env.ARTIFACTS`, authenticator from JWKS
6
+ * settings, and so on). The app is built once per environment object, so the decision cache
7
+ * lives as long as the isolate.
8
+ */
9
+ function createGatewayWorker(setup) {
10
+ const apps = /* @__PURE__ */ new WeakMap();
11
+ return { async fetch(request, env, context) {
12
+ let app = apps.get(env);
13
+ if (app === void 0) {
14
+ app = createGatewayApp(setup(env));
15
+ apps.set(env, app);
16
+ }
17
+ return app.fetch(request, env, context);
18
+ } };
19
+ }
20
+ export { createGatewayWorker };
21
+
22
+ //# sourceMappingURL=gateway-worker.js.map