owenloop 0.5.0 → 0.5.2

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 (229) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +144 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +29 -4
  5. package/dist/packages/work/src/agent/brief.js +49 -4
  6. package/dist/packages/work/src/agent/capability-model.d.ts +123 -0
  7. package/dist/packages/work/src/agent/capability-model.js +148 -0
  8. package/dist/packages/work/src/agent/loop.d.ts +56 -7
  9. package/dist/packages/work/src/agent/loop.js +166 -9
  10. package/dist/packages/work/src/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +29 -1
  20. package/dist/packages/work/src/exec/loop.js +313 -35
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +84 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +30 -10
  38. package/dist/packages/work/src/harness/session-store.js +317 -89
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +134 -12
  41. package/dist/packages/work/src/hub/client.d.ts +8 -1
  42. package/dist/packages/work/src/hub/client.js +15 -1
  43. package/dist/packages/work/src/hub/types.d.ts +137 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +115 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +6 -0
  53. package/dist/packages/work/src/roles/hold.js +83 -13
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +19 -2
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +36 -2
  59. package/dist/packages/work/src/settings/settings.d.ts +70 -1
  60. package/dist/packages/work/src/settings/settings.js +90 -4
  61. package/dist/packages/work/src/shift/logretention.d.ts +253 -0
  62. package/dist/packages/work/src/shift/logretention.js +407 -0
  63. package/dist/packages/work/src/shift/logsink.d.ts +14 -0
  64. package/dist/packages/work/src/shift/logsink.js +98 -0
  65. package/dist/packages/work/src/shift/loop.d.ts +32 -4
  66. package/dist/packages/work/src/shift/loop.js +687 -166
  67. package/dist/packages/work/src/shift/protocol.d.ts +128 -1
  68. package/dist/packages/work/src/shift/protocol.js +14 -0
  69. package/dist/packages/work/src/shift/runtime.d.ts +16 -0
  70. package/dist/packages/work/src/shift/runtime.js +291 -5
  71. package/dist/packages/work/src/shift/server.d.ts +13 -0
  72. package/dist/packages/work/src/shift/server.js +61 -36
  73. package/dist/packages/work/src/shift/spawn.d.ts +115 -19
  74. package/dist/packages/work/src/shift/spawn.js +234 -30
  75. package/dist/packages/work/src/shift/state.d.ts +76 -49
  76. package/dist/packages/work/src/shift/state.js +350 -103
  77. package/dist/packages/work/src/shift/truncate.d.ts +35 -0
  78. package/dist/packages/work/src/shift/truncate.js +73 -0
  79. package/dist/packages/work/src/submit-proof.d.ts +61 -0
  80. package/dist/packages/work/src/submit-proof.js +119 -0
  81. package/dist/packages/work/src/submit-value.d.ts +48 -0
  82. package/dist/packages/work/src/submit-value.js +118 -0
  83. package/dist/packages/work/src/usage.d.ts +1 -1
  84. package/dist/packages/work/src/usage.js +11 -0
  85. package/dist/src/add.d.ts +64 -259
  86. package/dist/src/add.js +81 -615
  87. package/dist/src/archive.d.ts +97 -0
  88. package/dist/src/archive.js +591 -0
  89. package/dist/src/bundle/index.d.ts +64 -0
  90. package/dist/src/bundle/index.js +508 -0
  91. package/dist/src/bundle/manifest.d.ts +50 -0
  92. package/dist/src/bundle/manifest.js +435 -0
  93. package/dist/src/bundle/runtime.d.ts +26 -0
  94. package/dist/src/bundle/runtime.js +64 -0
  95. package/dist/src/bundle/tar.d.ts +62 -0
  96. package/dist/src/bundle/tar.js +238 -0
  97. package/dist/src/bundle/types.d.ts +105 -0
  98. package/dist/src/bundle/types.js +21 -0
  99. package/dist/src/capabilities.d.ts +93 -0
  100. package/dist/src/capabilities.js +101 -0
  101. package/dist/src/cli.d.ts +90 -20
  102. package/dist/src/cli.js +2421 -374
  103. package/dist/src/credentials.d.ts +4 -3
  104. package/dist/src/credentials.js +21 -19
  105. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  106. package/dist/src/crypto/allowed-signers.js +307 -0
  107. package/dist/src/crypto/canonical.d.ts +8 -0
  108. package/dist/src/crypto/canonical.js +92 -0
  109. package/dist/src/crypto/chain.d.ts +65 -0
  110. package/dist/src/crypto/chain.js +377 -0
  111. package/dist/src/crypto/dsse.d.ts +209 -0
  112. package/dist/src/crypto/dsse.js +282 -0
  113. package/dist/src/crypto/enrollment.d.ts +78 -0
  114. package/dist/src/crypto/enrollment.js +186 -0
  115. package/dist/src/crypto/index.d.ts +48 -0
  116. package/dist/src/crypto/index.js +44 -0
  117. package/dist/src/crypto/keys.d.ts +258 -0
  118. package/dist/src/crypto/keys.js +908 -0
  119. package/dist/src/crypto/org-root.d.ts +33 -0
  120. package/dist/src/crypto/org-root.js +78 -0
  121. package/dist/src/crypto/origin-rules.d.ts +56 -0
  122. package/dist/src/crypto/origin-rules.js +143 -0
  123. package/dist/src/crypto/policy-floor.d.ts +98 -0
  124. package/dist/src/crypto/policy-floor.js +353 -0
  125. package/dist/src/crypto/records.d.ts +319 -0
  126. package/dist/src/crypto/records.js +168 -0
  127. package/dist/src/crypto/scope.d.ts +49 -0
  128. package/dist/src/crypto/scope.js +83 -0
  129. package/dist/src/crypto/ssh.d.ts +171 -0
  130. package/dist/src/crypto/ssh.js +396 -0
  131. package/dist/src/crypto/submission.d.ts +33 -0
  132. package/dist/src/crypto/submission.js +47 -0
  133. package/dist/src/crypto/trust-roots.d.ts +29 -0
  134. package/dist/src/crypto/trust-roots.js +39 -0
  135. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  136. package/dist/src/crypto/verify-consumed.js +259 -0
  137. package/dist/src/crypto/verify-origin.d.ts +50 -0
  138. package/dist/src/crypto/verify-origin.js +151 -0
  139. package/dist/src/crypto/verify-publication.d.ts +60 -0
  140. package/dist/src/crypto/verify-publication.js +150 -0
  141. package/dist/src/defs.d.ts +24 -1
  142. package/dist/src/defs.js +335 -27
  143. package/dist/src/engine.d.ts +211 -6
  144. package/dist/src/engine.js +459 -59
  145. package/dist/src/factory.d.ts +16 -0
  146. package/dist/src/factory.js +16 -4
  147. package/dist/src/global-config.d.ts +59 -0
  148. package/dist/src/global-config.js +84 -0
  149. package/dist/src/hub.d.ts +102 -32
  150. package/dist/src/hub.js +147 -58
  151. package/dist/src/index.d.ts +19 -2
  152. package/dist/src/index.js +23 -2
  153. package/dist/src/install.d.ts +538 -0
  154. package/dist/src/install.js +1981 -0
  155. package/dist/src/lock.d.ts +15 -57
  156. package/dist/src/lock.js +251 -143
  157. package/dist/src/mcp/serve.d.ts +46 -22
  158. package/dist/src/mcp/serve.js +174 -44
  159. package/dist/src/mcp/server.js +12 -1
  160. package/dist/src/model.d.ts +51 -0
  161. package/dist/src/model.js +157 -1
  162. package/dist/src/order-resolver.d.ts +184 -0
  163. package/dist/src/order-resolver.js +252 -0
  164. package/dist/src/package-version.d.ts +10 -0
  165. package/dist/src/package-version.js +42 -0
  166. package/dist/src/paths.d.ts +14 -1
  167. package/dist/src/paths.js +18 -0
  168. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  169. package/dist/src/schemas/index.d.ts +1433 -0
  170. package/dist/src/schemas/index.js +31 -0
  171. package/dist/src/schemas/order.v1.schema.json +120 -0
  172. package/dist/src/schemas/origin.v1.schema.json +68 -0
  173. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  174. package/dist/src/schemas/publication.v1.schema.json +31 -0
  175. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  176. package/dist/src/schemas/submission.v1.schema.json +61 -0
  177. package/dist/src/store/def-source.d.ts +52 -0
  178. package/dist/src/store/def-source.js +335 -0
  179. package/dist/src/store/index-file.d.ts +69 -0
  180. package/dist/src/store/index-file.js +151 -0
  181. package/dist/src/store/index.d.ts +27 -0
  182. package/dist/src/store/index.js +22 -0
  183. package/dist/src/store/ingestor.d.ts +43 -0
  184. package/dist/src/store/ingestor.js +211 -0
  185. package/dist/src/store/install.d.ts +228 -0
  186. package/dist/src/store/install.js +555 -0
  187. package/dist/src/store/instruction-source.d.ts +49 -0
  188. package/dist/src/store/instruction-source.js +298 -0
  189. package/dist/src/store/origin-evidence.d.ts +21 -0
  190. package/dist/src/store/origin-evidence.js +66 -0
  191. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  192. package/dist/src/store/pre-commit-verifier.js +418 -0
  193. package/dist/src/store/resolve.d.ts +138 -0
  194. package/dist/src/store/resolve.js +363 -0
  195. package/dist/src/store/types.d.ts +288 -0
  196. package/dist/src/store/types.js +356 -0
  197. package/dist/src/store.d.ts +33 -1
  198. package/dist/src/store.js +57 -4
  199. package/dist/src/types.d.ts +146 -12
  200. package/dist/src/untar.d.ts +8 -23
  201. package/dist/src/untar.js +10 -136
  202. package/docs/agent-runner.md +86 -0
  203. package/docs/authoring.md +64 -6
  204. package/docs/bundles.md +350 -0
  205. package/docs/cli.md +1298 -106
  206. package/docs/crypto.md +832 -0
  207. package/docs/design.md +342 -20
  208. package/docs/embedding.md +132 -25
  209. package/docs/shift-logs.md +642 -0
  210. package/docs/wire-contracts.md +395 -0
  211. package/package.json +6 -1
  212. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  213. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  214. package/plugins/claude-code/plugin/.mcp.json +14 -0
  215. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  216. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  217. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  218. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  219. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  220. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  221. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  222. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  223. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  224. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  225. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  226. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  227. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  228. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  229. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -33,9 +33,10 @@ import type { Credential, CredentialSlotSelector, Keychain } from './hub.ts';
33
33
  export interface CredentialIO {
34
34
  env: Record<string, string | undefined>;
35
35
  /**
36
- * OS keychain backend for credential storage. `undefined` — non-mac, or
37
- * `OWENLOOP_NO_KEYCHAIN=1` — selects the file backend. A keychain write
38
- * failure is a hard error, never a silent file fallback (REL-6).
36
+ * OS Keychain backend. `OWENLOOP_NO_KEYCHAIN=1` excludes this backend from
37
+ * ordinary reads and writes, but defensive logout still inspects and clears
38
+ * an injected backend. A keychain write failure is a hard error, never a
39
+ * silent file fallback (REL-6).
39
40
  */
40
41
  keychain?: Keychain;
41
42
  /** Injectable for hermetic tests — the OAuth-refresh network calls use this. */
@@ -23,7 +23,7 @@
23
23
  * avoids an import cycle.
24
24
  */
25
25
  import { join } from 'node:path';
26
- import { asMintAgentTokenOk, asRekeyAgentTokenOk, configDir, credentialBackend, credentialFilePath, credentialSlot, externalCredentialCommand, keychainServiceFor, readCredentialFile, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, } from "./hub.js";
26
+ import { asMintAgentTokenOk, asRekeyAgentTokenOk, configDir, credentialBackend, credentialFilePath, credentialSlot, externalCredentialCommand, keychainServiceFor, readCredentialFile, readStoredCredential, resolveEndpoint, resolveLocalKeychain, writeCredentialFile, } from "./hub.js";
27
27
  import { CliError, nowMs } from "./util.js";
28
28
  import { acquireFileLock, FileLockTimeoutError, releaseFileLock } from "./lock.js";
29
29
  /**
@@ -33,7 +33,7 @@ import { acquireFileLock, FileLockTimeoutError, releaseFileLock } from "./lock.j
33
33
  * refreshed — adopt it").
34
34
  */
35
35
  const FRESH_WINDOW_MS = 60_000;
36
- // ---- the refresh/store lockfile --------------------------------------------
36
+ // ---- the refresh/store SQLite lock -----------------------------------------
37
37
  /** The credential lock path — sibling of `credentials.json` in the config dir. */
38
38
  function credLockPath(env) {
39
39
  return join(configDir(env), 'credentials.lock');
@@ -44,12 +44,10 @@ function envNum(env, key, fallback) {
44
44
  return Number.isFinite(n) && n > 0 ? n : fallback;
45
45
  }
46
46
  /**
47
- * Lock timings for the credential lock. Defaults 45s wait / 30s stale / 100ms
48
- * poll; each overridable via `OWENLOOP_CRED_LOCK_{WAIT,STALE,POLL}_MS`. The 30s
49
- * TTL is safe even against a slow live holder (a worst-case refresh — discovery
50
- * + token POST, each budgeted `HUB_TIMEOUT_MS` = 30s — can exceed it) because
51
- * `lockIsStale` never age-reclaims a lock whose recorded pid is alive; age only
52
- * governs an abandoned/unparseable lockfile.
47
+ * Lock timings for the credential lock. Defaults 45s wait / 100ms poll, each
48
+ * overridable via `OWENLOOP_CRED_LOCK_{WAIT,POLL}_MS`. The STALE knob remains in
49
+ * the options for source and environment compatibility, but SQLite connection
50
+ * ownership makes age-based pathname reclamation both unnecessary and unsafe.
53
51
  */
54
52
  function credLockOpts(env) {
55
53
  return {
@@ -62,11 +60,10 @@ function credLockOpts(env) {
62
60
  /**
63
61
  * Acquire the credential lock, mapping a clean acquire timeout to a loud
64
62
  * `CliError` — never falling through to an unlocked refresh (that would silently
65
- * reintroduce the double-refresh race). A real filesystem error from the
66
- * exclusive create (EACCES/EROFS) is NOT a timeout and propagates untouched. No
67
- * token value ever appears in the message (the lock payload is pid/host/
68
- * startedAt/token-only, and this message names neither the credential nor a
69
- * token).
63
+ * reintroduce the double-refresh race). A real filesystem or SQLite error
64
+ * (EACCES/EROFS/corruption) is NOT a timeout and propagates untouched. No token
65
+ * value ever appears in the message; the diagnostic sidecar contains only
66
+ * pid/host/timestamps plus a random acquisition token.
70
67
  */
71
68
  async function acquireCredLock(io) {
72
69
  try {
@@ -75,8 +72,11 @@ async function acquireCredLock(io) {
75
72
  catch (e) {
76
73
  if (e instanceof FileLockTimeoutError) {
77
74
  const who = e.holderPid !== undefined ? `pid ${e.holderPid}` : 'another process';
75
+ const legacyHelp = e.legacy
76
+ ? '; found a legacy lockfile that Owenloop will not delete automatically — verify that no old process owns it, then remove it manually'
77
+ : '';
78
78
  throw new CliError(`another owenloop process is using the credential store (${who}) — holds ${e.lockPath}; ` +
79
- `timed out waiting after ${Math.round(e.waitMs / 1000)}s`);
79
+ `timed out waiting after ${Math.round(e.waitMs / 1000)}s${legacyHelp}`);
80
80
  }
81
81
  throw e;
82
82
  }
@@ -148,15 +148,17 @@ export async function storeCredential(io, origin, slot, cred) {
148
148
  }
149
149
  /**
150
150
  * Delete body WITHOUT the lock — the caller holds it. Deletes the stored
151
- * credential for `(origin, slot)` from BOTH backends (a defensive dual-clear, so
152
- * a live refresh token can never be stranded in the store that wasn't the
153
- * currently-chosen one). Returns whether anything was removed. Only the NAMED
154
- * slot is removed.
151
+ * credential for `(origin, slot)` from BOTH locally available backends (a
152
+ * defensive dual-clear, so a live refresh token can never be stranded in the
153
+ * store that ordinary reads currently ignore). `OWENLOOP_NO_KEYCHAIN=1` selects
154
+ * the file for ordinary operations but does not hide an available Keychain from
155
+ * this cleanup path. Returns whether anything was removed. Only the NAMED slot
156
+ * is removed.
155
157
  */
156
158
  function deleteCredentialUnlocked(io, origin, slot) {
157
159
  const account = credentialSlot(slot);
158
160
  let removed = false;
159
- const kc = resolveKeychain(io.env, io.keychain);
161
+ const kc = resolveLocalKeychain(io.keychain);
160
162
  const service = keychainServiceFor(origin);
161
163
  if (kc && kc.get(service, account) !== null) {
162
164
  kc.delete(service, account);
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Parser for the stock OpenSSH `allowed_signers` file format (ssh-keygen(1)
3
+ * SSH SIGNATURES). The parser is STRUCTURAL only: it extracts principals,
4
+ * options, key type, key blob, and trailing comment with line numbers. It does
5
+ * NOT implement OpenSSH pattern matching, timestamp policy, certificate
6
+ * validation, or authorization — `ssh-keygen -Y verify` remains the policy
7
+ * authority (this repo's `SshSigner` delegates to it).
8
+ *
9
+ * Line structure:
10
+ *
11
+ * principals[,principal...] [options] keytype base64key [comment...]
12
+ *
13
+ * - principals: comma-separated pattern list (no spaces);
14
+ * - options (optional): one comma-separated `name` / `name="value"` field.
15
+ * Quoted values may contain commas, spaces, and `\"` / `\\` escapes.
16
+ * Recognized stock options: `cert-authority`, `namespaces=`, `valid-after=`,
17
+ * `valid-before=`. Principal/namespace pattern text is
18
+ * retained verbatim.
19
+ * - keytype: e.g. `ssh-ed25519`, `ssh-rsa`, `ecdsa-sha2-nistp256`;
20
+ * - base64key: the key blob, standard Base64;
21
+ * - comment: everything after the key blob (may contain spaces).
22
+ *
23
+ * Blank lines and full-line `#` comments are ignored; LF and CRLF both
24
+ * accepted. All parse errors carry their 1-indexed line number and never
25
+ * include secret material (the format carries only public keys).
26
+ */
27
+ /** Structured options recognized on an allowed_signers line. */
28
+ export interface AllowedSignerOptions {
29
+ /** `cert-authority` singleton. */
30
+ certAuthority: boolean;
31
+ /** `namespaces="a,b"` — retained pattern text, one entry per comma item. */
32
+ namespaces: string[] | undefined;
33
+ /** `valid-after="..."` — retained verbatim (no timestamp policy here). */
34
+ validAfter: string | undefined;
35
+ /** `valid-before="..."` — retained verbatim. */
36
+ validBefore: string | undefined;
37
+ }
38
+ /** One parsed allowed_signers entry. */
39
+ export interface AllowedSignerEntry {
40
+ /** The principal pattern list (split on unquoted commas). */
41
+ principals: string[];
42
+ options: AllowedSignerOptions;
43
+ keyType: string;
44
+ /** The raw Base64 key text as written in the file. */
45
+ keyBase64: string;
46
+ /** The decoded key blob. */
47
+ keyBlob: Buffer;
48
+ /** Trailing comment (may be empty). */
49
+ comment: string;
50
+ /** 1-indexed source line. */
51
+ line: number;
52
+ }
53
+ /** A line-numbered parse error. Non-secret by construction. */
54
+ export interface AllowedSignersParseError {
55
+ line: number;
56
+ message: string;
57
+ }
58
+ /** The parse result: every well-formed entry plus every error. */
59
+ export interface AllowedSignersFile {
60
+ entries: AllowedSignerEntry[];
61
+ errors: AllowedSignersParseError[];
62
+ }
63
+ /**
64
+ * Parse stock `allowed_signers` text. Returns every well-formed entry plus
65
+ * line-numbered errors for malformed lines; parsing never throws. Blank lines
66
+ * and full-line comments are skipped silently.
67
+ */
68
+ export declare function parseAllowedSigners(text: string): AllowedSignersFile;
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Parser for the stock OpenSSH `allowed_signers` file format (ssh-keygen(1)
3
+ * SSH SIGNATURES). The parser is STRUCTURAL only: it extracts principals,
4
+ * options, key type, key blob, and trailing comment with line numbers. It does
5
+ * NOT implement OpenSSH pattern matching, timestamp policy, certificate
6
+ * validation, or authorization — `ssh-keygen -Y verify` remains the policy
7
+ * authority (this repo's `SshSigner` delegates to it).
8
+ *
9
+ * Line structure:
10
+ *
11
+ * principals[,principal...] [options] keytype base64key [comment...]
12
+ *
13
+ * - principals: comma-separated pattern list (no spaces);
14
+ * - options (optional): one comma-separated `name` / `name="value"` field.
15
+ * Quoted values may contain commas, spaces, and `\"` / `\\` escapes.
16
+ * Recognized stock options: `cert-authority`, `namespaces=`, `valid-after=`,
17
+ * `valid-before=`. Principal/namespace pattern text is
18
+ * retained verbatim.
19
+ * - keytype: e.g. `ssh-ed25519`, `ssh-rsa`, `ecdsa-sha2-nistp256`;
20
+ * - base64key: the key blob, standard Base64;
21
+ * - comment: everything after the key blob (may contain spaces).
22
+ *
23
+ * Blank lines and full-line `#` comments are ignored; LF and CRLF both
24
+ * accepted. All parse errors carry their 1-indexed line number and never
25
+ * include secret material (the format carries only public keys).
26
+ */
27
+ /** Key types the parser recognizes syntactically (any stock type is accepted). */
28
+ const KEYTYPE_RE = /^(?:ssh-[a-z0-9@._+-]+|ecdsa-[a-z0-9@._+-]+|sk-[a-z0-9@._+-]+)$/i;
29
+ /** Singleton option names (no `=value`). */
30
+ const SINGLETON_OPTIONS = new Set(['cert-authority']);
31
+ /** Assignment option names (`name="value"`). */
32
+ const ASSIGN_OPTIONS = new Set(['namespaces', 'valid-after', 'valid-before']);
33
+ /** Split a single options field on commas outside quoted spans. */
34
+ function tokenizeOptions(text) {
35
+ const tokens = [];
36
+ let current = '';
37
+ let inQuotes = false;
38
+ for (let i = 0; i < text.length; i++) {
39
+ const ch = text[i];
40
+ if (ch === '\\') {
41
+ const next = text[i + 1];
42
+ if (next === undefined)
43
+ throw new Error('dangling escape in option value');
44
+ current += ch + next;
45
+ i += 1;
46
+ continue;
47
+ }
48
+ if (ch === '"')
49
+ inQuotes = !inQuotes;
50
+ if (ch === ',' && !inQuotes) {
51
+ // OpenSSH tolerates empty option slots between commas. A trailing comma
52
+ // is different: stock reports an unexpected end-of-options error.
53
+ tokens.push(current);
54
+ current = '';
55
+ continue;
56
+ }
57
+ current += ch;
58
+ }
59
+ if (inQuotes)
60
+ throw new Error('unterminated quoted option value');
61
+ if (current === '')
62
+ throw new Error('empty option');
63
+ tokens.push(current);
64
+ return tokens;
65
+ }
66
+ /** Split the principals field on commas (patterns carry no quoting). */
67
+ function splitPrincipals(text) {
68
+ return text.split(',').map((p) => p.trim()).filter((p) => p !== '');
69
+ }
70
+ /**
71
+ * Read the fields needed to identify one line, then treat the rest as opaque
72
+ * comment text. OpenSSH only applies quote rules to the optional options field;
73
+ * quotes in a trailing comment must never turn a valid line into a parse error.
74
+ */
75
+ function splitLineTokens(line) {
76
+ const tokens = [];
77
+ let offset = 0;
78
+ const skipWhitespace = () => {
79
+ while (offset < line.length && (line[offset] === ' ' || line[offset] === '\t'))
80
+ offset += 1;
81
+ };
82
+ const readToken = () => {
83
+ skipWhitespace();
84
+ if (offset >= line.length)
85
+ return '';
86
+ let token = '';
87
+ let inQuotes = false;
88
+ while (offset < line.length) {
89
+ const ch = line[offset];
90
+ if (ch === '\\' && inQuotes) {
91
+ const next = line[offset + 1];
92
+ if (next === undefined)
93
+ throw new Error('dangling escape in quoted token');
94
+ token += ch + next;
95
+ offset += 2;
96
+ continue;
97
+ }
98
+ if (ch === '"') {
99
+ inQuotes = !inQuotes;
100
+ token += ch;
101
+ offset += 1;
102
+ continue;
103
+ }
104
+ if (!inQuotes && (ch === ' ' || ch === '\t'))
105
+ break;
106
+ token += ch;
107
+ offset += 1;
108
+ }
109
+ if (inQuotes)
110
+ throw new Error('unterminated quoted option value');
111
+ return token;
112
+ };
113
+ const first = readToken();
114
+ if (first === '')
115
+ return tokens;
116
+ tokens.push(first);
117
+ const second = readToken();
118
+ if (second === '')
119
+ return tokens;
120
+ tokens.push(second);
121
+ // A bare line needs principals, key type, and key blob. An options line
122
+ // needs one additional field. Stop scanning immediately after the blob.
123
+ const requiredFields = KEYTYPE_RE.test(second) ? 3 : 4;
124
+ while (tokens.length < requiredFields) {
125
+ const before = offset;
126
+ const token = readToken();
127
+ if (token === '' && before === offset)
128
+ break;
129
+ tokens.push(token);
130
+ }
131
+ skipWhitespace();
132
+ if (offset < line.length)
133
+ tokens.push(line.slice(offset));
134
+ return tokens;
135
+ }
136
+ /** Decode only standard RFC 4648 Base64, which is what OpenSSH accepts. */
137
+ function decodeStandardBase64(text) {
138
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text) || text.length % 4 === 1)
139
+ throw new Error('bad base64');
140
+ const body = text.replace(/=+$/, '');
141
+ const expectedPadding = body.length % 4 === 0 ? 0 : 4 - (body.length % 4);
142
+ if (text.length - body.length !== expectedPadding)
143
+ throw new Error('bad base64 padding');
144
+ return Buffer.from(text, 'base64');
145
+ }
146
+ /** Parse and unescape one stock quoted assignment value. */
147
+ function parseQuotedValue(raw) {
148
+ if (!raw.startsWith('"') || !raw.endsWith('"'))
149
+ throw new Error('assignment value must be quoted');
150
+ let value = '';
151
+ for (let i = 1; i < raw.length - 1; i++) {
152
+ const ch = raw[i];
153
+ if (ch !== '\\') {
154
+ if (ch === '"')
155
+ throw new Error('unescaped quote in assignment value');
156
+ value += ch;
157
+ continue;
158
+ }
159
+ const next = raw[++i];
160
+ if (next !== '"' && next !== '\\')
161
+ throw new Error('unsupported escape in assignment value');
162
+ value += next;
163
+ }
164
+ return value;
165
+ }
166
+ /**
167
+ * Parse stock `allowed_signers` text. Returns every well-formed entry plus
168
+ * line-numbered errors for malformed lines; parsing never throws. Blank lines
169
+ * and full-line comments are skipped silently.
170
+ */
171
+ export function parseAllowedSigners(text) {
172
+ const entries = [];
173
+ const errors = [];
174
+ const lines = text.split(/\r?\n/);
175
+ for (let idx = 0; idx < lines.length; idx++) {
176
+ const lineNo = idx + 1;
177
+ const raw = lines[idx];
178
+ const trimmed = raw.trim();
179
+ if (trimmed === '' || trimmed.startsWith('#'))
180
+ continue;
181
+ const fail = (message) => {
182
+ errors.push({ line: lineNo, message });
183
+ return null;
184
+ };
185
+ let tokens;
186
+ try {
187
+ tokens = splitLineTokens(trimmed);
188
+ }
189
+ catch (e) {
190
+ fail(e.message);
191
+ continue;
192
+ }
193
+ if (tokens.length < 3) {
194
+ fail('missing fields: expected principals, key type, and base64 key');
195
+ continue;
196
+ }
197
+ const principals = splitPrincipals(tokens[0]);
198
+ if (principals.length === 0) {
199
+ fail('missing principals');
200
+ continue;
201
+ }
202
+ const options = {
203
+ certAuthority: false,
204
+ namespaces: undefined,
205
+ validAfter: undefined,
206
+ validBefore: undefined,
207
+ };
208
+ let keyIndex = 1;
209
+ if (!KEYTYPE_RE.test(tokens[1])) {
210
+ // Stock grammar has exactly one options field. If the next token is not
211
+ // the key type, whitespace-separated options are rejected rather than
212
+ // silently normalized into a different policy line.
213
+ if (tokens.length < 4 || KEYTYPE_RE.test(tokens[2])) {
214
+ // The branch with a key type at token 2 is the valid one-option form.
215
+ keyIndex = 2;
216
+ }
217
+ else {
218
+ fail('options must be one comma-separated field');
219
+ continue;
220
+ }
221
+ let optionTokens;
222
+ try {
223
+ optionTokens = tokenizeOptions(tokens[1]);
224
+ }
225
+ catch (e) {
226
+ fail(`options: ${e.message}`);
227
+ continue;
228
+ }
229
+ let optionError = null;
230
+ for (const rawOption of optionTokens) {
231
+ if (rawOption === '')
232
+ continue;
233
+ const eq = rawOption.indexOf('=');
234
+ const rawName = eq < 0 ? rawOption : rawOption.slice(0, eq);
235
+ const name = rawName.toLowerCase();
236
+ if (eq < 0) {
237
+ if (!SINGLETON_OPTIONS.has(name)) {
238
+ optionError = `unsupported option syntax: '${rawOption}'`;
239
+ break;
240
+ }
241
+ // OpenSSH accepts repeated cert-authority options. Preserve the
242
+ // boolean representation without treating repetition as a grammar error.
243
+ options.certAuthority = true;
244
+ continue;
245
+ }
246
+ if (!ASSIGN_OPTIONS.has(name)) {
247
+ optionError = `unsupported option syntax: '${rawOption}'`;
248
+ break;
249
+ }
250
+ let value;
251
+ try {
252
+ value = parseQuotedValue(rawOption.slice(eq + 1));
253
+ }
254
+ catch (e) {
255
+ optionError = `option '${name}': ${e.message}`;
256
+ break;
257
+ }
258
+ if (name === 'namespaces') {
259
+ if (options.namespaces !== undefined) {
260
+ optionError = 'duplicate option: namespaces';
261
+ break;
262
+ }
263
+ options.namespaces = value.split(',').map((s) => s.trim()).filter((s) => s !== '');
264
+ }
265
+ else if (name === 'valid-after') {
266
+ if (options.validAfter !== undefined) {
267
+ optionError = 'duplicate option: valid-after';
268
+ break;
269
+ }
270
+ options.validAfter = value;
271
+ }
272
+ else {
273
+ if (options.validBefore !== undefined) {
274
+ optionError = 'duplicate option: valid-before';
275
+ break;
276
+ }
277
+ options.validBefore = value;
278
+ }
279
+ }
280
+ if (optionError !== null) {
281
+ fail(optionError);
282
+ continue;
283
+ }
284
+ }
285
+ const keyType = tokens[keyIndex];
286
+ if (!KEYTYPE_RE.test(keyType)) {
287
+ fail(`invalid key type: '${keyType}'`);
288
+ continue;
289
+ }
290
+ if (keyIndex + 1 >= tokens.length) {
291
+ fail('missing base64 key');
292
+ continue;
293
+ }
294
+ const keyBase64 = tokens[keyIndex + 1];
295
+ let keyBlob;
296
+ try {
297
+ keyBlob = decodeStandardBase64(keyBase64);
298
+ }
299
+ catch {
300
+ fail('bad base64 key blob');
301
+ continue;
302
+ }
303
+ const comment = tokens.slice(keyIndex + 2).join(' ');
304
+ entries.push({ principals, options, keyType, keyBase64, keyBlob, comment, line: lineNo });
305
+ }
306
+ return { entries, errors };
307
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Serialize a JSON value deterministically for value-level trust records.
3
+ * Object keys are sorted recursively; array order is preserved. The output is
4
+ * separator-tight JSON encoded as UTF-8 bytes.
5
+ */
6
+ export declare function canonicalValueBytes(value: unknown): Uint8Array;
7
+ /** Compute the lowercase SHA-256 digest of a canonical JSON value. */
8
+ export declare function valueDigestHex(value: unknown): string;
@@ -0,0 +1,92 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * Serialize a JSON value deterministically for value-level trust records.
4
+ * Object keys are sorted recursively; array order is preserved. The output is
5
+ * separator-tight JSON encoded as UTF-8 bytes.
6
+ */
7
+ export function canonicalValueBytes(value) {
8
+ const json = canonicalValueJson(value);
9
+ if (json === undefined)
10
+ throw new TypeError('cannot canonicalize a value that serializes to undefined');
11
+ return new TextEncoder().encode(json);
12
+ }
13
+ /** Compute the lowercase SHA-256 digest of a canonical JSON value. */
14
+ export function valueDigestHex(value) {
15
+ return createHash('sha256').update(canonicalValueBytes(value)).digest('hex');
16
+ }
17
+ /**
18
+ * Apply the same `toJSON(key)` hook that JSON.stringify applies before a value
19
+ * crosses the submit transport. Objects without JSON-compatible prototypes are
20
+ * rejected instead of being treated as empty records.
21
+ */
22
+ function canonicalValueJson(value, key = '', stack = new Set(), position = 'root') {
23
+ if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
24
+ const toJSON = value.toJSON;
25
+ if (typeof toJSON === 'function') {
26
+ if (stack.has(value))
27
+ throw new TypeError('cannot canonicalize a circular value');
28
+ stack.add(value);
29
+ try {
30
+ const replacement = Reflect.apply(toJSON, value, [key]);
31
+ return canonicalValueJson(replacement, key, stack, position);
32
+ }
33
+ finally {
34
+ stack.delete(value);
35
+ }
36
+ }
37
+ }
38
+ if (value === null)
39
+ return 'null';
40
+ switch (typeof value) {
41
+ case 'string':
42
+ return JSON.stringify(value);
43
+ case 'boolean':
44
+ return value ? 'true' : 'false';
45
+ case 'number': {
46
+ if (!Number.isFinite(value))
47
+ throw new TypeError('cannot canonicalize a non-finite number');
48
+ return JSON.stringify(value);
49
+ }
50
+ case 'undefined':
51
+ case 'function':
52
+ case 'symbol':
53
+ if (position === 'object')
54
+ return undefined;
55
+ if (position === 'array')
56
+ return 'null';
57
+ throw new TypeError(`cannot canonicalize ${typeof value}`);
58
+ case 'bigint':
59
+ throw new TypeError('cannot canonicalize bigint');
60
+ case 'object':
61
+ break;
62
+ default:
63
+ throw new TypeError(`cannot canonicalize ${typeof value}`);
64
+ }
65
+ if (stack.has(value))
66
+ throw new TypeError('cannot canonicalize a circular value');
67
+ stack.add(value);
68
+ try {
69
+ if (Array.isArray(value)) {
70
+ const entries = [];
71
+ for (let index = 0; index < value.length; index += 1) {
72
+ entries.push(canonicalValueJson(value[index], String(index), stack, 'array') ?? 'null');
73
+ }
74
+ return `[${entries.join(',')}]`;
75
+ }
76
+ const prototype = Object.getPrototypeOf(value);
77
+ if (prototype !== Object.prototype && prototype !== null) {
78
+ throw new TypeError('cannot canonicalize a non-plain object without toJSON');
79
+ }
80
+ const object = value;
81
+ const entries = [];
82
+ for (const property of Object.keys(object).sort()) {
83
+ const serialized = canonicalValueJson(object[property], property, stack, 'object');
84
+ if (serialized !== undefined)
85
+ entries.push(`${JSON.stringify(property)}:${serialized}`);
86
+ }
87
+ return `{${entries.join(',')}}`;
88
+ }
89
+ finally {
90
+ stack.delete(value);
91
+ }
92
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Enrollment-chain verification for locally anchored principal keys.
3
+ *
4
+ * The validator consumes raw DSSE envelopes and an explicit validation instant.
5
+ * Each grant link is verified with a signer whose allowed-signers text contains
6
+ * exactly that link's parent key, so a remote roster assertion cannot substitute
7
+ * for the local org-root anchor. Scope attenuation and revocation authority are
8
+ * checked after schema decoding and cryptographic verification. This module is
9
+ * deliberately pure: it performs no filesystem or network I/O; org-root.ts
10
+ * supplies the optional on-disk loader for callers that need one.
11
+ */
12
+ import type { Signer } from './ssh.ts';
13
+ import type { GrantScope, PrincipalReference, RevocationRecord } from './records.ts';
14
+ /** Inputs to the pure enrollment-chain validator. */
15
+ export interface ChainInput {
16
+ targetKeyId: string;
17
+ orgRootPublicKey: string;
18
+ grants: Uint8Array[];
19
+ revocations?: Uint8Array[];
20
+ at: number;
21
+ }
22
+ /** Injectable cryptographic and policy options for chain verification. */
23
+ export interface ChainOptions {
24
+ signerForPrincipal?: (args: {
25
+ principal: string;
26
+ allowedSignersText: string;
27
+ }) => Pick<Signer, 'verify'> & {
28
+ dispose?: () => void;
29
+ };
30
+ /** SSHSIG namespace used by the DSSE envelopes. */
31
+ namespace?: string;
32
+ /** Maximum number of grant links before the walk is refused. */
33
+ maxChainDepth?: number;
34
+ /** Sink for the conspicuous, non-secret accepted-backdating note. */
35
+ onBackdatedRevocation?: (note: string) => void;
36
+ }
37
+ /** The three possible chain-validation decisions. */
38
+ export type ChainVerdict = {
39
+ kind: 'verified';
40
+ keyid: string;
41
+ principal: PrincipalReference;
42
+ effectiveScope: GrantScope;
43
+ depth: number;
44
+ } | {
45
+ kind: 'unverifiable';
46
+ reason: string;
47
+ } | {
48
+ kind: 'invalid';
49
+ reason: string;
50
+ };
51
+ /** The canonical cross-field revocation timestamp rule. */
52
+ export declare function revocationTemporalConsistency(record: RevocationRecord): boolean;
53
+ /**
54
+ * Validate that `targetKeyId` is rooted at the supplied org anchor, with all
55
+ * grant links attenuating scope and all effective revocations applied at `at`.
56
+ */
57
+ export declare function validateEnrollmentChain(input: ChainInput, options?: ChainOptions): Promise<ChainVerdict>;
58
+ /** Validate a chain first, then apply the requested producer scope demand. */
59
+ export declare function validateProducer(input: ChainInput & {
60
+ demand: {
61
+ pool?: string;
62
+ label?: string;
63
+ namespace?: string;
64
+ };
65
+ }, options?: ChainOptions): Promise<ChainVerdict>;