@agent-custody/receipts 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -7
- package/dist/check.d.ts +19 -0
- package/dist/check.js +288 -0
- package/dist/cli.js +119 -11
- package/dist/config.d.ts +1 -0
- package/dist/config.js +3 -0
- package/dist/console-page.d.ts +4 -0
- package/dist/console-page.js +342 -0
- package/dist/console.d.ts +20 -0
- package/dist/console.js +522 -0
- package/dist/gateway-http.js +1 -1
- package/dist/gateway.d.ts +18 -0
- package/dist/gateway.js +196 -48
- package/dist/index.d.ts +6 -2
- package/dist/index.js +4 -1
- package/dist/issue.d.ts +31 -1
- package/dist/issue.js +261 -10
- package/dist/log-store.d.ts +3 -2
- package/dist/log-store.js +2 -0
- package/dist/policy.d.ts +4 -0
- package/dist/policy.js +15 -0
- package/dist/portal.d.ts +78 -4
- package/dist/portal.js +517 -26
- package/dist/simulate.d.ts +7 -1
- package/dist/simulate.js +27 -2
- package/dist/sso.d.ts +47 -0
- package/dist/sso.js +161 -0
- package/dist/verify.js +8 -4
- package/docs/codex-recovery.md +132 -0
- package/docs/configuration.md +226 -0
- package/docs/console.md +78 -0
- package/docs/policies.md +4 -1
- package/docs/threat-model.md +13 -0
- package/docs/tutorials.md +4 -0
- package/docs/usage.md +38 -4
- package/package.json +8 -2
- package/vectors/audit.json +27 -27
- package/vectors/receipts.json +1135 -929
package/dist/issue.js
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
1
|
// Signing, logging and writing a receipt. Shared by every producer: the gateway and the SDK.
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { RECEIPT_ID, SALTS_DIR, saltsFileFor } from "./retention.js";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
5
7
|
import { effectiveRule, getAt, privateView } from "./capture.js";
|
|
6
8
|
import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
|
|
7
9
|
import { fileLog } from "./log-sink.js";
|
|
10
|
+
import { ownerAlive, processStamp } from "./operations.js";
|
|
8
11
|
import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
|
|
12
|
+
/** The receipts whose log append failed wait here, signed, until `flushOutbox` appends them. */
|
|
13
|
+
export const OUTBOX_DIR = "outbox";
|
|
14
|
+
/**
|
|
15
|
+
* Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
|
|
16
|
+
* no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
|
|
17
|
+
*/
|
|
18
|
+
export class ReceiptPending extends Error {
|
|
19
|
+
receiptId;
|
|
20
|
+
constructor(receiptId, cause) {
|
|
21
|
+
super(`receipt ${receiptId} is kept in the outbox; its log append is pending: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
22
|
+
this.name = "ReceiptPending";
|
|
23
|
+
this.receiptId = receiptId;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
9
26
|
/** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
|
|
10
27
|
export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
11
28
|
const sink = typeof log === "string" ? fileLog(log, key) : log;
|
|
@@ -32,6 +49,116 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
32
49
|
/** an authorization whose receipt has not followed within this long is a call that died; its view is let go */
|
|
33
50
|
const COMMITTED_FOR_MS = 60 * 60 * 1000;
|
|
34
51
|
const COMMITTED_AT_MOST = 100_000;
|
|
52
|
+
/** a lock that its owner has not touched for this long is broken, whatever machine the owner is on */
|
|
53
|
+
const LOCK_STALE_MS = 15 * 60 * 1000;
|
|
54
|
+
const outboxDir = join(receiptsDir, OUTBOX_DIR);
|
|
55
|
+
const outboxed = () => existsSync(outboxDir) ? readdirSync(outboxDir).filter((f) => f.endsWith(".json") && RECEIPT_ID.test(f.slice(0, -".json".length))) : [];
|
|
56
|
+
/** the outbox in the order of the signed statements' timestamps; an entry that cannot be read sorts first and is dealt with when its turn comes */
|
|
57
|
+
const outboxOrdered = () => outboxed().map((f) => {
|
|
58
|
+
let at = 0;
|
|
59
|
+
try {
|
|
60
|
+
const env = JSON.parse(readFileSync(join(outboxDir, f), "utf8")).envelope;
|
|
61
|
+
at = Date.parse(JSON.parse(Buffer.from(env.payload, "base64").toString("utf8")).predicate.timestamp) || 0;
|
|
62
|
+
}
|
|
63
|
+
catch { /* unreadable: at stays 0 */ }
|
|
64
|
+
return { f, at };
|
|
65
|
+
}).sort((a, b) => a.at - b.at || (a.f < b.f ? -1 : 1)).map((e) => e.f);
|
|
66
|
+
/** the file is whole or absent, and on disk before the caller goes on: it can be the only copy of the evidence */
|
|
67
|
+
const writeDurable = (file, text) => {
|
|
68
|
+
const fd = openSync(`${file}.tmp`, "w");
|
|
69
|
+
try {
|
|
70
|
+
writeFileSync(fd, text);
|
|
71
|
+
fsyncSync(fd);
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
closeSync(fd);
|
|
75
|
+
}
|
|
76
|
+
renameSync(`${file}.tmp`, file);
|
|
77
|
+
syncDir(dirname(file));
|
|
78
|
+
};
|
|
79
|
+
const syncDir = (dir) => {
|
|
80
|
+
const fd = openSync(dir, "r");
|
|
81
|
+
try {
|
|
82
|
+
fsyncSync(fd);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
closeSync(fd);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const lockFile = join(outboxDir, ".lock");
|
|
89
|
+
/** Takes the outbox lock with an exclusive create. A lock whose owner is gone, or that no one has touched for a long time, is broken. Returns its release, or undefined when another flusher holds it. */
|
|
90
|
+
const takeLock = () => {
|
|
91
|
+
const token = randomUUID();
|
|
92
|
+
const body = JSON.stringify({ token, pid: process.pid, start: processStamp(process.pid), host: hostname() });
|
|
93
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
94
|
+
try {
|
|
95
|
+
const fd = openSync(lockFile, "wx", 0o600);
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(fd, body);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
return () => {
|
|
103
|
+
try {
|
|
104
|
+
if (JSON.parse(readFileSync(lockFile, "utf8")).token === token)
|
|
105
|
+
rmSync(lockFile, { force: true });
|
|
106
|
+
}
|
|
107
|
+
catch { /* already broken by another flusher */ }
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
if (e.code !== "EEXIST")
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
if (!lockIsStale())
|
|
115
|
+
return undefined;
|
|
116
|
+
// two flushers may both judge it stale; the rename lets one of them move it, the other gets ENOENT and tries again
|
|
117
|
+
try {
|
|
118
|
+
const gone = `${lockFile}.stale-${randomUUID()}`;
|
|
119
|
+
renameSync(lockFile, gone);
|
|
120
|
+
rmSync(gone, { force: true });
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
if (e.code !== "ENOENT")
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
};
|
|
129
|
+
const lockIsStale = () => {
|
|
130
|
+
try {
|
|
131
|
+
const age = Date.now() - statSync(lockFile).mtimeMs;
|
|
132
|
+
let owner;
|
|
133
|
+
try {
|
|
134
|
+
owner = JSON.parse(readFileSync(lockFile, "utf8"));
|
|
135
|
+
}
|
|
136
|
+
catch { /* a lock being written */ }
|
|
137
|
+
if (!owner)
|
|
138
|
+
return age > 60_000;
|
|
139
|
+
if (owner.host === hostname() && !ownerAlive({ ownerPid: owner.pid, ...(owner.start ? { ownerStart: owner.start } : {}) }))
|
|
140
|
+
return true;
|
|
141
|
+
return age > LOCK_STALE_MS;
|
|
142
|
+
}
|
|
143
|
+
catch (e) {
|
|
144
|
+
if (e.code === "ENOENT")
|
|
145
|
+
return true;
|
|
146
|
+
throw e;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const writeBundle = async (receiptId, v, bundle) => {
|
|
150
|
+
const file = join(receiptsDir, `${receiptId}.json`);
|
|
151
|
+
// whole or absent: a flush takes a bundle that is there as proof that the outbox entry is done
|
|
152
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(bundle, null, 2));
|
|
153
|
+
renameSync(`${file}.tmp`, file);
|
|
154
|
+
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
155
|
+
// exporter sees the view, never the full call.
|
|
156
|
+
if (opts.exporter)
|
|
157
|
+
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
158
|
+
};
|
|
159
|
+
let flushing;
|
|
160
|
+
/** the log's answer for a receipt whose bundle could not be written yet: a retry in this process writes the bundle and does not append again */
|
|
161
|
+
const appended = new Map();
|
|
35
162
|
/**
|
|
36
163
|
* The salts behind a statement's digest-only commitments, kept beside the receipts and never in them:
|
|
37
164
|
* `receipts/salts/<id>.json`, the owner's alone. They are what makes a disclosure possible for a value withheld
|
|
@@ -47,7 +174,7 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
47
174
|
return {
|
|
48
175
|
keyid: key.keyid,
|
|
49
176
|
log: sink,
|
|
50
|
-
async issue(predicate, ctx, retainPrepared) {
|
|
177
|
+
async issue(predicate, ctx, retainPrepared, issueOpts) {
|
|
51
178
|
ensureSaltsDir();
|
|
52
179
|
// the authorization's view stays until the log has taken the receipt: a producer that retries after a refusal gets the same commitments and salts
|
|
53
180
|
const prior = committed.get(predicate.receiptId)?.view;
|
|
@@ -63,16 +190,32 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
63
190
|
if (!checked.ok || envelope.payloadType !== RECEIPT_TYPE || v.receiptId !== predicate.receiptId || canonicalize(checked.payload) !== canonicalize(buildStatement(v)))
|
|
64
191
|
throw new Error("prepared receipt does not match this issuer, predicate, or receipt id");
|
|
65
192
|
}
|
|
66
|
-
|
|
193
|
+
let entry;
|
|
194
|
+
try {
|
|
195
|
+
entry = await sink.append(canonicalize(envelope));
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
if (!issueOpts?.deferLog)
|
|
199
|
+
throw e;
|
|
200
|
+
// The call has happened, so its receipt is kept: signed, with its salts, and appended later. The salts go
|
|
201
|
+
// first, so an outbox entry never lacks them; the rename makes the entry whole or absent.
|
|
202
|
+
try {
|
|
203
|
+
keepSalts(pv);
|
|
204
|
+
mkdirSync(outboxDir, { recursive: true });
|
|
205
|
+
writeDurable(join(outboxDir, `${predicate.receiptId}.json`), JSON.stringify({ envelope }));
|
|
206
|
+
syncDir(receiptsDir);
|
|
207
|
+
}
|
|
208
|
+
catch (w) {
|
|
209
|
+
throw new Error(`${e instanceof Error ? e.message : String(e)}; the receipt could not be kept in the outbox either: ${w instanceof Error ? w.message : String(w)}`, { cause: e });
|
|
210
|
+
}
|
|
211
|
+
committed.delete(predicate.receiptId);
|
|
212
|
+
throw new ReceiptPending(predicate.receiptId, e);
|
|
213
|
+
}
|
|
67
214
|
committed.delete(predicate.receiptId);
|
|
68
215
|
// the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
|
|
69
216
|
keepSalts(pv);
|
|
70
217
|
const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
|
|
71
|
-
|
|
72
|
-
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
73
|
-
// exporter sees the view, never the full call.
|
|
74
|
-
if (opts.exporter)
|
|
75
|
-
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
218
|
+
await writeBundle(predicate.receiptId, v, bundle);
|
|
76
219
|
return bundle;
|
|
77
220
|
},
|
|
78
221
|
async authorize(predicate, ctx) {
|
|
@@ -97,5 +240,113 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
97
240
|
writeFileSync(join(receiptsDir, `${predicate.receiptId}.authorization.json`), JSON.stringify(bundle, null, 2));
|
|
98
241
|
return bundle;
|
|
99
242
|
},
|
|
243
|
+
pending: () => outboxed().length,
|
|
244
|
+
flushOutbox() {
|
|
245
|
+
flushing ??= (async () => {
|
|
246
|
+
const idle = () => ({ sent: 0, pending: outboxed().length, setAside: 0, foreign: 0 });
|
|
247
|
+
if (!outboxed().length)
|
|
248
|
+
return idle();
|
|
249
|
+
const release = takeLock();
|
|
250
|
+
if (!release)
|
|
251
|
+
return idle();
|
|
252
|
+
try {
|
|
253
|
+
let sent = 0;
|
|
254
|
+
let setAside = 0;
|
|
255
|
+
let foreign = 0;
|
|
256
|
+
const errors = [];
|
|
257
|
+
const done = () => ({ sent, pending: outboxed().length, setAside, foreign, ...(errors.length ? { error: errors.length === 1 ? errors[0] : `${errors[0]} (and ${errors.length - 1} more)` } : {}) });
|
|
258
|
+
const setAsideFile = (file) => {
|
|
259
|
+
try {
|
|
260
|
+
renameSync(file, `${file}.bad`);
|
|
261
|
+
setAside++;
|
|
262
|
+
}
|
|
263
|
+
catch (e) {
|
|
264
|
+
if (e.code !== "ENOENT")
|
|
265
|
+
throw e;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
for (const f of outboxOrdered()) {
|
|
269
|
+
const receiptId = f.slice(0, -".json".length);
|
|
270
|
+
const file = join(outboxDir, f);
|
|
271
|
+
try {
|
|
272
|
+
// a bundle already there means the append and the write happened and only the removal did not
|
|
273
|
+
if (existsSync(join(receiptsDir, f))) {
|
|
274
|
+
rmSync(file, { force: true });
|
|
275
|
+
appended.delete(receiptId);
|
|
276
|
+
sent++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
let record;
|
|
280
|
+
try {
|
|
281
|
+
record = JSON.parse(readFileSync(file, "utf8"));
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
// gone: another flusher took it; anything else that is not readable JSON is damaged
|
|
285
|
+
if (e.code === "ENOENT")
|
|
286
|
+
continue;
|
|
287
|
+
if (!(e instanceof SyntaxError))
|
|
288
|
+
throw e;
|
|
289
|
+
setAsideFile(file);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const envelope = record?.envelope;
|
|
293
|
+
if (typeof envelope?.payload !== "string" || !Array.isArray(envelope.signatures) || envelope.signatures.length === 0) {
|
|
294
|
+
setAsideFile(file);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
// a signature by another key proves nothing about this entry (a rotated key, a restored backup): it stays, and is reported
|
|
298
|
+
if (!envelope.signatures.some((sig) => sig?.keyid === key.keyid)) {
|
|
299
|
+
foreign++;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
// only this issuer's own receipt, under its own id, goes to the log; anything else is set aside, not retried
|
|
303
|
+
const checked = dsseVerify(envelope, [key]);
|
|
304
|
+
const statement = (checked.ok ? checked.payload : undefined);
|
|
305
|
+
if (!statement || envelope.payloadType !== RECEIPT_TYPE || statement.predicate?.receiptId !== receiptId) {
|
|
306
|
+
setAsideFile(file);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
let entry = record.appended ?? appended.get(receiptId);
|
|
310
|
+
if (!entry) {
|
|
311
|
+
try {
|
|
312
|
+
entry = await sink.append(canonicalize(envelope));
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
errors.push(e instanceof Error ? e.message : String(e));
|
|
316
|
+
return done();
|
|
317
|
+
}
|
|
318
|
+
// Until the bundle is written, the answer is the only proof that the log has the leaf. It is kept in
|
|
319
|
+
// memory and in the entry, so that a failure now does not make the next flush append the leaf again.
|
|
320
|
+
appended.set(receiptId, entry);
|
|
321
|
+
try {
|
|
322
|
+
writeDurable(file, JSON.stringify({ envelope, appended: entry }));
|
|
323
|
+
}
|
|
324
|
+
catch (e) {
|
|
325
|
+
errors.push(`receipt ${receiptId} is in the log, but its outbox entry could not record that: ${e instanceof Error ? e.message : String(e)}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
await writeBundle(receiptId, statement.predicate, { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion });
|
|
329
|
+
rmSync(file, { force: true });
|
|
330
|
+
appended.delete(receiptId);
|
|
331
|
+
sent++;
|
|
332
|
+
try {
|
|
333
|
+
utimesSync(lockFile, new Date(), new Date());
|
|
334
|
+
}
|
|
335
|
+
catch { /* the lock is only a hint */ }
|
|
336
|
+
}
|
|
337
|
+
catch (e) {
|
|
338
|
+
if (e.code === "ENOENT" && !existsSync(file))
|
|
339
|
+
continue;
|
|
340
|
+
errors.push(`outbox entry ${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return done();
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
release();
|
|
347
|
+
}
|
|
348
|
+
})().finally(() => { flushing = undefined; });
|
|
349
|
+
return flushing;
|
|
350
|
+
},
|
|
100
351
|
};
|
|
101
352
|
}
|
package/dist/log-store.d.ts
CHANGED
|
@@ -88,7 +88,7 @@ export interface AuditEntry {
|
|
|
88
88
|
id: number;
|
|
89
89
|
at: string;
|
|
90
90
|
actor: string;
|
|
91
|
-
action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke" | "policy.add" | "policy.remove";
|
|
91
|
+
action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke" | "policy.add" | "policy.remove" | "sso.set" | "sso.remove" | "user.mfa-reset";
|
|
92
92
|
tenantId: string | null;
|
|
93
93
|
detail: Record<string, unknown>;
|
|
94
94
|
}
|
|
@@ -116,7 +116,8 @@ export declare class PostgresTenancy {
|
|
|
116
116
|
quotas?: Partial<Record<Plan, number | null>>;
|
|
117
117
|
});
|
|
118
118
|
private init;
|
|
119
|
-
|
|
119
|
+
/** Writes one audit entry. `detail` never holds a secret or a token. */
|
|
120
|
+
record(actor: string | undefined, action: AuditEntry["action"], tenantId: string | null, detail: Record<string, unknown>): Promise<void>;
|
|
120
121
|
/** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
|
|
121
122
|
audit(opts?: {
|
|
122
123
|
tenant?: string;
|
package/dist/log-store.js
CHANGED
|
@@ -204,7 +204,9 @@ export class PostgresTenancy {
|
|
|
204
204
|
}
|
|
205
205
|
return this.ready;
|
|
206
206
|
}
|
|
207
|
+
/** Writes one audit entry. `detail` never holds a secret or a token. */
|
|
207
208
|
async record(actor, action, tenantId, detail) {
|
|
209
|
+
await this.init();
|
|
208
210
|
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)]);
|
|
209
211
|
}
|
|
210
212
|
/** Administrative actions, newest first; for one tenant when given. What the admin page shows and a tenant's export carries. */
|
package/dist/policy.d.ts
CHANGED
|
@@ -14,6 +14,10 @@ export interface PolicyRequest {
|
|
|
14
14
|
/** Cedar context. Numbers must be integers; Cedar has no floats. */
|
|
15
15
|
context: Record<string, unknown>;
|
|
16
16
|
}
|
|
17
|
+
/** True when the policy set contains a permit rule. Cedar answers, so a `permit(` in a comment does not count. */
|
|
18
|
+
export declare function hasPermitRule(policyText: string): boolean;
|
|
19
|
+
/** Why Cedar cannot parse the policy set, or an empty list when it can. */
|
|
20
|
+
export declare function policyParseErrors(policyText: string): string[];
|
|
17
21
|
export declare function policyDigest(policyText: string): string;
|
|
18
22
|
/**
|
|
19
23
|
* Cedar's JSON context reads `{ "__entity": … }` and `{ "__extn": … }` as typed values. Arguments come from the agent,
|
package/dist/policy.js
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
// Cedar policy evaluation. Fails closed: any evaluation error is a deny.
|
|
2
2
|
import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
|
|
3
3
|
import { sha256Hex } from "./crypto.js";
|
|
4
|
+
/** True when the policy set contains a permit rule. Cedar answers, so a `permit(` in a comment does not count. */
|
|
5
|
+
export function hasPermitRule(policyText) {
|
|
6
|
+
const parts = cedar.policySetTextToParts(policyText);
|
|
7
|
+
if (parts.type !== "success")
|
|
8
|
+
return false;
|
|
9
|
+
return parts.policies.some((p) => {
|
|
10
|
+
const j = cedar.policyToJson(p);
|
|
11
|
+
return j.type === "success" && j.json.effect === "permit";
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** Why Cedar cannot parse the policy set, or an empty list when it can. */
|
|
15
|
+
export function policyParseErrors(policyText) {
|
|
16
|
+
const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
|
|
17
|
+
return parsed.type === "success" ? [] : parsed.errors.map((e) => e.message);
|
|
18
|
+
}
|
|
4
19
|
export function policyDigest(policyText) {
|
|
5
20
|
return sha256Hex(policyText);
|
|
6
21
|
}
|
package/dist/portal.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
2
|
import { type PostgresLike, type PostgresTenancy } from "./log-store.ts";
|
|
3
|
+
import { type OidcConfig, type SamlConfig, type SsoIdentity } from "./sso.ts";
|
|
3
4
|
export interface StripeOptions {
|
|
4
5
|
secretKey: string;
|
|
5
6
|
webhookSecret: string;
|
|
@@ -46,6 +47,8 @@ export interface PortalOptions {
|
|
|
46
47
|
stripe?: StripeOptions;
|
|
47
48
|
mail?: MailOptions;
|
|
48
49
|
oauth?: OAuthOptions;
|
|
50
|
+
/** the fetch for OIDC discovery, keys, and tokens; the global one by default */
|
|
51
|
+
ssoFetch?: typeof fetch;
|
|
49
52
|
/** key throttles by X-Forwarded-For; only behind a proxy you run. Also marks cookies Secure. */
|
|
50
53
|
trustProxy?: boolean;
|
|
51
54
|
/** table prefix; default portal_ */
|
|
@@ -64,6 +67,18 @@ export declare class UnverifiedAccountError extends Error {
|
|
|
64
67
|
email: string;
|
|
65
68
|
constructor(email: string);
|
|
66
69
|
}
|
|
70
|
+
/** A single sign-on identity that the tenant's rules refuse: another domain, or an account in another tenant. */
|
|
71
|
+
export declare class SsoRefusedError extends Error {
|
|
72
|
+
}
|
|
73
|
+
/** One tenant's enterprise identity provider. Set by the operator only, because an IdP is trusted for the domains that the operator checked. */
|
|
74
|
+
export interface SsoSetting {
|
|
75
|
+
tenant: string;
|
|
76
|
+
protocol: "oidc" | "saml";
|
|
77
|
+
config: OidcConfig | SamlConfig;
|
|
78
|
+
domains: string[];
|
|
79
|
+
defaultRole: Role;
|
|
80
|
+
enforced: boolean;
|
|
81
|
+
}
|
|
67
82
|
/** Users, memberships, and billing records, beside the log's tables. */
|
|
68
83
|
/** What a registration says about the person and the organisation; every field optional in the store, the route decides what it requires. */
|
|
69
84
|
export interface Profile {
|
|
@@ -73,6 +88,13 @@ export interface Profile {
|
|
|
73
88
|
phone?: string | null;
|
|
74
89
|
telegram?: string | null;
|
|
75
90
|
}
|
|
91
|
+
/** Lowest first. */
|
|
92
|
+
export declare const ROLES: readonly ["readonly", "reviewer", "admin", "owner"];
|
|
93
|
+
export type Role = (typeof ROLES)[number];
|
|
94
|
+
export declare const base32: (b: Buffer) => string;
|
|
95
|
+
export declare function totp(key: Buffer, step: number): string;
|
|
96
|
+
/** The time step the code matches, one step either side of now allowed; null when none. */
|
|
97
|
+
export declare function totpStep(key: Buffer, code: string, now?: number): number | null;
|
|
76
98
|
export declare class PortalStore {
|
|
77
99
|
private readonly client;
|
|
78
100
|
private readonly p;
|
|
@@ -115,7 +137,56 @@ export declare class PortalStore {
|
|
|
115
137
|
findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
|
|
116
138
|
authenticate(email: string, password: string): Promise<PortalUser | null>;
|
|
117
139
|
user(id: string): Promise<PortalUser | null>;
|
|
118
|
-
addMember(userId: string, tenantId: string): Promise<void>;
|
|
140
|
+
addMember(userId: string, tenantId: string, role?: Role): Promise<void>;
|
|
141
|
+
roleOf(userId: string, tenantId: string): Promise<Role | null>;
|
|
142
|
+
members(tenantId: string): Promise<{
|
|
143
|
+
id: string;
|
|
144
|
+
email: string;
|
|
145
|
+
role: Role;
|
|
146
|
+
joinedAt: string;
|
|
147
|
+
mfa: boolean;
|
|
148
|
+
}[]>;
|
|
149
|
+
setRole(tenantId: string, userId: string, role: Role): Promise<boolean>;
|
|
150
|
+
removeMember(tenantId: string, userId: string): Promise<boolean>;
|
|
151
|
+
invite(tenantId: string, email: string, role: Role, by: string): Promise<void>;
|
|
152
|
+
invitesOf(tenantId: string): Promise<{
|
|
153
|
+
email: string;
|
|
154
|
+
role: Role;
|
|
155
|
+
invitedBy: string;
|
|
156
|
+
createdAt: string;
|
|
157
|
+
}[]>;
|
|
158
|
+
invitesFor(email: string): Promise<{
|
|
159
|
+
tenant: string;
|
|
160
|
+
role: Role;
|
|
161
|
+
}[]>;
|
|
162
|
+
removeInvite(tenantId: string, email: string): Promise<boolean>;
|
|
163
|
+
takeInvite(tenantId: string, email: string): Promise<Role | null>;
|
|
164
|
+
mfa(userId: string): Promise<{
|
|
165
|
+
secret: string | null;
|
|
166
|
+
enabled: boolean;
|
|
167
|
+
}>;
|
|
168
|
+
setMfaSecret(userId: string, secretHex: string): Promise<boolean>;
|
|
169
|
+
/** False when this step or a later one was used already. */
|
|
170
|
+
takeMfaStep(userId: string, step: number): Promise<boolean>;
|
|
171
|
+
enableMfa(userId: string): Promise<void>;
|
|
172
|
+
resetMfa(email: string): Promise<boolean>;
|
|
173
|
+
/** Replaces the tenant's setting. A domain belongs to one tenant, so a domain that another tenant holds is refused. */
|
|
174
|
+
setSso(s: SsoSetting): Promise<void>;
|
|
175
|
+
private ssoWhere;
|
|
176
|
+
ssoOf(tenant: string): Promise<SsoSetting | null>;
|
|
177
|
+
ssoByDomain(domain: string): Promise<SsoSetting | null>;
|
|
178
|
+
removeSso(tenant: string): Promise<boolean>;
|
|
179
|
+
/**
|
|
180
|
+
* The account behind an identity that the tenant's IdP vouched for: the linked one; else the account with that
|
|
181
|
+
* email, linked from now on, if it verified its address; else a new verified account with a random password.
|
|
182
|
+
* The IdP proves the address, so an account that never verified it loses the address: the account goes, with its
|
|
183
|
+
* password, its sessions, and its links. A tenant that it owned stays for the operator. There are two exceptions: an
|
|
184
|
+
* unverified member of this same tenant, who verifies by password first (UnverifiedAccountError), and an
|
|
185
|
+
* unverified member of another tenant that has other members, who is refused. An account with
|
|
186
|
+
* no tenant joins with the default role. A member that an admin removed joins again only through a new invite,
|
|
187
|
+
* with the invited role.
|
|
188
|
+
*/
|
|
189
|
+
findOrCreateSsoUser(s: SsoSetting, id: SsoIdentity): Promise<PortalUser>;
|
|
119
190
|
/** the user's tenant; one per account today */
|
|
120
191
|
tenantOf(userId: string): Promise<string | null>;
|
|
121
192
|
setBilling(tenantId: string, b: {
|
|
@@ -134,7 +205,7 @@ export declare class PortalStore {
|
|
|
134
205
|
stripeEventSeen(id: string): Promise<boolean>;
|
|
135
206
|
/** Records a Stripe event id as applied, after it was applied, so a failure before this point lets Stripe's retry through. */
|
|
136
207
|
noteStripeEvent(id: string): Promise<void>;
|
|
137
|
-
/** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
|
|
208
|
+
/** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. Owners only. */
|
|
138
209
|
registrations(): Promise<({
|
|
139
210
|
tenantId: string;
|
|
140
211
|
email: string;
|
|
@@ -143,8 +214,11 @@ export declare class PortalStore {
|
|
|
143
214
|
} & Profile)[]>;
|
|
144
215
|
tenantBySubscription(subscriptionId: string): Promise<string | null>;
|
|
145
216
|
}
|
|
146
|
-
|
|
147
|
-
export declare function
|
|
217
|
+
/** `via` records how the user signed in, for example `sso:acme`. */
|
|
218
|
+
export declare function signSession(secret: string, userId: string, ttlMs?: number, via?: string): string;
|
|
219
|
+
export declare const readSession: (secret: string, cookie: string | undefined) => string | null;
|
|
220
|
+
/** The `via` of a valid session, or null. */
|
|
221
|
+
export declare const readSessionVia: (secret: string, cookie: string | undefined) => string | null;
|
|
148
222
|
export declare function stripeRequest(s: StripeOptions, path: string, body: Record<string, string>): Promise<Record<string, unknown>>;
|
|
149
223
|
/** Stripe-Signature: t=<unix>,v1=<hmac>; the mac is over `${t}.${rawBody}` with the endpoint secret. */
|
|
150
224
|
export declare function verifyStripeSignature(header: string | undefined, rawBody: string, secret: string, now?: number, toleranceMs?: number): boolean;
|