@tnunamak/dalan 0.0.0-stage → 0.6.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/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
package/src/as-store.mjs
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { randomInt, randomUUID, randomBytes, createCipheriv, createDecipheriv, createHmac } from 'node:crypto';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { errors } from 'oidc-provider';
|
|
7
|
+
import { isLoopbackCallback, PAIRING_MINUTES } from './as-files.mjs';
|
|
8
|
+
|
|
9
|
+
// Storage of the built-in authorization server. One SQLite file (WAL, synchronous FULL) holds
|
|
10
|
+
// oidc every oidc-provider model, through the adapter below
|
|
11
|
+
// static_clients markers for owner-created Client rows, which are not subject to stale DCR cleanup
|
|
12
|
+
// connections the owner-approved connections (the bridge's authority record)
|
|
13
|
+
// pairings one row per browser interaction that wants a connection
|
|
14
|
+
// windows the open pairing window (at most one row)
|
|
15
|
+
// Statements are synchronous, so a single statement or a BEGIN IMMEDIATE block is atomic inside this process.
|
|
16
|
+
const CLOCK_TOLERANCE_S = 15; // the provider's default clockTolerance; consumed and expired records live this much longer
|
|
17
|
+
export const LIMITS = Object.freeze({ clients: 100, staleClientMs: 24 * 3600 * 1000 });
|
|
18
|
+
const GRANTABLE = ['AccessToken', 'AuthorizationCode', 'RefreshToken'];
|
|
19
|
+
const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O/1/I
|
|
20
|
+
|
|
21
|
+
import { normalizeCode } from './as-files.mjs';
|
|
22
|
+
export { normalizeCode } from './as-files.mjs';
|
|
23
|
+
const showCode = code => `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
24
|
+
|
|
25
|
+
// Opens one sealed value. The restore check calls this with the same logic the store uses at startup.
|
|
26
|
+
export function openAsValue(key, value, context) {
|
|
27
|
+
try {
|
|
28
|
+
const [version, nonce, tag, data, extra] = value.split('.');
|
|
29
|
+
if (version !== 'v1' || extra !== undefined || !nonce || !tag || data === undefined) throw new Error();
|
|
30
|
+
const iv = Buffer.from(nonce, 'base64url'), auth = Buffer.from(tag, 'base64url');
|
|
31
|
+
if (iv.length !== 12 || auth.length !== 16) throw new Error();
|
|
32
|
+
const cipher = createDecipheriv('aes-256-gcm', key, iv); cipher.setAuthTag(auth); cipher.setAAD(Buffer.from(context));
|
|
33
|
+
return Buffer.concat([cipher.update(Buffer.from(data, 'base64url')), cipher.final()]).toString('utf8');
|
|
34
|
+
} catch { throw new Error('as: encrypted storage is damaged or its key is invalid'); }
|
|
35
|
+
}
|
|
36
|
+
export class AsStore {
|
|
37
|
+
constructor(file, { now = Date.now, limits = { registrations: 5, interactions: 5 } } = {}) {
|
|
38
|
+
this.now = now;
|
|
39
|
+
this.file = file;
|
|
40
|
+
this.limits = limits;
|
|
41
|
+
this.admission = new AsyncLocalStorage();
|
|
42
|
+
this.refreshExchange = new AsyncLocalStorage();
|
|
43
|
+
// Create the file with mode 0600 before SQLite sees it; WAL and shared-memory files copy the mode of the main file.
|
|
44
|
+
fs.closeSync(fs.openSync(file, 'a', 0o600));
|
|
45
|
+
fs.chmodSync(file, 0o600);
|
|
46
|
+
this.db = new DatabaseSync(file);
|
|
47
|
+
this.db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON;');
|
|
48
|
+
this.db.exec(`
|
|
49
|
+
CREATE TABLE IF NOT EXISTS oidc(
|
|
50
|
+
model TEXT NOT NULL, id TEXT NOT NULL, payload TEXT NOT NULL, grant_id TEXT, uid TEXT, user_code TEXT,
|
|
51
|
+
consumed INTEGER, created_at INTEGER NOT NULL, expires_at INTEGER, PRIMARY KEY(model,id)) WITHOUT ROWID;
|
|
52
|
+
CREATE INDEX IF NOT EXISTS oidc_grant ON oidc(grant_id) WHERE grant_id IS NOT NULL;
|
|
53
|
+
CREATE INDEX IF NOT EXISTS oidc_uid ON oidc(model,uid) WHERE uid IS NOT NULL;
|
|
54
|
+
CREATE INDEX IF NOT EXISTS oidc_user_code ON oidc(model,user_code) WHERE user_code IS NOT NULL;
|
|
55
|
+
CREATE INDEX IF NOT EXISTS oidc_expiry ON oidc(expires_at) WHERE expires_at IS NOT NULL;
|
|
56
|
+
CREATE TABLE IF NOT EXISTS refresh_receipts(
|
|
57
|
+
grant_id TEXT PRIMARY KEY, token_id TEXT NOT NULL, deadline INTEGER NOT NULL, payload TEXT NOT NULL) WITHOUT ROWID;
|
|
58
|
+
CREATE TABLE IF NOT EXISTS static_clients(client_id TEXT PRIMARY KEY) WITHOUT ROWID;
|
|
59
|
+
CREATE TABLE IF NOT EXISTS connections(
|
|
60
|
+
connection_id TEXT PRIMARY KEY, worker TEXT NOT NULL, grant_id TEXT NOT NULL UNIQUE, client_id TEXT NOT NULL,
|
|
61
|
+
redirect_uri TEXT NOT NULL, resource TEXT NOT NULL, scopes TEXT NOT NULL, created_at INTEGER NOT NULL,
|
|
62
|
+
revoked_at INTEGER, revoked_reason TEXT);
|
|
63
|
+
CREATE UNIQUE INDEX IF NOT EXISTS connections_one_active ON connections(worker) WHERE revoked_at IS NULL;
|
|
64
|
+
CREATE TABLE IF NOT EXISTS pairings(
|
|
65
|
+
code TEXT PRIMARY KEY, uid TEXT NOT NULL UNIQUE, worker TEXT NOT NULL, client_id TEXT NOT NULL, client_name TEXT,
|
|
66
|
+
redirect_uri TEXT NOT NULL, resource TEXT NOT NULL, scopes TEXT NOT NULL, created_at INTEGER NOT NULL,
|
|
67
|
+
expires_at INTEGER NOT NULL, state TEXT NOT NULL CHECK(state IN ('pending','approving','approved','done','failed')),
|
|
68
|
+
grant_id TEXT, connection_id TEXT);
|
|
69
|
+
CREATE TABLE IF NOT EXISTS windows(id INTEGER PRIMARY KEY CHECK(id=1), worker TEXT NOT NULL, opened_at INTEGER NOT NULL, expires_at INTEGER NOT NULL);
|
|
70
|
+
`);
|
|
71
|
+
const columns = this.db.prepare('PRAGMA table_info(windows)').all().map(c => c.name);
|
|
72
|
+
if (!columns.includes('registrations')) this.db.exec('ALTER TABLE windows ADD COLUMN registrations INTEGER NOT NULL DEFAULT 0');
|
|
73
|
+
if (!columns.includes('generation')) this.db.exec('ALTER TABLE windows ADD COLUMN generation TEXT');
|
|
74
|
+
try { this.#initializeCodec(); } catch { this.db.close(); throw new Error('as: encrypted storage could not be opened'); }
|
|
75
|
+
this.onGrantRevoked = () => {};
|
|
76
|
+
const self = this;
|
|
77
|
+
// oidc-provider builds one adapter object for each model name.
|
|
78
|
+
this.Adapter = class SqliteAdapter {
|
|
79
|
+
constructor(model) { this.model = model; }
|
|
80
|
+
async upsert(id, payload, expiresIn) {
|
|
81
|
+
const exchange = self.refreshExchange.getStore();
|
|
82
|
+
if (exchange && ['RefreshToken', 'AccessToken'].includes(this.model)) exchange.writes.push(['upsert', this.model, id, payload, expiresIn]);
|
|
83
|
+
else self.upsert(this.model, id, payload, expiresIn);
|
|
84
|
+
}
|
|
85
|
+
async find(id) {
|
|
86
|
+
const result = await self.find(this.model, id);
|
|
87
|
+
if (this.model === 'AuthorizationCode' && result?.consumed) self.consume(this.model, id);
|
|
88
|
+
const exchange = self.refreshExchange.getStore();
|
|
89
|
+
if (exchange && ['RefreshToken', 'Grant'].includes(this.model)) {
|
|
90
|
+
exchange.reads.push([this.model, id, JSON.stringify(result)]);
|
|
91
|
+
if (this.model === 'RefreshToken' && id === exchange.retryToken && result?.consumed) {
|
|
92
|
+
const copy = { ...result }; delete copy.consumed; return copy;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
async findByUid(uid) { return self.findBy(this.model, 'uid', uid); }
|
|
98
|
+
async findByUserCode(userCode) { return self.findBy(this.model, 'user_code', userCode); }
|
|
99
|
+
async destroy(id) { self.db.prepare('DELETE FROM oidc WHERE model=? AND id=?').run(this.model, self.#id(this.model, id)); }
|
|
100
|
+
async revokeByGrantId(grantId) { self.deleteByGrant(grantId, this.model); }
|
|
101
|
+
async consume(id) {
|
|
102
|
+
const exchange = self.refreshExchange.getStore();
|
|
103
|
+
if (exchange && this.model === 'RefreshToken') exchange.writes.push(['consume', this.model, id]);
|
|
104
|
+
else self.consume(this.model, id);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The key never enters SQLite. The marker makes a lost key distinguishable from a legacy database.
|
|
110
|
+
#initializeCodec() {
|
|
111
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS as_storage_meta (id INTEGER PRIMARY KEY CHECK(id=1), state TEXT NOT NULL, verifier TEXT NOT NULL)');
|
|
112
|
+
const marker = this.db.prepare('SELECT state,verifier FROM as_storage_meta WHERE id=1').get();
|
|
113
|
+
const keyFile = path.join(path.dirname(this.file), 'as-storage.key');
|
|
114
|
+
const dirStat = fs.statSync(path.dirname(keyFile));
|
|
115
|
+
if (!dirStat.isDirectory() || (dirStat.mode & 0o077) !== 0 || (typeof process.getuid === 'function' && dirStat.uid !== process.getuid())) throw new Error('as: storage directory permissions are invalid');
|
|
116
|
+
// Ownership excludes another publisher. Remove only our private, regular temporary key files.
|
|
117
|
+
for (const name of fs.readdirSync(path.dirname(keyFile))) {
|
|
118
|
+
if (!/^\.as-storage-key-[a-f0-9]{32}\.tmp$/.test(name)) continue;
|
|
119
|
+
const temp = path.join(path.dirname(keyFile), name), stat = fs.lstatSync(temp);
|
|
120
|
+
if (stat.isFile() && (stat.mode & 0o777) === 0o600 && (typeof process.getuid !== 'function' || stat.uid === process.getuid())) fs.unlinkSync(temp);
|
|
121
|
+
}
|
|
122
|
+
if (!fs.existsSync(keyFile)) {
|
|
123
|
+
if (marker) throw new Error('as: storage key is missing');
|
|
124
|
+
const temp = path.join(path.dirname(keyFile), `.as-storage-key-${randomBytes(16).toString('hex')}.tmp`);
|
|
125
|
+
try {
|
|
126
|
+
const fd = fs.openSync(temp, 'wx', 0o600);
|
|
127
|
+
try { fs.writeFileSync(fd, randomBytes(32)); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
128
|
+
// A hard link publishes a complete key atomically and never replaces an existing key.
|
|
129
|
+
fs.linkSync(temp, keyFile);
|
|
130
|
+
const dir = fs.openSync(path.dirname(keyFile), 'r');
|
|
131
|
+
try { fs.fsyncSync(dir); } finally { fs.closeSync(dir); }
|
|
132
|
+
} finally { fs.rmSync(temp, { force: true }); }
|
|
133
|
+
}
|
|
134
|
+
const stat = fs.lstatSync(keyFile);
|
|
135
|
+
if (!stat.isFile() || (stat.mode & 0o777) !== 0o600 || (dirStat.mode & 0o077) !== 0 || (typeof process.getuid === 'function' && (stat.uid !== process.getuid() || dirStat.uid !== process.getuid()))) throw new Error('as: storage key or directory permissions are invalid');
|
|
136
|
+
this.key = fs.readFileSync(keyFile);
|
|
137
|
+
if (this.key.length !== 32) throw new Error('as: storage key is invalid');
|
|
138
|
+
// Recovery may see a complete link whose publication was interrupted before fsync.
|
|
139
|
+
// Make that directory entry durable before committing any encrypted state.
|
|
140
|
+
const keyDir = fs.openSync(path.dirname(keyFile), 'r');
|
|
141
|
+
try { fs.fsyncSync(keyDir); } finally { fs.closeSync(keyDir); }
|
|
142
|
+
if (marker) {
|
|
143
|
+
if (this.#open(marker.verifier, 'verifier') !== 'dot-bridge storage v1') throw new Error('as: storage key is invalid');
|
|
144
|
+
if (!['cleanup', 'ready'].includes(marker.state)) throw new Error('as: storage state is invalid');
|
|
145
|
+
} else {
|
|
146
|
+
this.tx(() => {
|
|
147
|
+
for (const row of this.db.prepare('SELECT model,id,payload,uid,user_code FROM oidc').all()) {
|
|
148
|
+
JSON.parse(row.payload);
|
|
149
|
+
this.db.prepare('UPDATE oidc SET id=?,payload=?,uid=?,user_code=? WHERE model=? AND id=?').run(this.#id(row.model, row.id), this.#seal(row.payload, `oidc:${row.model}:${this.#id(row.model, row.id)}`), this.#lookup('uid', row.uid), this.#lookup('user_code', row.user_code), row.model, row.id);
|
|
150
|
+
}
|
|
151
|
+
for (const table of ['connections', 'pairings']) {
|
|
152
|
+
const key = table === 'connections' ? 'connection_id' : 'code';
|
|
153
|
+
for (const row of this.db.prepare(`SELECT ${key} AS id,resource FROM ${table}`).all()) this.db.prepare(`UPDATE ${table} SET resource=? WHERE ${key}=?`).run(this.#seal(row.resource, `${table}:${row.id}`), row.id);
|
|
154
|
+
}
|
|
155
|
+
this.db.prepare("INSERT INTO as_storage_meta VALUES(1,'cleanup',?)").run(this.#seal('dot-bridge storage v1', 'verifier'));
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
// Validate all ciphertext at startup, even rows that are not currently in use.
|
|
159
|
+
for (const row of this.db.prepare('SELECT model,id,payload FROM oidc').all()) JSON.parse(this.#open(row.payload, `oidc:${row.model}:${row.id}`));
|
|
160
|
+
for (const table of ['connections', 'pairings']) {
|
|
161
|
+
const key = table === 'connections' ? 'connection_id' : 'code';
|
|
162
|
+
for (const row of this.db.prepare(`SELECT ${key} AS id,resource FROM ${table}`).all()) this.#open(row.resource, `${table}:${row.id}`);
|
|
163
|
+
}
|
|
164
|
+
if (!marker || marker.state === 'cleanup') {
|
|
165
|
+
this.#checkpoint();
|
|
166
|
+
this.db.exec('VACUUM');
|
|
167
|
+
this.#checkpoint();
|
|
168
|
+
this.db.prepare("UPDATE as_storage_meta SET state='ready' WHERE id=1").run();
|
|
169
|
+
this.#checkpoint();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
#checkpoint() {
|
|
173
|
+
const result = this.db.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get();
|
|
174
|
+
if (result.busy) throw new Error('as: storage checkpoint is busy');
|
|
175
|
+
}
|
|
176
|
+
#seal(value, context) {
|
|
177
|
+
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', this.key, iv);
|
|
178
|
+
cipher.setAAD(Buffer.from(context));
|
|
179
|
+
const data = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
|
180
|
+
return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join('.');
|
|
181
|
+
}
|
|
182
|
+
#open(value, context) { return openAsValue(this.key, value, context); }
|
|
183
|
+
#lookup(domain, value) { return value == null ? null : createHmac('sha256', this.key).update(domain).update('\0').update(value).digest('base64url'); }
|
|
184
|
+
#id(model, id) { return ['Client', 'Grant', 'Interaction'].includes(model) ? id : this.#lookup(`id:${model}`, id); }
|
|
185
|
+
#resource(row) { return row ? { ...row, resource: this.#open(row.resource, row.connection_id && !row.code ? `connections:${row.connection_id}` : `pairings:${row.code}`) } : row; }
|
|
186
|
+
|
|
187
|
+
close() { this.db.close(); }
|
|
188
|
+
tx(fn) {
|
|
189
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
190
|
+
try { const out = fn(); this.db.exec('COMMIT'); return out; } catch (error) { this.db.exec('ROLLBACK'); throw error; }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
refreshReceipt(token) {
|
|
194
|
+
const tokenId = this.#id('RefreshToken', token);
|
|
195
|
+
const row = this.db.prepare('SELECT * FROM refresh_receipts WHERE token_id=?').get(tokenId);
|
|
196
|
+
if (!row || row.deadline <= this.now()) return undefined;
|
|
197
|
+
return { ...row, value: JSON.parse(this.#open(row.payload, `refresh-receipt:${row.grant_id}`)) };
|
|
198
|
+
}
|
|
199
|
+
refreshValid(grantId, clientId, successor) {
|
|
200
|
+
const connection = this.connectionByGrant(grantId);
|
|
201
|
+
const grant = this.find('Grant', grantId);
|
|
202
|
+
const token = this.find('RefreshToken', successor);
|
|
203
|
+
return !!(connection && connection.revoked_at === null && connection.client_id === clientId && grant &&
|
|
204
|
+
grant.clientId === clientId && grant.exp * 1000 > Date.now() && token && !token.consumed && token.grantId === grantId && token.clientId === clientId && token.exp * 1000 > Date.now());
|
|
205
|
+
}
|
|
206
|
+
commitFailedRefresh(exchange) {
|
|
207
|
+
this.tx(() => {
|
|
208
|
+
for (const [model, id, original] of exchange.reads) {
|
|
209
|
+
if (JSON.stringify(this.find(model, id)) !== original) throw new errors.InvalidGrant('refresh state changed');
|
|
210
|
+
}
|
|
211
|
+
for (const [op, model, id] of exchange.writes) if (op === 'consume') this.consume(model, id);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
commitRefresh(exchange, grantId, clientId, token, params, response, deadline) {
|
|
215
|
+
this.tx(() => {
|
|
216
|
+
for (const [model, id, original] of exchange.reads) {
|
|
217
|
+
if (JSON.stringify(this.find(model, id)) !== original) throw new errors.InvalidGrant('refresh state changed');
|
|
218
|
+
}
|
|
219
|
+
const connection = this.connectionByGrant(grantId);
|
|
220
|
+
const grant = this.find('Grant', grantId);
|
|
221
|
+
if (!connection || connection.revoked_at !== null || connection.client_id !== clientId || !grant || grant.clientId !== clientId) throw new errors.InvalidGrant('grant inactive');
|
|
222
|
+
for (const [op, model, id, payload, ttl] of exchange.writes) {
|
|
223
|
+
if (op === 'consume') this.consume(model, id);
|
|
224
|
+
else this.upsert(model, id, payload, ttl);
|
|
225
|
+
}
|
|
226
|
+
this.db.prepare('DELETE FROM refresh_receipts WHERE deadline<=? OR grant_id=?').run(this.now(), grantId);
|
|
227
|
+
this.db.prepare('INSERT INTO refresh_receipts VALUES(?,?,?,?)').run(grantId, this.#id('RefreshToken', token), deadline,
|
|
228
|
+
this.#seal(JSON.stringify({ clientId, params, response }), `refresh-receipt:${grantId}`));
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ---- the oidc-provider adapter ---------------------------------------------------------------------------------
|
|
233
|
+
upsert(model, id, payload, expiresIn) {
|
|
234
|
+
const now = this.now();
|
|
235
|
+
if (['Client', 'Interaction'].includes(model) && !this.db.prepare('SELECT 1 FROM oidc WHERE model=? AND id=?').get(model, this.#id(model, id))) {
|
|
236
|
+
const window = this.window();
|
|
237
|
+
// A request that was parsing during reset or stop/start must not recreate cleared state.
|
|
238
|
+
if (!window || window.generation !== this.admission.getStore()) throw new errors.InvalidRequest('pairing window changed; retry', 403);
|
|
239
|
+
if (model === 'Client' && this.clientCount() >= LIMITS.clients) throw new errors.InvalidClientMetadata('the client registration limit is reached');
|
|
240
|
+
if (model === 'Interaction' && this.interactionsFull()) throw new errors.InvalidRequest('Too many connection attempts are waiting. Ask the owner to run dalan connect reset, then retry.', 503);
|
|
241
|
+
}
|
|
242
|
+
const expires = typeof expiresIn === 'number' ? now + (expiresIn + CLOCK_TOLERANCE_S) * 1000 : null;
|
|
243
|
+
const grantId = GRANTABLE.includes(model) || model === 'Grant' ? payload.grantId ?? null : null;
|
|
244
|
+
this.db.prepare(`INSERT INTO oidc(model,id,payload,grant_id,uid,user_code,consumed,created_at,expires_at) VALUES(?,?,?,?,?,?,NULL,?,?)
|
|
245
|
+
ON CONFLICT(model,id) DO UPDATE SET payload=excluded.payload,grant_id=excluded.grant_id,uid=excluded.uid,user_code=excluded.user_code,expires_at=excluded.expires_at`)
|
|
246
|
+
.run(model, this.#id(model, id), this.#seal(JSON.stringify(payload), `oidc:${model}:${this.#id(model, id)}`), grantId, this.#lookup('uid', payload.uid), this.#lookup('user_code', payload.userCode), now, expires);
|
|
247
|
+
}
|
|
248
|
+
#row(row) {
|
|
249
|
+
if (!row || (row.expires_at !== null && row.expires_at <= this.now())) return undefined;
|
|
250
|
+
const payload = JSON.parse(this.#open(row.payload, `oidc:${row.model}:${row.id}`));
|
|
251
|
+
if (row.consumed) payload.consumed = row.consumed;
|
|
252
|
+
return payload;
|
|
253
|
+
}
|
|
254
|
+
find(model, id) { return this.#row(this.db.prepare('SELECT * FROM oidc WHERE model=? AND id=?').get(model, this.#id(model, id))); }
|
|
255
|
+
findBy(model, column, value) {
|
|
256
|
+
if (!['uid', 'user_code'].includes(column)) throw new Error('bad column');
|
|
257
|
+
return this.#row(this.db.prepare(`SELECT * FROM oidc WHERE model=? AND ${column}=?`).get(model, this.#lookup(column, value)));
|
|
258
|
+
}
|
|
259
|
+
// Compare-and-set: exactly one caller marks a record consumed. A second caller is a replay: the whole grant is revoked.
|
|
260
|
+
consume(model, id) {
|
|
261
|
+
const done = this.db.prepare('UPDATE oidc SET consumed=? WHERE model=? AND id=? AND consumed IS NULL').run(Math.floor(this.now() / 1000), model, this.#id(model, id));
|
|
262
|
+
if (done.changes === 1) return;
|
|
263
|
+
const row = this.db.prepare('SELECT grant_id FROM oidc WHERE model=? AND id=?').get(model, this.#id(model, id));
|
|
264
|
+
if (row?.grant_id) this.revokeGrant(row.grant_id, 'replay');
|
|
265
|
+
throw new errors.InvalidGrant(`${model === 'AuthorizationCode' ? 'authorization code' : 'refresh token'} already consumed`);
|
|
266
|
+
}
|
|
267
|
+
deleteByGrant(grantId, model) { this.db.prepare('DELETE FROM oidc WHERE grant_id=? AND model=?').run(grantId, model); }
|
|
268
|
+
#revokeGrantRows(grantId, reason, now = this.now()) {
|
|
269
|
+
this.db.prepare('DELETE FROM oidc WHERE grant_id=?').run(grantId);
|
|
270
|
+
this.db.prepare("DELETE FROM oidc WHERE model='Grant' AND id=?").run(grantId);
|
|
271
|
+
this.db.prepare('UPDATE connections SET revoked_at=?,revoked_reason=? WHERE grant_id=? AND revoked_at IS NULL').run(now, reason, grantId);
|
|
272
|
+
}
|
|
273
|
+
// The one revocation path: tokens, codes and the Grant record go, and the connection row is marked. Idempotent.
|
|
274
|
+
revokeGrant(grantId, reason) {
|
|
275
|
+
this.tx(() => this.#revokeGrantRows(grantId, reason));
|
|
276
|
+
this.onGrantRevoked(grantId, reason);
|
|
277
|
+
}
|
|
278
|
+
addStaticClient(clientId, metadata) {
|
|
279
|
+
const now = this.now();
|
|
280
|
+
this.tx(() => {
|
|
281
|
+
if (this.clientCount() >= LIMITS.clients) throw new Error('the client registration limit is reached');
|
|
282
|
+
this.db.prepare('INSERT INTO oidc(model,id,payload,grant_id,uid,user_code,consumed,created_at,expires_at) VALUES(\'Client\',?,?,NULL,NULL,NULL,NULL,?,NULL)')
|
|
283
|
+
.run(clientId, this.#seal(JSON.stringify(metadata), `oidc:Client:${clientId}`), now);
|
|
284
|
+
this.db.prepare('INSERT INTO static_clients(client_id) VALUES(?)').run(clientId);
|
|
285
|
+
});
|
|
286
|
+
return now;
|
|
287
|
+
}
|
|
288
|
+
clientRows() {
|
|
289
|
+
return this.db.prepare(`SELECT c.id AS client_id,c.payload,c.created_at,CASE WHEN s.client_id IS NULL THEN 0 ELSE 1 END AS is_static
|
|
290
|
+
FROM oidc c LEFT JOIN static_clients s ON s.client_id=c.id WHERE c.model='Client' ORDER BY c.created_at,c.id`).all()
|
|
291
|
+
.map(row => ({ ...row, metadata: JSON.parse(this.#open(row.payload, `oidc:Client:${row.client_id}`)) }));
|
|
292
|
+
}
|
|
293
|
+
removeStaticClient(clientId) {
|
|
294
|
+
const grantIds = this.tx(() => {
|
|
295
|
+
if (!this.db.prepare('SELECT 1 FROM static_clients WHERE client_id=?').get(clientId)) throw new Error('client is not a static client');
|
|
296
|
+
const ids = new Set([
|
|
297
|
+
...this.db.prepare("SELECT id,payload FROM oidc WHERE model='Grant'").all().filter(row => JSON.parse(this.#open(row.payload, `oidc:Grant:${row.id}`)).clientId === clientId).map(row => row.id),
|
|
298
|
+
...this.db.prepare('SELECT grant_id AS id FROM connections WHERE client_id=? AND revoked_at IS NULL').all(clientId).map(row => row.id),
|
|
299
|
+
]);
|
|
300
|
+
const now = this.now();
|
|
301
|
+
for (const grantId of ids) this.#revokeGrantRows(grantId, 'client_removed', now);
|
|
302
|
+
this.db.prepare("DELETE FROM oidc WHERE model='Interaction' AND id IN (SELECT uid FROM pairings WHERE client_id=?)").run(clientId);
|
|
303
|
+
this.db.prepare("UPDATE pairings SET state='failed' WHERE client_id=? AND state IN ('pending','approving','approved')").run(clientId);
|
|
304
|
+
this.db.prepare("DELETE FROM oidc WHERE model='Client' AND id=?").run(clientId);
|
|
305
|
+
this.db.prepare('DELETE FROM static_clients WHERE client_id=?').run(clientId);
|
|
306
|
+
return [...ids];
|
|
307
|
+
});
|
|
308
|
+
for (const grantId of grantIds) this.onGrantRevoked(grantId, 'client_removed');
|
|
309
|
+
return { client_id: clientId, revoked_grants: grantIds.length };
|
|
310
|
+
}
|
|
311
|
+
purge() {
|
|
312
|
+
const now = this.now();
|
|
313
|
+
this.db.prepare('DELETE FROM refresh_receipts WHERE deadline<=?').run(now);
|
|
314
|
+
const expired = this.db.prepare('DELETE FROM oidc WHERE expires_at IS NOT NULL AND expires_at<=?').run(now).changes;
|
|
315
|
+
// Registered clients that never got a connection are dropped after a day: anonymous registration must not grow without bound.
|
|
316
|
+
const stale = this.db.prepare(`DELETE FROM oidc WHERE model='Client' AND created_at<? AND id NOT IN (SELECT client_id FROM static_clients) AND id NOT IN (SELECT client_id FROM connections)
|
|
317
|
+
AND id NOT IN (SELECT client_id FROM pairings WHERE state IN ('pending','approving','approved'))`).run(now - LIMITS.staleClientMs).changes;
|
|
318
|
+
this.db.prepare("DELETE FROM pairings WHERE (state IN ('done','failed') OR expires_at<=?) AND created_at<?").run(now, now - 24 * 3600 * 1000);
|
|
319
|
+
return { expired, stale_clients: stale };
|
|
320
|
+
}
|
|
321
|
+
clientCount() { return this.db.prepare("SELECT count(*) n FROM oidc WHERE model='Client'").get().n; }
|
|
322
|
+
|
|
323
|
+
// ---- pairing window --------------------------------------------------------------------------------------------
|
|
324
|
+
openWindow(worker, minutes) {
|
|
325
|
+
const now = this.now(), open = this.window();
|
|
326
|
+
if (open && open.worker !== worker) throw new Error(`a pairing window for ${open.worker} is open until ${new Date(open.expires_at).toISOString()}; stop it first`);
|
|
327
|
+
if (open) this.db.prepare('UPDATE windows SET expires_at=? WHERE id=1').run(now + minutes * 60000);
|
|
328
|
+
else this.db.prepare('INSERT INTO windows(id,worker,opened_at,expires_at,registrations,generation) VALUES(1,?,?,?,0,?) ON CONFLICT(id) DO UPDATE SET worker=excluded.worker,opened_at=excluded.opened_at,expires_at=excluded.expires_at,registrations=0,generation=excluded.generation')
|
|
329
|
+
.run(worker, now, now + minutes * 60000, randomUUID());
|
|
330
|
+
return this.window();
|
|
331
|
+
}
|
|
332
|
+
window() {
|
|
333
|
+
const row = this.db.prepare('SELECT * FROM windows WHERE id=1').get();
|
|
334
|
+
return row && row.expires_at > this.now() ? { ...row } : null;
|
|
335
|
+
}
|
|
336
|
+
// True when a window was opened and ran out; false when it is open, or was closed by the owner.
|
|
337
|
+
windowExpired() {
|
|
338
|
+
const row = this.db.prepare('SELECT expires_at FROM windows WHERE id=1').get();
|
|
339
|
+
return Boolean(row) && row.expires_at <= this.now();
|
|
340
|
+
}
|
|
341
|
+
closeWindow() { return this.db.prepare('DELETE FROM windows').run().changes; }
|
|
342
|
+
|
|
343
|
+
// Count attempts before reading DCR bodies, so concurrent and slow registrations cannot bypass the budget.
|
|
344
|
+
reserveRegistration() {
|
|
345
|
+
return this.db.prepare('UPDATE windows SET registrations=registrations+1 WHERE id=1 AND expires_at>? AND registrations<?')
|
|
346
|
+
.run(this.now(), this.limits.registrations).changes === 1;
|
|
347
|
+
}
|
|
348
|
+
reset() {
|
|
349
|
+
return this.tx(() => {
|
|
350
|
+
const result = this.#purgeUnapproved();
|
|
351
|
+
const clients = this.db.prepare(`DELETE FROM oidc WHERE model='Client' AND id NOT IN (SELECT client_id FROM static_clients)
|
|
352
|
+
AND id NOT IN (SELECT client_id FROM connections)
|
|
353
|
+
AND id NOT IN (SELECT client_id FROM pairings WHERE state IN ('approving','approved'))`).run().changes;
|
|
354
|
+
this.db.prepare('UPDATE windows SET registrations=0,generation=? WHERE id=1').run(randomUUID());
|
|
355
|
+
return { ...result, clients, window_open: !!this.window() };
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ---- pairings --------------------------------------------------------------------------------------------------
|
|
360
|
+
// Idempotent for one interaction: a page reload shows the same code.
|
|
361
|
+
interactionsFull() { return this.db.prepare("SELECT count(*) n FROM oidc WHERE model='Interaction' AND expires_at>?").get(this.now()).n >= this.limits.interactions; }
|
|
362
|
+
// Unapproved attempts (pending pairings and their interactions). Attempts being approved or already approved are kept.
|
|
363
|
+
purgeUnapproved() { return this.tx(() => this.#purgeUnapproved()); }
|
|
364
|
+
#purgeUnapproved() {
|
|
365
|
+
// A done pairing still needs its Interaction until the browser follows the provider's resume redirect.
|
|
366
|
+
const keep = "SELECT uid FROM pairings WHERE state IN ('approving','approved','done')";
|
|
367
|
+
const interactions = this.db.prepare(`DELETE FROM oidc WHERE model='Interaction' AND id NOT IN (${keep})`).run().changes;
|
|
368
|
+
const pairings = this.db.prepare("DELETE FROM pairings WHERE state='pending'").run().changes;
|
|
369
|
+
return { interactions, pairings };
|
|
370
|
+
}
|
|
371
|
+
pairingFor(uid, snapshot, window) {
|
|
372
|
+
const existing = this.db.prepare('SELECT * FROM pairings WHERE uid=?').get(uid);
|
|
373
|
+
if (existing) return this.#resource(existing);
|
|
374
|
+
const now = this.now();
|
|
375
|
+
if (this.db.prepare("SELECT count(*) n FROM pairings WHERE state='pending' AND expires_at>?").get(now).n >= this.limits.interactions) throw new Error('too many pending pairings');
|
|
376
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
377
|
+
const code = Array.from({ length: 8 }, () => ALPHABET[randomInt(ALPHABET.length)]).join('');
|
|
378
|
+
try {
|
|
379
|
+
this.db.prepare(`INSERT INTO pairings(code,uid,worker,client_id,client_name,redirect_uri,resource,scopes,created_at,expires_at,state)
|
|
380
|
+
VALUES(?,?,?,?,?,?,?,?,?,?, 'pending')`).run(code, uid, window.worker, snapshot.client_id, snapshot.client_name, snapshot.redirect_uri, this.#seal(snapshot.resource, `pairings:${code}`), snapshot.scopes, now, Math.min(snapshot.interaction_expires_at, now + PAIRING_MINUTES * 60000));
|
|
381
|
+
return this.#resource(this.db.prepare('SELECT * FROM pairings WHERE code=?').get(code));
|
|
382
|
+
} catch (error) { if (!/UNIQUE/.test(String(error.message))) throw error; }
|
|
383
|
+
}
|
|
384
|
+
throw new Error('could not allocate a pairing code');
|
|
385
|
+
}
|
|
386
|
+
pairingByCode(code) { return this.#resource(this.db.prepare('SELECT * FROM pairings WHERE code=?').get(normalizeCode(code))); }
|
|
387
|
+
pairingByUid(uid) { return this.#resource(this.db.prepare('SELECT * FROM pairings WHERE uid=?').get(uid)); }
|
|
388
|
+
pendingPairings() {
|
|
389
|
+
const now = this.now();
|
|
390
|
+
return this.db.prepare("SELECT * FROM pairings WHERE state='pending' AND expires_at>? ORDER BY created_at").all(now).map(row => this.#resource(row));
|
|
391
|
+
}
|
|
392
|
+
// Atomic reservation: exactly one approval wins a pending code, and it reserves only that code.
|
|
393
|
+
// A web pairing (https redirect to a fixed vendor) is refused while a newer web pairing is pending for the same worker:
|
|
394
|
+
// an app that registered again abandons its older attempts, and a re-registration reaches the same vendor.
|
|
395
|
+
// A native pairing (loopback redirect) is never refused for a newer attempt and never displaces another one: its
|
|
396
|
+
// redirect names no party, so a newer registrant must not take the owner's approval from an older teammate.
|
|
397
|
+
reserve(code) {
|
|
398
|
+
return this.tx(() => {
|
|
399
|
+
const now = this.now();
|
|
400
|
+
const row = this.db.prepare("SELECT rowid AS rid, * FROM pairings WHERE code=? AND state='pending' AND expires_at>?").get(code, now);
|
|
401
|
+
if (!row) return false;
|
|
402
|
+
if (!isLoopbackCallback(new URL(row.redirect_uri))) {
|
|
403
|
+
const newer = this.db.prepare("SELECT redirect_uri FROM pairings WHERE state='pending' AND expires_at>? AND worker=? AND rowid<>? AND (created_at>? OR (created_at=? AND rowid>?))")
|
|
404
|
+
.all(now, row.worker, row.rid, row.created_at, row.created_at, row.rid);
|
|
405
|
+
if (newer.some(p => !isLoopbackCallback(new URL(p.redirect_uri)))) return false;
|
|
406
|
+
}
|
|
407
|
+
return this.db.prepare("UPDATE pairings SET state='approving' WHERE code=? AND state='pending'").run(code).changes === 1;
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
failPairing(code) { this.db.prepare("UPDATE pairings SET state='failed' WHERE code=? AND state='approving'").run(code); }
|
|
411
|
+
// One transaction: the pairing becomes approved, the connection row appears, and (with replace) the old connection ends.
|
|
412
|
+
commitApproval({ code, worker, grantId, snapshot, replace }) {
|
|
413
|
+
return this.tx(() => {
|
|
414
|
+
const now = this.now();
|
|
415
|
+
// Removal and approval serialize here, so a delayed approval cannot recreate a connection after client removal.
|
|
416
|
+
if (!this.db.prepare("SELECT 1 FROM oidc WHERE model='Client' AND id=?").get(snapshot.client_id)) throw new Error('client was removed');
|
|
417
|
+
let replaced = null;
|
|
418
|
+
const active = this.db.prepare('SELECT * FROM connections WHERE worker=? AND revoked_at IS NULL').get(worker);
|
|
419
|
+
if (active) {
|
|
420
|
+
if (!replace) throw new Error(`worker ${worker} already has an active connection. Approving with --replace ends it and gives the new client every queued and future job for worker ${worker}, including briefs approved before the switch. Approve only a code you started yourself`);
|
|
421
|
+
this.db.prepare("UPDATE connections SET revoked_at=?,revoked_reason='replaced' WHERE connection_id=?").run(now, active.connection_id);
|
|
422
|
+
replaced = this.#resource(active);
|
|
423
|
+
}
|
|
424
|
+
const connectionId = randomUUID();
|
|
425
|
+
this.db.prepare('INSERT INTO connections(connection_id,worker,grant_id,client_id,redirect_uri,resource,scopes,created_at) VALUES(?,?,?,?,?,?,?,?)')
|
|
426
|
+
.run(connectionId, worker, grantId, snapshot.client_id, snapshot.redirect_uri, this.#seal(snapshot.resource, `connections:${connectionId}`), snapshot.scopes, now);
|
|
427
|
+
const done = this.db.prepare("UPDATE pairings SET state='approved',grant_id=?,connection_id=? WHERE code=? AND state='approving'").run(grantId, connectionId, code);
|
|
428
|
+
if (done.changes !== 1) throw new Error('pairing is no longer being approved');
|
|
429
|
+
return { connection_id: connectionId, replaced };
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
// The browser completes an approved pairing exactly once.
|
|
433
|
+
finishPairing(uid) {
|
|
434
|
+
return this.db.prepare("UPDATE pairings SET state='done' WHERE uid=? AND state='approved'").run(uid).changes === 1;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// ---- connections -----------------------------------------------------------------------------------------------
|
|
438
|
+
connectionByGrant(grantId) { return this.#resource(this.db.prepare('SELECT * FROM connections WHERE grant_id=?').get(grantId)); }
|
|
439
|
+
activeConnection(worker) { return this.#resource(this.db.prepare('SELECT * FROM connections WHERE worker=? AND revoked_at IS NULL').get(worker)); }
|
|
440
|
+
connectionIsLive(connectionId) {
|
|
441
|
+
if(typeof connectionId!=='string'||!connectionId) return false;
|
|
442
|
+
const connection=this.db.prepare('SELECT worker,grant_id,revoked_at FROM connections WHERE connection_id=?').get(connectionId);
|
|
443
|
+
if(!connection||connection.revoked_at!==null) return false;
|
|
444
|
+
const active=this.activeConnection(connection.worker);
|
|
445
|
+
if(active?.connection_id!==connectionId||active.grant_id!==connection.grant_id) return false;
|
|
446
|
+
const grant=this.db.prepare("SELECT expires_at FROM oidc WHERE model='Grant' AND id=?").get(connection.grant_id);
|
|
447
|
+
return !!grant&&(grant.expires_at===null||grant.expires_at>this.now());
|
|
448
|
+
}
|
|
449
|
+
liveConnectionIds(worker) {
|
|
450
|
+
return this.db.prepare('SELECT connection_id FROM connections WHERE worker=? AND revoked_at IS NULL ORDER BY connection_id').all(worker)
|
|
451
|
+
.map(row=>row.connection_id).filter(id=>this.connectionIsLive(id));
|
|
452
|
+
}
|
|
453
|
+
connections() { return this.db.prepare('SELECT * FROM connections ORDER BY created_at').all().map(row => this.#resource(row)); }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export { showCode };
|