@agent-custody/receipts 0.16.5 → 0.16.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -13
- package/dist/capture.d.ts +2 -0
- package/dist/capture.js +13 -2
- package/dist/check.d.ts +1 -1
- package/dist/check.js +34 -10
- package/dist/cli.js +54 -9
- package/dist/config.d.ts +27 -2
- package/dist/config.js +66 -2
- package/dist/console-page.js +144 -50
- package/dist/deny-report.d.ts +7 -0
- package/dist/deny-report.js +8 -3
- package/dist/design.d.ts +11 -0
- package/dist/design.js +91 -0
- package/dist/door-app.d.ts +28 -0
- package/dist/door-app.js +244 -0
- package/dist/door-partner.d.ts +66 -0
- package/dist/door-partner.js +94 -0
- package/dist/door.d.ts +139 -10
- package/dist/door.js +297 -137
- package/dist/gateway-http.d.ts +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.js +5 -1
- package/dist/log-admin.js +100 -59
- package/dist/log-store.d.ts +8 -2
- package/dist/log-store.js +22 -12
- package/dist/perathos.d.ts +50 -0
- package/dist/perathos.js +188 -0
- package/dist/portal.d.ts +66 -5
- package/dist/portal.js +895 -242
- package/dist/receipt.d.ts +4 -1
- package/dist/session-audit.d.ts +46 -0
- package/dist/session-audit.js +150 -0
- package/dist/site-links.d.ts +23 -0
- package/dist/site-links.js +29 -0
- package/dist/verify.js +44 -4
- package/dist/web-bot-auth.d.ts +105 -0
- package/dist/web-bot-auth.js +508 -0
- package/docs/acs.md +2 -0
- package/docs/approvals.md +1 -1
- package/docs/completeness.md +1 -1
- package/docs/configuration.md +2 -0
- package/docs/console.md +11 -2
- package/docs/door-languages.md +168 -0
- package/docs/door-middleware.md +216 -0
- package/docs/door-quickstart.md +1 -1
- package/docs/door-signals.md +43 -6
- package/docs/door.md +129 -32
- package/docs/egress.md +3 -1
- package/docs/github-action.md +2 -2
- package/docs/mandates.md +1 -1
- package/docs/perathos.md +100 -0
- package/docs/sdk.md +32 -1
- package/docs/threat-model.md +2 -1
- package/docs/tutorials.md +6 -0
- package/docs/usage.md +3 -1
- package/docs/verification.md +3 -1
- package/package.json +7 -1
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/interop/perathos/LICENSE +21 -0
- package/vectors/interop/perathos/README.md +17 -0
- package/vectors/interop/perathos/pocketos-replay/session.head.json +11 -0
- package/vectors/interop/perathos/pocketos-replay/session.jsonl +8 -0
- package/vectors/interop/perathos/pocketos-replay/verification.json +65 -0
- package/vectors/receipts.json +1701 -1210
package/dist/gateway-http.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { type GatewayHost } from "./gateway.ts";
|
|
|
4
4
|
export declare const GRANT_HEADER = "x-agent-custody-grant";
|
|
5
5
|
/** The header value that presents a grant: the DSSE envelope as base64url JSON. Send it as `Authorization: Bearer <value>` or as `X-Agent-Custody-Grant`. */
|
|
6
6
|
export declare function grantHeader(envelope: Envelope): string;
|
|
7
|
-
export declare function parseGrantHeader(req: IncomingMessage): Envelope | null;
|
|
7
|
+
export declare function parseGrantHeader(req: Pick<IncomingMessage, "headers">): Envelope | null;
|
|
8
8
|
export interface HttpGatewayOptions {
|
|
9
9
|
port: number;
|
|
10
10
|
host?: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,8 @@ export { hecEvent, splunkExporter } from "./splunk.ts";
|
|
|
7
7
|
export { serveConsole, type ConsoleOptions, type RunningConsole } from "./console.ts";
|
|
8
8
|
export { checkConfig, formatFindings, type CheckFinding, type CheckOptions } from "./check.ts";
|
|
9
9
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
|
|
10
|
-
export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, verifyChallengeToken } from "./door.ts";
|
|
10
|
+
export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.ts";
|
|
11
|
+
export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.ts";
|
|
11
12
|
export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, createEgressHost, destinationName, normalizeHost, parseAuthority, publicOnlyLookup, serveEgress } from "./egress.ts";
|
|
12
13
|
export { internalAddress } from "./addresses.ts";
|
|
13
14
|
export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.ts";
|
|
@@ -15,9 +16,12 @@ export type { DraftAgent, DraftDestination, DraftSkip, EgressPolicyDraft } from
|
|
|
15
16
|
export type { Destination, EgressEnd, EgressHost, EgressOptions, EgressResult, EgressServerOptions, RunningEgress } from "./egress.ts";
|
|
16
17
|
export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP_FACT, ACS_VERSION, acsEntryHash, createAcsGuardian } from "./acs.ts";
|
|
17
18
|
export type { AcsGuardian, AcsMethod, AcsResponse } from "./acs.ts";
|
|
19
|
+
export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.ts";
|
|
20
|
+
export type { PerathosCheck, PerathosOptions, PerathosReport } from "./perathos.ts";
|
|
18
21
|
export { loadAcsGuardianConfig } from "./config.ts";
|
|
19
22
|
export type { AcsGuardianConfig } from "./config.ts";
|
|
20
|
-
export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
|
|
23
|
+
export type { Arrival, ArrivalChallenge, ArrivalClass, ArrivalRate, ChallengeCheck, Classified, DoorHost, DoorOptions, DoorRequest, DoorServerOptions, RateTracker, RateTrackerLimits, RunningDoor } from "./door.ts";
|
|
24
|
+
export type { SignatureCheck, SignedRequest, WebBotAuthOptions, WebBotAuthVerifier } from "./web-bot-auth.ts";
|
|
21
25
|
export * from "./capture.ts";
|
|
22
26
|
export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.ts";
|
|
23
27
|
export { deliverMail, founderNote, PortalStore, portalHandler, readSession, readSessionVia, sendFollowUps, servePortal, signSession, SsoRefusedError, stripeRequest, verifyStripeSignature } from "./portal.ts";
|
|
@@ -76,3 +80,5 @@ export * from "./pr-summary.ts";
|
|
|
76
80
|
export * from "./export.ts";
|
|
77
81
|
export * from "./claude-init.ts";
|
|
78
82
|
export * from "./deny-report.ts";
|
|
83
|
+
export { DESIGN_CSS, LOGO_MARK, APP_HEADER_CSS, THEME_SCRIPT, appHeader } from "./design.ts";
|
|
84
|
+
export * from "./session-audit.ts";
|
package/dist/index.js
CHANGED
|
@@ -6,11 +6,13 @@ export { hecEvent, splunkExporter } from "./splunk.js";
|
|
|
6
6
|
export { serveConsole } from "./console.js";
|
|
7
7
|
export { checkConfig, formatFindings } from "./check.js";
|
|
8
8
|
export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.js";
|
|
9
|
-
export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, verifyChallengeToken } from "./door.js";
|
|
9
|
+
export { AGENT_HEADER, ARRIVAL_FACT, CLASS_HEADER, DOOR_DEFAULT_CAPTURE, DOOR_VERSION, MAX_CHALLENGE_TOKEN, RECEIPT_HEADER, RATE_BURST_MS, RATE_MINUTE_MS, cedarArgs, classifyArrival, createDoorHost, createRateTracker, matchRoute, normalizePath, remoteOf, serveDoor, signedRequestOf, verifyChallengeToken } from "./door.js";
|
|
10
|
+
export { DIRECTORY_MEDIA_TYPE, DIRECTORY_PATH, WEB_BOT_AUTH_TAG, agentOrigin, createWebBotAuthVerifier, jwkThumbprint, normalizeAuthority, parseDictionary, signatureBase } from "./web-bot-auth.js";
|
|
10
11
|
export { DESTINATION_FACT, EGRESS_VERSION, PROXY_REALM, checkProxyCredential, createEgressHost, destinationName, normalizeHost, parseAuthority, publicOnlyLookup, serveEgress } from "./egress.js";
|
|
11
12
|
export { internalAddress } from "./addresses.js";
|
|
12
13
|
export { DRAFT_WARNING, draftEgressPolicy } from "./egress-draft.js";
|
|
13
14
|
export { ACS_ERROR, ACS_GUARDIAN_VERSION, ACS_METHODS, ACS_RECEIPT_KEY, ACS_STEP_FACT, ACS_VERSION, acsEntryHash, createAcsGuardian } from "./acs.js";
|
|
15
|
+
export { formatPerathosReport, PERATHOS_RECEIPT_V1, perathosHead, perathosReceiptHash, verifyPerathosLog } from "./perathos.js";
|
|
14
16
|
export { loadAcsGuardianConfig } from "./config.js";
|
|
15
17
|
export * from "./capture.js";
|
|
16
18
|
export { A2A_CARD_PATH, A2A_RECEIPT_METADATA_KEY, A2A_STREAM_META_KEY, a2aUpstream, fetchAgentCard, serveA2a, textOf } from "./a2a.js";
|
|
@@ -50,3 +52,5 @@ export * from "./pr-summary.js";
|
|
|
50
52
|
export * from "./export.js";
|
|
51
53
|
export * from "./claude-init.js";
|
|
52
54
|
export * from "./deny-report.js";
|
|
55
|
+
export { DESIGN_CSS, LOGO_MARK, APP_HEADER_CSS, THEME_SCRIPT, appHeader } from "./design.js";
|
|
56
|
+
export * from "./session-audit.js";
|
package/dist/log-admin.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
// receipts; the log holds hashes and the panel holds names.
|
|
7
7
|
import { timingSafeEqual } from "node:crypto";
|
|
8
8
|
import { RateLimiter, PLANS } from "./log-store.js";
|
|
9
|
+
import { APP_HEADER_CSS, DESIGN_CSS, THEME_SCRIPT, appHeader } from "./design.js";
|
|
9
10
|
import { clientAddress } from "./log-sink.js";
|
|
10
11
|
const same = (a, b) => {
|
|
11
12
|
const x = Buffer.from(a);
|
|
@@ -41,7 +42,7 @@ export function welcomeSheet(o) {
|
|
|
41
42
|
"a log copy that verify --log and audit --log read with no server.",
|
|
42
43
|
"",
|
|
43
44
|
"What this log does not do: hold receipt contents, forge a receipt (your gateway key signs those), or, today,",
|
|
44
|
-
"countersign with a second independent witness. The proof table: https://agent-custody
|
|
45
|
+
"countersign with a second independent witness. The proof table: https://github.com/svayatta/agent-custody/tree/main/packages/receipts#what-a-receipt-proves-and-what-it-does-not",
|
|
45
46
|
];
|
|
46
47
|
return lines.join("\n");
|
|
47
48
|
}
|
|
@@ -211,79 +212,97 @@ export function adminRoutes(opts) {
|
|
|
211
212
|
};
|
|
212
213
|
}
|
|
213
214
|
/** The page. One file, no framework, no third-party requests; the browser holds the admin credential it prompted for. */
|
|
215
|
+
const TABS = ["registrations", "tenants", "tokens", "usage", "activity"];
|
|
214
216
|
const ADMIN_PAGE = `<!doctype html>
|
|
217
|
+
<html lang="en">
|
|
215
218
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
216
219
|
<title>agent-custody log admin</title>
|
|
217
220
|
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
|
218
221
|
<script>(() => { try { const t = localStorage.getItem("agent-custody-theme"); if (t === "dark" || t === "light") document.documentElement.dataset.theme = t; } catch {} })();</script>
|
|
219
222
|
<style>
|
|
220
|
-
|
|
221
|
-
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #4fc3b0; --warn: #e2b862; --warnbg: #2d2412; } }
|
|
222
|
-
:root[data-theme="dark"] { --ink: #e6ecf0; --ink2: #9fb0bd; --line: #27333c; --bg: #0e1418; --panel: #151d23; --accent: #4fc3b0; --warn: #e2b862; --warnbg: #2d2412; }
|
|
223
|
-
body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, sans-serif; }
|
|
223
|
+
${DESIGN_CSS}${APP_HEADER_CSS}
|
|
224
224
|
main { max-width: 72rem; margin: 0 auto; padding: 2rem 1.25rem 4rem; }
|
|
225
|
-
h1 {
|
|
225
|
+
h1 { margin: 0 0 .25rem; } h2 { margin: 1.5rem 0 .75rem; }
|
|
226
226
|
.sub { color: var(--ink2); margin: 0 0 1.5rem; }
|
|
227
227
|
.row { display: flex; gap: .6rem; flex-wrap: wrap; align-items: end; }
|
|
228
228
|
label { display: grid; gap: .25rem; font-size: .85rem; color: var(--ink2); }
|
|
229
|
-
input {
|
|
230
|
-
|
|
231
|
-
button.quiet { background: transparent; color: var(--accent); }
|
|
232
|
-
button:disabled { opacity: .5; cursor: default; }
|
|
229
|
+
input { min-width: 14rem; }
|
|
230
|
+
.scroll { overflow-x: auto; }
|
|
233
231
|
table { border-collapse: collapse; width: 100%; font-size: .93rem; }
|
|
234
|
-
th, td { text-align: left; padding: .5rem .6rem; border-bottom: 1px solid var(--line); vertical-align: top; }
|
|
235
|
-
th { font-size:
|
|
236
|
-
|
|
237
|
-
pre {
|
|
238
|
-
|
|
239
|
-
.
|
|
232
|
+
th, td { text-align: left; padding: .5rem .6rem; border-bottom: 1px solid var(--line); vertical-align: top; white-space: nowrap; }
|
|
233
|
+
th { font-size: var(--text-xs); font-weight: 600; color: var(--ink2); } th::first-letter { text-transform: uppercase; }
|
|
234
|
+
td.detail { white-space: normal; min-width: 16rem; }
|
|
235
|
+
code, pre { font-size: .86em; }
|
|
236
|
+
pre { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: .9rem 1rem; overflow-x: auto; white-space: pre-wrap; }
|
|
237
|
+
.once { border-left: 3px solid var(--warn); background: var(--warn-bg); padding: .8rem 1rem; border-radius: 0 var(--radius-sm) var(--radius-sm) 0; margin: 1rem 0; }
|
|
238
|
+
.muted { color: var(--ink2); } .err { color: var(--bad); } .ok { color: var(--ok); }
|
|
240
239
|
.tok { font-family: var(--mono); font-size: 1.05rem; word-break: break-all; user-select: all; }
|
|
241
|
-
.
|
|
242
|
-
|
|
240
|
+
.tabs { display: flex; gap: var(--space-1); overflow-x: auto; border-bottom: 1px solid var(--line); margin-bottom: var(--space-4); }
|
|
241
|
+
.tabs a { padding: var(--space-2) var(--space-3); border-bottom: 2px solid transparent; color: var(--ink2); font-weight: 600; text-decoration: none; white-space: nowrap; }
|
|
242
|
+
.tabs a:hover { color: var(--ink); } .tabs a[aria-current] { color: var(--accent); border-bottom-color: var(--accent); }
|
|
243
|
+
.status { margin-left: var(--space-2); font-size: var(--text-sm); }
|
|
244
|
+
.actions { display: flex; gap: var(--space-2); justify-content: flex-end; margin-top: var(--space-5); }
|
|
243
245
|
[hidden] { display: none !important; }
|
|
244
|
-
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .6rem; margin:
|
|
245
|
-
.stat { background: var(--panel); border: 1px solid var(--line); border-radius:
|
|
246
|
-
.stat b { display: block; font-size:
|
|
246
|
+
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: .6rem; margin: .8rem 0 1rem; }
|
|
247
|
+
.stat { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-md); padding: .6rem .8rem; }
|
|
248
|
+
.stat b { display: block; font-size: var(--text-xl); font-variant-numeric: tabular-nums; } .stat span { color: var(--ink2); font-size: .8rem; }
|
|
247
249
|
</style>
|
|
250
|
+
${appHeader("Log admin")}
|
|
248
251
|
<main>
|
|
249
|
-
<
|
|
250
|
-
<p class="sub" id="where">Tenants and tokens on this log.</p
|
|
252
|
+
<h1>Log admin</h1>
|
|
253
|
+
<p class="sub" id="where">Tenants and tokens on this log.</p>
|
|
254
|
+
<p class="err" role="status" data-status="page"></p>
|
|
255
|
+
<nav class="tabs" aria-label="Sections">${TABS.map((t) => `<a href="#tab-${t}">${t[0].toUpperCase()}${t.slice(1)}</a>`).join("")}</nav>
|
|
251
256
|
<section id="app">
|
|
257
|
+
<div data-tab="registrations">
|
|
252
258
|
<h2>Registrations</h2>
|
|
253
|
-
<div class="row"><label>month<input id="rmonth" type="month"></label><button class="quiet" id="loadRegs">Show</button><a id="rcsv" class="quiet" href="#" style="align-self:center">Download CSV</a></div>
|
|
259
|
+
<div class="row"><label>month<input id="rmonth" type="month"></label><button class="quiet" id="loadRegs">Show</button><a id="rcsv" class="quiet" href="#" style="align-self:center">Download CSV</a><span class="status" role="status" data-status="regs"></span></div>
|
|
254
260
|
<div class="stats"><div class="stat"><b id="sTenants">–</b><span>tenants</span></div><div class="stat"><b id="sRegistered">–</b><span>registered through the portal</span></div><div class="stat"><b id="sAppends">–</b><span>appends this month</span></div><div class="stat"><b id="sLeaves">–</b><span>leaves in total</span></div></div>
|
|
255
|
-
<table><thead><tr><th>who</th><th>reach</th><th>tenant</th><th>plan</th><th>registered</th><th>billing</th><th>appends this month</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="regs"></tbody></table>
|
|
261
|
+
<div class="scroll" tabindex="0" role="region" aria-label="Registrations"><table><thead><tr><th>who</th><th>reach</th><th>tenant</th><th>plan</th><th>registered</th><th>billing</th><th>appends this month</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="regs"></tbody></table></div>
|
|
262
|
+
</div>
|
|
263
|
+
<div data-tab="tenants" hidden>
|
|
256
264
|
<h2>Tenants</h2>
|
|
257
|
-
<table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>live tokens</th><th>created</th><th></th></tr></thead><tbody id="tenants"></tbody></table>
|
|
265
|
+
<div class="scroll" tabindex="0" role="region" aria-label="Tenants"><table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>live tokens</th><th>created</th><th></th></tr></thead><tbody id="tenants"></tbody></table></div>
|
|
258
266
|
<h2>New tenant</h2>
|
|
259
267
|
<div class="row">
|
|
260
268
|
<label>tenant id (in the URL)<input id="tid" placeholder="acme" autocomplete="off"></label>
|
|
261
269
|
<label>log id (on tree heads; default = tenant id)<input id="lid" placeholder="acme-eu" autocomplete="off"></label>
|
|
262
|
-
<button id="addTenant">Create</button>
|
|
270
|
+
<button id="addTenant">Create</button><span class="status" role="status" data-status="addTenant"></span>
|
|
271
|
+
</div>
|
|
263
272
|
</div>
|
|
273
|
+
<div data-tab="tokens" hidden>
|
|
264
274
|
<h2>New token</h2>
|
|
265
275
|
<div class="row">
|
|
266
276
|
<label>tenant<input id="ttid" placeholder="acme" autocomplete="off"></label>
|
|
267
277
|
<label>label (which fleet)<input id="label" placeholder="support fleet" autocomplete="off"></label>
|
|
268
|
-
<button id="mint">Mint token</button>
|
|
278
|
+
<button id="mint">Mint token</button><span class="status" role="status" data-status="mint"></span>
|
|
269
279
|
</div>
|
|
270
280
|
<div id="minted" class="once" hidden>
|
|
271
281
|
<p><b>Shown once.</b> Hand it over by a channel you trust; the log keeps only its hash.</p>
|
|
272
282
|
<p class="tok" id="tokval"></p>
|
|
273
|
-
<button class="quiet" id="copyTok">Copy token</button> <button class="quiet" id="copySheet">Copy welcome sheet</button>
|
|
283
|
+
<button class="quiet" id="copyTok">Copy token</button> <button class="quiet" id="copySheet">Copy welcome sheet</button><span class="status" role="status" data-status="copy"></span>
|
|
274
284
|
<pre id="sheet"></pre>
|
|
275
285
|
</div>
|
|
276
|
-
<h2>Usage</h2>
|
|
277
|
-
<div class="row"><label>month<input id="month" type="month"></label><button class="quiet" id="loadUsage">Show</button><a id="csv" class="quiet" href="#" style="align-self:center">Download CSV</a></div>
|
|
278
|
-
<table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>appends this month</th><th>quota</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="usage"></tbody></table>
|
|
279
286
|
<h2>Tokens of a tenant</h2>
|
|
280
|
-
<div class="row"><label>tenant<input id="ltid" placeholder="acme" autocomplete="off"></label><button class="quiet" id="listTokens">List</button></div>
|
|
281
|
-
<table><thead><tr><th>label</th><th>hash</th><th>created</th><th>state</th><th></th></tr></thead><tbody id="tokens"></tbody></table>
|
|
287
|
+
<div class="row"><label>tenant<input id="ltid" placeholder="acme" autocomplete="off"></label><button class="quiet" id="listTokens">List</button><span class="status" role="status" data-status="listTokens"></span></div>
|
|
288
|
+
<div class="scroll" tabindex="0" role="region" aria-label="Tokens of a tenant"><table><thead><tr><th>label</th><th>hash</th><th>created</th><th>state</th><th></th></tr></thead><tbody id="tokens"></tbody></table></div>
|
|
289
|
+
</div>
|
|
290
|
+
<div data-tab="usage" hidden>
|
|
291
|
+
<h2>Usage</h2>
|
|
292
|
+
<div class="row"><label>month<input id="month" type="month"></label><button class="quiet" id="loadUsage">Show</button><a id="csv" class="quiet" href="#" style="align-self:center">Download CSV</a><span class="status" role="status" data-status="usage"></span></div>
|
|
293
|
+
<div class="scroll" tabindex="0" role="region" aria-label="Usage"><table><thead><tr><th>tenant</th><th>log id</th><th>plan</th><th>appends this month</th><th>quota</th><th>leaves in total</th><th>live tokens</th></tr></thead><tbody id="usage"></tbody></table></div>
|
|
294
|
+
</div>
|
|
295
|
+
<div data-tab="activity" hidden>
|
|
282
296
|
<h2>Activity</h2>
|
|
283
297
|
<p class="muted">Every tenant and token change on this log, newest first, with who made it: the name entered at the sign-in prompt, or the command line on the server. Tenants see their own rows in their export.</p>
|
|
284
|
-
<table><thead><tr><th>when</th><th>who</th><th>action</th><th>tenant</th><th>detail</th></tr></thead><tbody id="audit"></tbody></table>
|
|
285
|
-
|
|
298
|
+
<div class="scroll" tabindex="0" role="region" aria-label="Activity"><table><thead><tr><th>when</th><th>who</th><th>action</th><th>tenant</th><th>detail</th></tr></thead><tbody id="audit"></tbody></table></div>
|
|
299
|
+
</div>
|
|
286
300
|
</section>
|
|
301
|
+
<dialog id="planDialog" aria-labelledby="planTitle">
|
|
302
|
+
<h2 id="planTitle">Change the plan?</h2>
|
|
303
|
+
<p>Tenant <code id="dTenant"></code>: change the plan from <b id="dFrom"></b> to <b id="dTo"></b>.</p>
|
|
304
|
+
<div class="actions"><button class="quiet" id="planCancel" type="button">Cancel</button><button id="planSave" type="button">Save plan</button></div>
|
|
305
|
+
</dialog>
|
|
287
306
|
</main>
|
|
288
307
|
<script>
|
|
289
308
|
(() => {
|
|
@@ -297,20 +316,27 @@ const ADMIN_PAGE = `<!doctype html>
|
|
|
297
316
|
return j;
|
|
298
317
|
};
|
|
299
318
|
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c]));
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
const
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
319
|
+
// The result of an action shows beside the control that caused it.
|
|
320
|
+
const say = (key, t, cls) => { const el = document.querySelector("[data-status=\\"" + key + "\\"]"); if (el) { el.textContent = t; el.className = "status " + (cls || "muted"); } };
|
|
321
|
+
const statusSpan = (key) => "<span class=status role=status data-status=\\"" + esc(key) + "\\"></span>";
|
|
322
|
+
// A tab is a link to #tab-<name>. No element has that id, so the browser does not scroll.
|
|
323
|
+
const TABS = ${JSON.stringify(TABS)};
|
|
324
|
+
const showTab = () => {
|
|
325
|
+
const name = location.hash.replace(/^#tab-/, "");
|
|
326
|
+
const tab = TABS.includes(name) ? name : TABS[0];
|
|
327
|
+
for (const pane of document.querySelectorAll("[data-tab]")) pane.hidden = pane.dataset.tab !== tab;
|
|
328
|
+
for (const a of document.querySelectorAll(".tabs a")) { if (a.getAttribute("href") === "#tab-" + tab) a.setAttribute("aria-current", "page"); else a.removeAttribute("aria-current"); }
|
|
329
|
+
};
|
|
330
|
+
window.addEventListener("hashchange", showTab);
|
|
331
|
+
showTab();
|
|
306
332
|
const loadTenants = async () => {
|
|
307
333
|
const list = await api("GET", "/admin/tenants");
|
|
308
|
-
const planPick = (t) => "<select data-plan=\\"" + esc(t.id) + "\\">" + ["free", "team", "enterprise"].map((p) => "<option" + (p === t.plan ? " selected" : "") + ">" + p + "</option>").join("") + "</select>";
|
|
309
|
-
$("tenants").innerHTML = list.map((t) => "<tr><td><code>" + esc(t.id) + "</code></td><td><code>" + esc(t.logId) + "</code></td><td>" + planPick(t) + "</td><td>" + t.tokens + "</td><td>" + esc(t.createdAt.slice(0, 10)) + "</td><td>" + (t.disabledAt ? "<span class=muted>disabled</span>" : "<button class=quiet data-disable=\\"" + esc(t.id) + "\\">Disable</button>") + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>none yet</td></tr>";
|
|
334
|
+
const planPick = (t) => "<select data-plan=\\"" + esc(t.id) + "\\" data-current=\\"" + esc(t.plan) + "\\" aria-label=\\"Plan of " + esc(t.id) + "\\">" + ["free", "team", "enterprise"].map((p) => "<option" + (p === t.plan ? " selected" : "") + ">" + p + "</option>").join("") + "</select>" + statusSpan("plan:" + t.id);
|
|
335
|
+
$("tenants").innerHTML = list.map((t) => "<tr><td><code>" + esc(t.id) + "</code></td><td><code>" + esc(t.logId) + "</code></td><td>" + planPick(t) + "</td><td>" + t.tokens + "</td><td>" + esc(t.createdAt.slice(0, 10)) + "</td><td>" + (t.disabledAt ? "<span class=muted>disabled</span>" : "<button class=quiet data-disable=\\"" + esc(t.id) + "\\">Disable</button>") + statusSpan("disable:" + t.id) + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>none yet</td></tr>";
|
|
310
336
|
};
|
|
311
337
|
const loadTokens = async (id) => {
|
|
312
338
|
const list = await api("GET", "/admin/tenants/" + encodeURIComponent(id) + "/tokens");
|
|
313
|
-
$("tokens").innerHTML = list.map((k) => "<tr><td>" + esc(k.label) + "</td><td><code>" + esc(k.tokenHash.slice(0, 12)) + "</code></td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "<span class=ok>live</span>") + "</td><td>" + (k.revokedAt ? "" : "<button class=quiet data-revoke=\\"" + esc(id) + "|" + esc(k.tokenHash.slice(0, 12)) + "\\">Revoke</button>") + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>no tokens</td></tr>";
|
|
339
|
+
$("tokens").innerHTML = list.map((k) => "<tr><td>" + esc(k.label) + "</td><td><code>" + esc(k.tokenHash.slice(0, 12)) + "</code></td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "<span class=ok>live</span>") + "</td><td>" + (k.revokedAt ? "" : "<button class=quiet data-revoke=\\"" + esc(id) + "|" + esc(k.tokenHash.slice(0, 12)) + "\\">Revoke</button>") + statusSpan("revoke:" + k.tokenHash.slice(0, 12)) + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>no tokens</td></tr>";
|
|
314
340
|
};
|
|
315
341
|
const enter = async () => {
|
|
316
342
|
try {
|
|
@@ -320,21 +346,21 @@ const ADMIN_PAGE = `<!doctype html>
|
|
|
320
346
|
await loadTenants();
|
|
321
347
|
await loadUsage();
|
|
322
348
|
await loadAudit();
|
|
323
|
-
} catch (e) { say(e.message, "err"); }
|
|
349
|
+
} catch (e) { say("page", e.message, "err"); }
|
|
324
350
|
};
|
|
325
|
-
$("addTenant").onclick = async () => { try { const t = await api("POST", "/admin/tenants", { id: $("tid").value.trim(), logId: $("lid").value.trim() }); say("tenant " + t.id + " created; reached at /t/" + t.id + "/", "ok");
|
|
351
|
+
$("addTenant").onclick = async () => { try { const t = await api("POST", "/admin/tenants", { id: $("tid").value.trim(), logId: $("lid").value.trim() }); $("ttid").value = t.id; await loadTenants(); await loadAudit(); say("addTenant", "tenant " + t.id + " created; reached at /t/" + t.id + "/", "ok"); } catch (e) { say("addTenant", e.message, "err"); } };
|
|
326
352
|
$("mint").onclick = async () => {
|
|
327
353
|
try {
|
|
328
354
|
const r = await api("POST", "/admin/tenants/" + encodeURIComponent($("ttid").value.trim()) + "/tokens", { label: $("label").value.trim() });
|
|
329
355
|
$("tokval").textContent = r.token; $("sheet").textContent = r.welcome || "(set --public-url on the server for the welcome sheet)"; $("minted").hidden = false;
|
|
330
|
-
say("token minted for " + $("ttid").value.trim() + "; stored as hash " + r.tokenHash.slice(0, 12), "ok");
|
|
331
356
|
await loadTenants();
|
|
332
357
|
await loadAudit();
|
|
333
|
-
|
|
358
|
+
say("mint", "token minted for " + $("ttid").value.trim() + "; stored as hash " + r.tokenHash.slice(0, 12), "ok");
|
|
359
|
+
} catch (e) { say("mint", e.message, "err"); }
|
|
334
360
|
};
|
|
335
|
-
$("copyTok").onclick = () => navigator.clipboard.writeText($("tokval").textContent).then(() => say("token copied", "ok"));
|
|
336
|
-
$("copySheet").onclick = () => navigator.clipboard.writeText($("sheet").textContent).then(() => say("welcome sheet copied", "ok"));
|
|
337
|
-
$("listTokens").onclick = () => loadTokens($("ltid").value.trim()).
|
|
361
|
+
$("copyTok").onclick = () => navigator.clipboard.writeText($("tokval").textContent).then(() => say("copy", "token copied", "ok"), (e) => say("copy", e.message, "err"));
|
|
362
|
+
$("copySheet").onclick = () => navigator.clipboard.writeText($("sheet").textContent).then(() => say("copy", "welcome sheet copied", "ok"), (e) => say("copy", e.message, "err"));
|
|
363
|
+
$("listTokens").onclick = () => loadTokens($("ltid").value.trim()).then(() => say("listTokens", "", "muted"), (e) => say("listTokens", e.message, "err"));
|
|
338
364
|
const loadUsage = async () => {
|
|
339
365
|
const month = $("month").value || new Date().toISOString().slice(0, 7);
|
|
340
366
|
const u = await api("GET", "/admin/usage?month=" + encodeURIComponent(month));
|
|
@@ -352,21 +378,36 @@ const ADMIN_PAGE = `<!doctype html>
|
|
|
352
378
|
};
|
|
353
379
|
const loadAudit = async () => {
|
|
354
380
|
const a = await api("GET", "/admin/audit?limit=100");
|
|
355
|
-
$("audit").innerHTML = a.entries.map((e) => "<tr><td>" + esc(e.at.replace("T", " ").slice(0, 19)) + "</td><td><code>" + esc(e.actor) + "</code></td><td>" + esc(e.action) + "</td><td><code>" + esc(e.tenantId || "") + "</code></td><td class
|
|
381
|
+
$("audit").innerHTML = a.entries.map((e) => "<tr><td>" + esc(e.at.replace("T", " ").slice(0, 19)) + "</td><td><code>" + esc(e.actor) + "</code></td><td>" + esc(e.action) + "</td><td><code>" + esc(e.tenantId || "") + "</code></td><td class=\\"detail muted\\">" + esc(Object.entries(e.detail).map(([k, v]) => k + "=" + v).join(" ")) + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>nothing yet</td></tr>";
|
|
356
382
|
};
|
|
357
|
-
$("loadUsage").onclick = () => loadUsage().
|
|
358
|
-
$("loadRegs").onclick = () => loadRegs().
|
|
383
|
+
$("loadUsage").onclick = () => loadUsage().then(() => say("usage", "", "muted"), (e) => say("usage", e.message, "err"));
|
|
384
|
+
$("loadRegs").onclick = () => loadRegs().then(() => say("regs", "", "muted"), (e) => say("regs", e.message, "err"));
|
|
359
385
|
$("month").value = $("rmonth").value = new Date().toISOString().slice(0, 7);
|
|
360
|
-
|
|
386
|
+
// A plan change opens the dialog. It saves only when the operator confirms; any other way out puts the old plan back.
|
|
387
|
+
const dialog = $("planDialog");
|
|
388
|
+
let pending = null;
|
|
389
|
+
document.addEventListener("change", (e) => {
|
|
361
390
|
const s = e.target.closest("select[data-plan]"); if (!s) return;
|
|
362
|
-
|
|
391
|
+
pending = { select: s, id: s.dataset.plan, from: s.dataset.current, to: s.value };
|
|
392
|
+
$("dTenant").textContent = pending.id; $("dFrom").textContent = pending.from; $("dTo").textContent = pending.to;
|
|
393
|
+
dialog.returnValue = "";
|
|
394
|
+
dialog.showModal();
|
|
395
|
+
});
|
|
396
|
+
$("planCancel").onclick = () => dialog.close("cancel");
|
|
397
|
+
$("planSave").onclick = () => dialog.close("save");
|
|
398
|
+
dialog.addEventListener("close", async () => {
|
|
399
|
+
const p = pending; pending = null;
|
|
400
|
+
if (!p) return;
|
|
401
|
+
if (dialog.returnValue !== "save") { p.select.value = p.from; return; }
|
|
402
|
+
try { await api("POST", "/admin/tenants/" + encodeURIComponent(p.id) + "/plan", { plan: p.to }); await loadTenants(); await loadRegs(); await loadUsage(); await loadAudit(); say("plan:" + p.id, "plan set to " + p.to, "ok"); } catch (err) { p.select.value = p.from; say("plan:" + p.id, err.message, "err"); }
|
|
363
403
|
});
|
|
364
404
|
document.addEventListener("click", async (e) => {
|
|
365
405
|
const b = e.target.closest("button"); if (!b) return;
|
|
366
|
-
if (b.dataset.disable && confirm("Disable tenant " + b.dataset.disable + "? Its paths answer 404 within ten seconds.")) { try { await api("POST", "/admin/tenants/" + encodeURIComponent(
|
|
367
|
-
if (b.dataset.revoke) { const [id, prefix] = b.dataset.revoke.split("|"); if (confirm("Revoke token " + prefix + " of " + id + "?")) { try { await api("POST", "/admin/tenants/" + encodeURIComponent(id) + "/tokens/" + prefix + "/revoke"); await loadTokens(id); await loadTenants(); await loadAudit(); say("revoked", "ok"); } catch (err) { say(err.message, "err"); } } }
|
|
406
|
+
if (b.dataset.disable && confirm("Disable tenant " + b.dataset.disable + "? Its paths answer 404 within ten seconds.")) { const id = b.dataset.disable; try { await api("POST", "/admin/tenants/" + encodeURIComponent(id) + "/disable"); await loadTenants(); await loadAudit(); say("disable:" + id, "disabled", "ok"); } catch (err) { say("disable:" + id, err.message, "err"); } }
|
|
407
|
+
if (b.dataset.revoke) { const [id, prefix] = b.dataset.revoke.split("|"); if (confirm("Revoke token " + prefix + " of " + id + "?")) { try { await api("POST", "/admin/tenants/" + encodeURIComponent(id) + "/tokens/" + prefix + "/revoke"); await loadTokens(id); await loadTenants(); await loadAudit(); say("revoke:" + prefix, "revoked", "ok"); } catch (err) { say("revoke:" + prefix, err.message, "err"); } } }
|
|
368
408
|
});
|
|
369
409
|
enter();
|
|
370
410
|
})();
|
|
371
411
|
</script>
|
|
412
|
+
<script>${THEME_SCRIPT}</script>
|
|
372
413
|
`;
|
package/dist/log-store.d.ts
CHANGED
|
@@ -82,13 +82,16 @@ export interface TokenRecord {
|
|
|
82
82
|
tokenHash: string;
|
|
83
83
|
createdAt: string;
|
|
84
84
|
revokedAt: string | null;
|
|
85
|
+
/** the last append with this token, to within a minute; null when never used since the column came */
|
|
86
|
+
lastUsedAt: string | null;
|
|
85
87
|
}
|
|
88
|
+
export declare const AUDIT_ACTIONS: readonly ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset"];
|
|
86
89
|
/** One administrative action: who did what to which tenant, when. Written by every mutation and never deleted. */
|
|
87
90
|
export interface AuditEntry {
|
|
88
91
|
id: number;
|
|
89
92
|
at: string;
|
|
90
93
|
actor: string;
|
|
91
|
-
action:
|
|
94
|
+
action: (typeof AUDIT_ACTIONS)[number];
|
|
92
95
|
tenantId: string | null;
|
|
93
96
|
detail: Record<string, unknown>;
|
|
94
97
|
}
|
|
@@ -109,6 +112,7 @@ export declare class PostgresTenancy {
|
|
|
109
112
|
private readonly logs;
|
|
110
113
|
private readonly tenantCache;
|
|
111
114
|
private readonly tokenCache;
|
|
115
|
+
private readonly tokenUseNoted;
|
|
112
116
|
private readonly quotaCache;
|
|
113
117
|
private readonly quotas;
|
|
114
118
|
private ready;
|
|
@@ -118,16 +122,18 @@ export declare class PostgresTenancy {
|
|
|
118
122
|
private init;
|
|
119
123
|
/** Writes one audit entry. `detail` never holds a secret or a token. */
|
|
120
124
|
record(actor: string | undefined, action: AuditEntry["action"], tenantId: string | null, detail: Record<string, unknown>): Promise<void>;
|
|
121
|
-
/** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
|
|
125
|
+
/** Administrative actions, newest first; for one tenant when given, and only entries older than the id `before` when given. What the admin page shows and a tenant's export carries. */
|
|
122
126
|
audit(opts?: {
|
|
123
127
|
tenant?: string;
|
|
124
128
|
limit?: number;
|
|
129
|
+
before?: number;
|
|
125
130
|
}): Promise<AuditEntry[]>;
|
|
126
131
|
private row;
|
|
127
132
|
/** The tenant, or null. Answers from a ten-second cache, so a disabled tenant is refused within that. */
|
|
128
133
|
tenant(id: string): Promise<Tenant | null>;
|
|
129
134
|
/** Whether the presented token is a live token of this tenant. Positive answers are cached for thirty seconds. */
|
|
130
135
|
authorize(tenantId: string, token: string | null): Promise<boolean>;
|
|
136
|
+
private noteTokenUse;
|
|
131
137
|
/** The tenant's log, one instance per tenant per process. */
|
|
132
138
|
log(tenantId: string): Promise<PostgresLog>;
|
|
133
139
|
/** Creates a tenant, or renames its log id. `by` names who did it in the audit trail. */
|
package/dist/log-store.js
CHANGED
|
@@ -174,6 +174,7 @@ export class PostgresLog {
|
|
|
174
174
|
export const PLANS = ["free", "team", "enterprise"];
|
|
175
175
|
export const PLAN_QUOTAS = { free: 10_000, team: 1_000_000, enterprise: null };
|
|
176
176
|
const sha256hex = (s) => createHash("sha256").update(s).digest("hex");
|
|
177
|
+
export const AUDIT_ACTIONS = ["tenant.add", "tenant.disable", "tenant.plan", "token.add", "token.revoke", "policy.add", "policy.remove", "sso.set", "sso.remove", "user.mfa-reset"];
|
|
177
178
|
/** Tenants and their tokens, in Postgres. Tokens are stored hashed; a lookup hashes what the caller presented. */
|
|
178
179
|
export class PostgresTenancy {
|
|
179
180
|
client;
|
|
@@ -181,6 +182,7 @@ export class PostgresTenancy {
|
|
|
181
182
|
logs = new Map();
|
|
182
183
|
tenantCache = new Map();
|
|
183
184
|
tokenCache = new Map();
|
|
185
|
+
tokenUseNoted = new Map();
|
|
184
186
|
quotaCache = new Map();
|
|
185
187
|
quotas;
|
|
186
188
|
ready = null;
|
|
@@ -197,6 +199,7 @@ export class PostgresTenancy {
|
|
|
197
199
|
await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}tenants (id TEXT PRIMARY KEY, log_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), disabled_at TIMESTAMPTZ)`);
|
|
198
200
|
await this.client.query(`ALTER TABLE ${p}tenants ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'free'`);
|
|
199
201
|
await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}tokens (token_hash TEXT PRIMARY KEY, tenant_id TEXT NOT NULL REFERENCES ${p}tenants(id), label TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), revoked_at TIMESTAMPTZ)`);
|
|
202
|
+
await this.client.query(`ALTER TABLE ${p}tokens ADD COLUMN IF NOT EXISTS last_used_at TIMESTAMPTZ`);
|
|
200
203
|
await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}audit (id BIGSERIAL PRIMARY KEY, at TIMESTAMPTZ NOT NULL DEFAULT now(), actor TEXT NOT NULL, action TEXT NOT NULL, tenant_id TEXT, detail JSONB NOT NULL DEFAULT '{}')`);
|
|
201
204
|
// named policy versions a tenant chose to publish, so a receipt's policy digest can be read as a name; enforcement never reads this table
|
|
202
205
|
await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}policies (id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL REFERENCES ${p}tenants(id), name TEXT NOT NULL, digest TEXT NOT NULL, text TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_by TEXT NOT NULL, UNIQUE (tenant_id, digest))`);
|
|
@@ -209,13 +212,11 @@ export class PostgresTenancy {
|
|
|
209
212
|
await this.init();
|
|
210
213
|
await this.client.query(`INSERT INTO ${this.prefix}audit (actor, action, tenant_id, detail) VALUES ($1, $2, $3, $4)`, [actor ?? "unattributed", action, tenantId, JSON.stringify(detail)]);
|
|
211
214
|
}
|
|
212
|
-
/** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
|
|
215
|
+
/** Administrative actions, newest first; for one tenant when given, and only entries older than the id `before` when given. What the admin page shows and a tenant's export carries. */
|
|
213
216
|
async audit(opts = {}) {
|
|
214
217
|
await this.init();
|
|
215
|
-
const limit = Math.min(Math.max(1, opts.limit ?? 200), 1000);
|
|
216
|
-
const rows = (opts.tenant
|
|
217
|
-
? await this.client.query(`SELECT id, at, actor, action, tenant_id, detail FROM ${this.prefix}audit WHERE tenant_id = $1 ORDER BY id DESC LIMIT ${limit}`, [opts.tenant])
|
|
218
|
-
: await this.client.query(`SELECT id, at, actor, action, tenant_id, detail FROM ${this.prefix}audit ORDER BY id DESC LIMIT ${limit}`)).rows;
|
|
218
|
+
const limit = Math.min(Math.max(1, Math.trunc(opts.limit ?? 200)), 1000);
|
|
219
|
+
const rows = (await this.client.query(`SELECT id, at, actor, action, tenant_id, detail FROM ${this.prefix}audit WHERE ($1::text IS NULL OR tenant_id = $1) AND ($2::bigint IS NULL OR id < $2) ORDER BY id DESC LIMIT ${limit}`, [opts.tenant ?? null, opts.before ?? null])).rows;
|
|
219
220
|
return rows.map((r) => ({ id: Number(r.id), at: new Date(r.at).toISOString(), actor: String(r.actor), action: r.action, tenantId: r.tenant_id === null || r.tenant_id === undefined ? null : String(r.tenant_id), detail: (typeof r.detail === "string" ? JSON.parse(r.detail) : r.detail) }));
|
|
220
221
|
}
|
|
221
222
|
row(r) {
|
|
@@ -240,14 +241,23 @@ export class PostgresTenancy {
|
|
|
240
241
|
const hash = sha256hex(token);
|
|
241
242
|
const key = `${tenantId}:${hash}`;
|
|
242
243
|
const at = this.tokenCache.get(key);
|
|
243
|
-
if (at && Date.now() - at < 30_000)
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
244
|
+
if (!(at && Date.now() - at < 30_000)) {
|
|
245
|
+
const rows = (await this.client.query(`SELECT 1 FROM ${this.prefix}tokens WHERE token_hash = $1 AND tenant_id = $2 AND revoked_at IS NULL`, [hash, tenantId])).rows;
|
|
246
|
+
if (rows.length === 0)
|
|
247
|
+
return false;
|
|
248
|
+
this.tokenCache.set(key, Date.now());
|
|
249
|
+
}
|
|
250
|
+
this.noteTokenUse(hash);
|
|
249
251
|
return true;
|
|
250
252
|
}
|
|
253
|
+
// At most one write a minute per token per process, off the append's path: a failure costs only the "last used" time.
|
|
254
|
+
noteTokenUse(hash) {
|
|
255
|
+
const now = Date.now();
|
|
256
|
+
if (now - (this.tokenUseNoted.get(hash) ?? 0) < 60_000)
|
|
257
|
+
return;
|
|
258
|
+
this.tokenUseNoted.set(hash, now);
|
|
259
|
+
this.client.query(`UPDATE ${this.prefix}tokens SET last_used_at = now() WHERE token_hash = $1`, [hash]).catch(() => this.tokenUseNoted.delete(hash));
|
|
260
|
+
}
|
|
251
261
|
/** The tenant's log, one instance per tenant per process. */
|
|
252
262
|
async log(tenantId) {
|
|
253
263
|
let l = this.logs.get(tenantId);
|
|
@@ -404,7 +414,7 @@ export class PostgresTenancy {
|
|
|
404
414
|
}
|
|
405
415
|
async listTokens(tenantId) {
|
|
406
416
|
await this.init();
|
|
407
|
-
return (await this.client.query(`SELECT tenant_id, label, token_hash, created_at, revoked_at FROM ${this.prefix}tokens WHERE tenant_id = $1 ORDER BY created_at`, [tenantId])).rows.map((r) => ({ tenantId: String(r.tenant_id), label: String(r.label), tokenHash: String(r.token_hash), createdAt: new Date(r.created_at).toISOString(), revokedAt: r.revoked_at ? new Date(r.revoked_at).toISOString() : null }));
|
|
417
|
+
return (await this.client.query(`SELECT tenant_id, label, token_hash, created_at, revoked_at, last_used_at FROM ${this.prefix}tokens WHERE tenant_id = $1 ORDER BY created_at`, [tenantId])).rows.map((r) => ({ tenantId: String(r.tenant_id), label: String(r.label), tokenHash: String(r.token_hash), createdAt: new Date(r.created_at).toISOString(), revokedAt: r.revoked_at ? new Date(r.revoked_at).toISOString() : null, lastUsedAt: r.last_used_at ? new Date(r.last_used_at).toISOString() : null }));
|
|
408
418
|
}
|
|
409
419
|
}
|
|
410
420
|
/**
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export declare const PERATHOS_RECEIPT_V1 = "perathos.receipt/v1";
|
|
2
|
+
export interface PerathosCheck {
|
|
3
|
+
name: string;
|
|
4
|
+
ok: boolean;
|
|
5
|
+
detail?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface PerathosReport {
|
|
8
|
+
ok: boolean;
|
|
9
|
+
checks: PerathosCheck[];
|
|
10
|
+
warnings: string[];
|
|
11
|
+
session: string | null;
|
|
12
|
+
agent: string | null;
|
|
13
|
+
receipts: number;
|
|
14
|
+
toolCalls: number;
|
|
15
|
+
checkpoints: number;
|
|
16
|
+
signers: string[];
|
|
17
|
+
/** the seq of the last checkpoint; receipts after it are an unsealed tail, which is not an error */
|
|
18
|
+
sealedThrough: number;
|
|
19
|
+
unsealedTail: number;
|
|
20
|
+
/** pre receipts whose guard decided deny: calls that never ran */
|
|
21
|
+
denied: number;
|
|
22
|
+
signerFailures: number;
|
|
23
|
+
firstTs: string | null;
|
|
24
|
+
lastTs: string | null;
|
|
25
|
+
provenance: string;
|
|
26
|
+
}
|
|
27
|
+
export interface PerathosOptions {
|
|
28
|
+
/** Ed25519 public keys as 64 hex characters; when given, every checkpoint signer must be one of them */
|
|
29
|
+
trustedKeys?: string[];
|
|
30
|
+
/** accept a log with no checkpoint or an unsigned one, as a warning */
|
|
31
|
+
allowUnsigned?: boolean;
|
|
32
|
+
/** the head witness (`<session_id>.head.json`): the latest checkpoint's seq and receipt_hash */
|
|
33
|
+
head?: {
|
|
34
|
+
seq: number;
|
|
35
|
+
receipt_hash: string;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
type Receipt = Record<string, unknown>;
|
|
39
|
+
/** The receipt_hash the spec defines: SHA-256 of the canonical JSON of every field but receipt_hash and signature. */
|
|
40
|
+
export declare function perathosReceiptHash(r: Receipt): string;
|
|
41
|
+
/** The head witness file, `{ "seq", "receipt_hash" }`, checked for shape. */
|
|
42
|
+
export declare function perathosHead(text: string): {
|
|
43
|
+
seq: number;
|
|
44
|
+
receipt_hash: string;
|
|
45
|
+
};
|
|
46
|
+
/** Check a Perathos session log (JSON Lines) against rules 1 to 9 of the v1 spec. */
|
|
47
|
+
export declare function verifyPerathosLog(text: string, opts?: PerathosOptions): PerathosReport;
|
|
48
|
+
/** The report as text, in the style of `verify`. */
|
|
49
|
+
export declare function formatPerathosReport(r: PerathosReport): string;
|
|
50
|
+
export {};
|