@tpsdev-ai/flair 0.59.0 → 0.62.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 +4 -4
- package/SECURITY.md +36 -0
- package/config.yaml +12 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +991 -248
- package/dist/commands/agent.js +224 -43
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +592 -146
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +97 -35
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +41 -10
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +4 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +24 -0
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1168 -326
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +76 -12
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +321 -1
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +10 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +751 -143
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +110 -39
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +181 -63
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/auth-middleware.js +400 -161
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +72 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +120 -18
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +23 -6
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +128 -19
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +20 -11
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +4 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +146 -45
- package/docs/api-reference.md +46 -11
- package/docs/auth.md +6 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +5 -2
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +12 -6
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +10 -5
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +84 -5
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
package/dist/resources/OAuth.js
CHANGED
|
@@ -2,8 +2,12 @@ import { Resource, databases } from "harper";
|
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
import { handleJwtBearerGrant } from "./XAA.js";
|
|
4
4
|
import { resolveAgentAuth } from "./agent-auth.js";
|
|
5
|
+
import { claimOAuthSingleUse, oauthSingleUseDeps, reportReplayStoreGapsAtBoot, } from "./replay-store.js";
|
|
5
6
|
import { decideRegistration } from "./dcr-gate.js";
|
|
6
7
|
import { buildAuthorizationServerMetadata } from "./oauth-discovery.js";
|
|
8
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
9
|
+
import { withKeyLock } from "./key-lock.js";
|
|
10
|
+
import { withOwnedTransaction } from "./request-transaction.js";
|
|
7
11
|
import { esc } from "./admin-layout.js";
|
|
8
12
|
/**
|
|
9
13
|
* OAuth 2.1 Authorization Server for Flair.
|
|
@@ -31,6 +35,68 @@ const ALLOWED_REDIRECT_ORIGIN = new URL(ALLOWED_REDIRECT_URI).origin;
|
|
|
31
35
|
const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
|
|
32
36
|
const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
|
|
33
37
|
const AUTH_CODE_TTL_MS = 600_000; // 10 minutes
|
|
38
|
+
/**
|
|
39
|
+
* Seconds before a claim to redeem a code or rotate a refresh token may be
|
|
40
|
+
* removed (schemas/oauth.graphql: `expiration:` on `OAuthSingleUse`). MUST
|
|
41
|
+
* equal that value — both pinned by
|
|
42
|
+
* test/unit-isolated/oauth-single-use-2145.test.ts. It must outlive the longest
|
|
43
|
+
* either can be presented after its row is recorded: AUTH_CODE_TTL_MS, and
|
|
44
|
+
* REFRESH_TOKEN_TTL_MS.
|
|
45
|
+
*/
|
|
46
|
+
export const OAUTH_SINGLE_USE_RETENTION_S = 691_200; // 8 days
|
|
47
|
+
/**
|
|
48
|
+
* The longest a code or refresh token can be presented after its row is
|
|
49
|
+
* recorded (AUTH_CODE_TTL_MS for a code, REFRESH_TOKEN_TTL_MS for a refresh
|
|
50
|
+
* token): the store must outlive this, and the boot report names a table that
|
|
51
|
+
* does not.
|
|
52
|
+
*/
|
|
53
|
+
export const OAUTH_SINGLE_USE_MIN_RETENTION_MS = Math.max(AUTH_CODE_TTL_MS, REFRESH_TOKEN_TTL_MS);
|
|
54
|
+
// Once per worker thread at boot, with the replay guards' own report: a
|
|
55
|
+
// misconfigured OAuthSingleUse table is named before the first redemption.
|
|
56
|
+
export const OAUTH_SINGLE_USE_BOOT_STORE = {
|
|
57
|
+
label: "OAuth single-use",
|
|
58
|
+
deps: oauthSingleUseDeps,
|
|
59
|
+
minRetentionMs: OAUTH_SINGLE_USE_MIN_RETENTION_MS,
|
|
60
|
+
retentionBasis: "a redeemed authorization code or refresh token can be presented",
|
|
61
|
+
};
|
|
62
|
+
reportReplayStoreGapsAtBoot(OAUTH_SINGLE_USE_BOOT_STORE);
|
|
63
|
+
/** A store error: nothing is issued, and the caller may retry (fail closed). */
|
|
64
|
+
function storeUnavailable() {
|
|
65
|
+
return new Response(JSON.stringify({ error: "temporarily_unavailable", error_description: "replay_store_unavailable" }), {
|
|
66
|
+
status: 503,
|
|
67
|
+
headers: { "content-type": "application/json" },
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Within one Harper process, rotation and revoke share a per-refresh-token
|
|
72
|
+
* lock (resources/key-lock.ts). Rotation holds it across its claim, committed
|
|
73
|
+
* row re-read, write and issuance; revoke takes it before writing `revokedAt`.
|
|
74
|
+
*/
|
|
75
|
+
const OAUTH_TOKEN_LOCK_NAMESPACE = "flair-oauth-token";
|
|
76
|
+
/** The wait for the token's other holder: at most OAUTH_TOKEN_LOCK_ATTEMPTS × OAUTH_TOKEN_LOCK_WAIT_MS. */
|
|
77
|
+
const OAUTH_TOKEN_LOCK_ATTEMPTS = 200;
|
|
78
|
+
const OAUTH_TOKEN_LOCK_WAIT_MS = 10;
|
|
79
|
+
/** 503: this process's lock for this token's rotation and revoke stayed held. */
|
|
80
|
+
function tokenLifecycleBusy() {
|
|
81
|
+
return new Response(JSON.stringify({
|
|
82
|
+
error: "temporarily_unavailable",
|
|
83
|
+
error_description: "token_lifecycle_in_progress",
|
|
84
|
+
}), { status: 503, headers: { "content-type": "application/json" } });
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Run `fn` holding this process's lock on refresh token `tokenHash`. A caller
|
|
88
|
+
* that cannot take the lock is refused — 503 `busy` when the lock stayed held
|
|
89
|
+
* elsewhere, 503 when the store has no lock — and `fn` does not run.
|
|
90
|
+
*/
|
|
91
|
+
async function withTokenLifecycleLock(tokenHash, fn) {
|
|
92
|
+
const store = databases?.flair?.OAuthToken?.primaryStore;
|
|
93
|
+
const outcome = await withKeyLock(store, [OAUTH_TOKEN_LOCK_NAMESPACE, tokenHash], fn, OAUTH_TOKEN_LOCK_ATTEMPTS, OAUTH_TOKEN_LOCK_WAIT_MS);
|
|
94
|
+
if (outcome.kind === "done")
|
|
95
|
+
return { ok: true, value: outcome.value };
|
|
96
|
+
if (outcome.kind === "busy")
|
|
97
|
+
return { ok: false, response: tokenLifecycleBusy() };
|
|
98
|
+
return { ok: false, response: storeUnavailable() };
|
|
99
|
+
}
|
|
34
100
|
/**
|
|
35
101
|
* The scopes this server can issue, straight from the authorization-server
|
|
36
102
|
* metadata — ONE source of truth, so the consent page can never render a scope
|
|
@@ -387,7 +453,7 @@ export class OAuthToken extends Resource {
|
|
|
387
453
|
return this.handleRefreshToken(data);
|
|
388
454
|
}
|
|
389
455
|
else if (grantType === "urn:ietf:params:oauth:grant-type:jwt-bearer") {
|
|
390
|
-
return handleJwtBearerGrant(data);
|
|
456
|
+
return handleJwtBearerGrant(data, this.getContext?.());
|
|
391
457
|
}
|
|
392
458
|
return new Response(JSON.stringify({ error: "unsupported_grant_type" }), {
|
|
393
459
|
status: 400, headers: { "content-type": "application/json" },
|
|
@@ -445,6 +511,16 @@ export class OAuthToken extends Resource {
|
|
|
445
511
|
});
|
|
446
512
|
}
|
|
447
513
|
}
|
|
514
|
+
// Claim to redeem once per instance under a per-key lock before any token
|
|
515
|
+
// is issued (resources/replay-store.ts).
|
|
516
|
+
const claim = await claimOAuthSingleUse("code", sha256(code), AUTH_CODE_TTL_MS);
|
|
517
|
+
if (claim === "unavailable")
|
|
518
|
+
return storeUnavailable();
|
|
519
|
+
if (claim === "replay") {
|
|
520
|
+
return new Response(JSON.stringify({ error: "invalid_grant", error_description: "code already used" }), {
|
|
521
|
+
status: 400, headers: { "content-type": "application/json" },
|
|
522
|
+
});
|
|
523
|
+
}
|
|
448
524
|
// Mark code as used
|
|
449
525
|
await databases.flair.OAuthAuthCode.put({ ...authCode, used: true });
|
|
450
526
|
// Issue tokens
|
|
@@ -490,20 +566,93 @@ export class OAuthToken extends Resource {
|
|
|
490
566
|
status: 400, headers: { "content-type": "application/json" },
|
|
491
567
|
});
|
|
492
568
|
}
|
|
493
|
-
//
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
569
|
+
// Test-only: valid names are inert unless fault injection is enabled and
|
|
570
|
+
// armed (resources/txn-pause-point.ts). Holds this rotation between the
|
|
571
|
+
// read above and the claim below — the interleaving where a revoke of the
|
|
572
|
+
// same token commits first. Such a revoke records the token's single-use
|
|
573
|
+
// claim (`r:<hash>`), so the rotation's own claim below is a replay and
|
|
574
|
+
// refuses it there, before the committed-row re-read is reached.
|
|
575
|
+
const pause = txnPausePoint("oauth-refresh-pre-claim");
|
|
576
|
+
if (pause)
|
|
577
|
+
await pause;
|
|
578
|
+
// Within one Harper process, claim, re-read, write and issuance hold the
|
|
579
|
+
// same token lock OAuthRevoke takes. A revoke's recorded claim refuses a
|
|
580
|
+
// later rotation; the re-read also covers a committed row change that did
|
|
581
|
+
// not record that claim. A rotation that cannot take the lock is refused.
|
|
582
|
+
const outcome = await withTokenLifecycleLock(tokenHash, async () => {
|
|
583
|
+
// Claim to rotate once per instance under a per-key lock before the new
|
|
584
|
+
// pair is issued (resources/replay-store.ts). A revoke of this refresh
|
|
585
|
+
// token records the same claim (OAuthRevoke below), so a revoke that
|
|
586
|
+
// committed before this claim makes it a replay.
|
|
587
|
+
const claim = await claimOAuthSingleUse("refresh", tokenHash, REFRESH_TOKEN_TTL_MS);
|
|
588
|
+
if (claim === "unavailable")
|
|
589
|
+
return storeUnavailable();
|
|
590
|
+
if (claim === "replay") {
|
|
591
|
+
return new Response(JSON.stringify({ error: "invalid_grant", error_description: "token revoked" }), {
|
|
592
|
+
status: 400, headers: { "content-type": "application/json" },
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
// Test-only: holds this rotation between its single-use claim above and
|
|
596
|
+
// its committed-row re-read below, while it holds the token lock. A
|
|
597
|
+
// competing write of `revokedAt` that does NOT take this lock and does
|
|
598
|
+
// NOT record the claim (so the claim above could not refuse it) can
|
|
599
|
+
// commit here; the re-read below is then the only check that refuses the
|
|
600
|
+
// rotation.
|
|
601
|
+
const midClaimPause = txnPausePoint("oauth-refresh-mid-claim");
|
|
602
|
+
if (midClaimPause)
|
|
603
|
+
await midClaimPause;
|
|
604
|
+
// The committed-row re-read, the old row's write and the new pair's
|
|
605
|
+
// issuance run in a FRESH OWNED transaction (withOwnedTransaction,
|
|
606
|
+
// resources/request-transaction.ts) that COMMITS before this token's lock
|
|
607
|
+
// releases. Harper wraps this POST in a REQUEST transaction that commits
|
|
608
|
+
// only after the handler returns, so writes that joined it would still be
|
|
609
|
+
// invisible when the lock frees — a request that looked at the row right
|
|
610
|
+
// after release would read it unrevoked. The re-read reads the row IN that
|
|
611
|
+
// owned transaction: committed state, never this request's earlier
|
|
612
|
+
// snapshot. (The single-use claim above is its own awaited transaction.)
|
|
613
|
+
const ctx = this.getContext?.() ?? {};
|
|
614
|
+
return await withOwnedTransaction(ctx, async (owned) => {
|
|
615
|
+
// Re-read the COMMITTED row and refuse unless it is still this token,
|
|
616
|
+
// unrevoked, including row changes that did not record the claim.
|
|
617
|
+
const committed = await databases.flair.OAuthToken.get(refreshRecord.id, owned);
|
|
618
|
+
if (!committed || committed.tokenHash !== tokenHash || committed.revokedAt) {
|
|
619
|
+
return new Response(JSON.stringify({ error: "invalid_grant", error_description: "token revoked" }), {
|
|
620
|
+
status: 400, headers: { "content-type": "application/json" },
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
// Test-only: holds this rotation between the re-read above and the write
|
|
624
|
+
// and issuance below, while it holds the token lock — the interleaving
|
|
625
|
+
// where a revoke of this token would commit between them.
|
|
626
|
+
const postClaimPause = txnPausePoint("oauth-refresh-post-claim");
|
|
627
|
+
if (postClaimPause)
|
|
628
|
+
await postClaimPause;
|
|
629
|
+
// Rotate: revoke old refresh token, issue new pair — both in `owned`, so
|
|
630
|
+
// they commit before the lock releases.
|
|
631
|
+
await databases.flair.OAuthToken.put({
|
|
632
|
+
...committed,
|
|
633
|
+
revokedAt: nowISO(),
|
|
634
|
+
}, owned);
|
|
635
|
+
return this.issueTokenPair(committed.clientId, committed.principalId, committed.scope, owned);
|
|
636
|
+
});
|
|
497
637
|
});
|
|
498
|
-
|
|
638
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
639
|
+
// Pauses AFTER the token lock released (and, with the owned transaction
|
|
640
|
+
// above, after the rotation's writes committed) but BEFORE this request's own
|
|
641
|
+
// transaction commits (Harper commits it when the handler returns). A request
|
|
642
|
+
// that looks at the token right here must see the committed revocation.
|
|
643
|
+
const claimDone = txnPausePoint("oauth-refresh-claim-done");
|
|
644
|
+
if (claimDone)
|
|
645
|
+
await claimDone;
|
|
646
|
+
return outcome.ok ? outcome.value : outcome.response;
|
|
499
647
|
}
|
|
500
|
-
async issueTokenPair(clientId, principalId, scope) {
|
|
648
|
+
async issueTokenPair(clientId, principalId, scope, ctx) {
|
|
649
|
+
const put = (row) => ctx ? databases.flair.OAuthToken.put(row, ctx) : databases.flair.OAuthToken.put(row);
|
|
501
650
|
const now = nowISO();
|
|
502
651
|
const accessTokenRaw = randomToken("flair_at_");
|
|
503
652
|
const refreshTokenRaw = randomToken("flair_rt_");
|
|
504
653
|
const accessId = `at_${randomBytes(8).toString("hex")}`;
|
|
505
654
|
const refreshId = `rt_${randomBytes(8).toString("hex")}`;
|
|
506
|
-
await
|
|
655
|
+
await put({
|
|
507
656
|
id: accessId,
|
|
508
657
|
tokenHash: sha256(accessTokenRaw),
|
|
509
658
|
tokenType: "access",
|
|
@@ -513,7 +662,7 @@ export class OAuthToken extends Resource {
|
|
|
513
662
|
expiresAt: futureISO(ACCESS_TOKEN_TTL_MS),
|
|
514
663
|
createdAt: now,
|
|
515
664
|
});
|
|
516
|
-
await
|
|
665
|
+
await put({
|
|
517
666
|
id: refreshId,
|
|
518
667
|
tokenHash: sha256(refreshTokenRaw),
|
|
519
668
|
tokenType: "refresh",
|
|
@@ -549,6 +698,34 @@ export class OAuthRevoke extends Resource {
|
|
|
549
698
|
for await (const t of databases.flair.OAuthToken.search({
|
|
550
699
|
conditions: [{ attribute: "tokenHash", comparator: "equals", value: tokenHash }],
|
|
551
700
|
})) {
|
|
701
|
+
// Within one Harper process, a refresh rotation takes this token's lock
|
|
702
|
+
// across its claim, committed-row re-read, write and issuance, recording the
|
|
703
|
+
// single-use claim `r:<hash>` (OAuthToken above). The revoke takes the
|
|
704
|
+
// same lock before it records `revokedAt`, so it is serialized with an
|
|
705
|
+
// in-flight rotation and cannot commit between that rotation's re-read
|
|
706
|
+
// and its issuance. A claim that is already recorded — the token was
|
|
707
|
+
// already rotated, or this is a repeat revoke — is not an error: the
|
|
708
|
+
// revoke still records `revokedAt` below. An access token has no rotation
|
|
709
|
+
// to serialize with.
|
|
710
|
+
if (t.tokenType === "refresh") {
|
|
711
|
+
const outcome = await withTokenLifecycleLock(tokenHash, async () => {
|
|
712
|
+
// If this refresh-token revoke cannot record its claim, return 503
|
|
713
|
+
// without writing `revokedAt`.
|
|
714
|
+
const claim = await claimOAuthSingleUse("refresh", tokenHash, REFRESH_TOKEN_TTL_MS);
|
|
715
|
+
if (claim === "unavailable")
|
|
716
|
+
return storeUnavailable();
|
|
717
|
+
await databases.flair.OAuthToken.put({
|
|
718
|
+
...t,
|
|
719
|
+
revokedAt: nowISO(),
|
|
720
|
+
});
|
|
721
|
+
return undefined;
|
|
722
|
+
});
|
|
723
|
+
if (!outcome.ok)
|
|
724
|
+
return outcome.response;
|
|
725
|
+
if (outcome.value)
|
|
726
|
+
return outcome.value;
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
552
729
|
await databases.flair.OAuthToken.put({
|
|
553
730
|
...t,
|
|
554
731
|
revokedAt: nowISO(),
|
|
@@ -4,16 +4,23 @@
|
|
|
4
4
|
* Auth (self-enforced now that the global gate is non-rejecting):
|
|
5
5
|
* Read — any verified agent/admin (org-scoped); anonymous denied.
|
|
6
6
|
* Write — authorId must match the authenticated agent (or admin); anonymous denied.
|
|
7
|
+
* createdAt — assigned by the server on create; a write that reaches the
|
|
8
|
+
* createdAt check cannot change a stored row's value, and a
|
|
9
|
+
* record whose id the check does not read is refused there
|
|
10
|
+
* (resources/org-event-created-at.ts).
|
|
7
11
|
*
|
|
8
12
|
* The previous version read context.request.tpsAgent and treated a MISSING agent
|
|
9
13
|
* as trusted (`if (agentId && …)` / `if (!agentId) super.delete`), so anonymous
|
|
10
14
|
* requests slipped through once the gate stopped rejecting. resolveAgentAuth
|
|
11
15
|
* distinguishes internal/agent/anonymous explicitly.
|
|
12
16
|
*/
|
|
17
|
+
import { randomUUID } from "node:crypto";
|
|
13
18
|
import { databases } from "harper";
|
|
14
19
|
import { resolveAgentAuth } from "./agent-auth.js";
|
|
20
|
+
import { guardObjectBody } from "./object-body-guard.js";
|
|
15
21
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
16
22
|
import { invalidEntitiesResponse } from "./entity-vocab.js";
|
|
23
|
+
import { applyServerCreatedAt, collectionElementIdRefusal, createdAtCheckUnavailable, invalidEventId, unreadableEventIdRefusal, } from "./org-event-created-at.js";
|
|
17
24
|
import { makeAuthGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
18
25
|
import { RECORD_TYPES } from "./record-types.js";
|
|
19
26
|
// See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
|
|
@@ -22,10 +29,59 @@ import { RECORD_TYPES } from "./record-types.js";
|
|
|
22
29
|
const orgEventAuthGate = makeAuthGate();
|
|
23
30
|
export class OrgEvent extends databases.flair.OrgEvent {
|
|
24
31
|
allowRead() { return orgEventAuthGate.call(this); }
|
|
32
|
+
/**
|
|
33
|
+
* Scans the collection body on the initial collection-PUT call, before
|
|
34
|
+
* Harper's per-element dispatch. The scan skips non-record elements.
|
|
35
|
+
*/
|
|
36
|
+
static getResource(target, request, options) {
|
|
37
|
+
const admitted = super.getResource(target, request, options);
|
|
38
|
+
if (this !== OrgEvent || !options?.isCollection || options.method !== "put")
|
|
39
|
+
return admitted;
|
|
40
|
+
return Promise.resolve(admitted).then(async (resource) => {
|
|
41
|
+
const denial = collectionElementIdRefusal(await request?.data);
|
|
42
|
+
if (denial)
|
|
43
|
+
throw denial;
|
|
44
|
+
return resource;
|
|
45
|
+
});
|
|
46
|
+
}
|
|
25
47
|
_auth() {
|
|
26
48
|
return resolveAgentAuth(this.getContext?.());
|
|
27
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* The createdAt check (resources/org-event-created-at.ts), run after this
|
|
52
|
+
* verb's earlier checks. Applies to each record the write stores — the
|
|
53
|
+
* content itself, or each element of an array body — reading the stored row
|
|
54
|
+
* at the id the write lands on: server time with no stored row, the stored
|
|
55
|
+
* value (whatever it is) with one. A record that is not an object, or whose
|
|
56
|
+
* id the check does not read (isReadableEventId), is refused with
|
|
57
|
+
* `invalid_event_id` (400) before any write.
|
|
58
|
+
*/
|
|
59
|
+
async _assignCreatedAt(content, mode, idOf) {
|
|
60
|
+
const records = Array.isArray(content) ? content : [content];
|
|
61
|
+
for (const record of records) {
|
|
62
|
+
if (record == null || typeof record !== "object" || Array.isArray(record))
|
|
63
|
+
return invalidEventId();
|
|
64
|
+
const id = idOf(record);
|
|
65
|
+
const idDenial = unreadableEventIdRefusal(id);
|
|
66
|
+
if (idDenial)
|
|
67
|
+
return idDenial;
|
|
68
|
+
let stored;
|
|
69
|
+
try {
|
|
70
|
+
stored = ((await databases.flair.OrgEvent.get(id, {})) ?? null);
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
return createdAtCheckUnavailable(err);
|
|
74
|
+
}
|
|
75
|
+
const denial = applyServerCreatedAt(record, stored, mode);
|
|
76
|
+
if (denial)
|
|
77
|
+
return denial;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
28
81
|
async post(content) {
|
|
82
|
+
const bodyDenial = guardObjectBody(content);
|
|
83
|
+
if (bodyDenial)
|
|
84
|
+
return bodyDenial;
|
|
29
85
|
const auth = await this._auth();
|
|
30
86
|
if (auth.kind === "anonymous")
|
|
31
87
|
return UNAUTH();
|
|
@@ -44,27 +100,85 @@ export class OrgEvent extends databases.flair.OrgEvent {
|
|
|
44
100
|
// the forbiddenMessage arg is dead for this mode, passed for signature
|
|
45
101
|
// completeness only.
|
|
46
102
|
stampAttribution(auth, content, RECORD_TYPES.OrgEvent.ownerField, RECORD_TYPES.OrgEvent.attribution.post, "forbidden: unreachable for stamp-default");
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
103
|
+
// An addressed POST binds a missing or null body id, and a string or number
|
|
104
|
+
// body id whose text matches the address, to getId(); any other id type is
|
|
105
|
+
// left unchanged by this step.
|
|
106
|
+
// At /OrgEvent/, an absent, null or empty body id generates an id.
|
|
107
|
+
// At /OrgEvent/<prefix>/, a missing body id takes the target id (<prefix>/).
|
|
108
|
+
const addressedId = this.getId?.();
|
|
109
|
+
const addressed = typeof addressedId === "string" || typeof addressedId === "number";
|
|
110
|
+
// A missing or null body id binds to the address; a string or number body id
|
|
111
|
+
// binds when its text matches the address. Any other id type is left
|
|
112
|
+
// unchanged by this binding step. Later checks apply to it where the write reaches
|
|
113
|
+
// them: isReadableEventId first (an invalid id is refused there), then the
|
|
114
|
+
// ownership check and, outside internal calls, the createdAt check.
|
|
115
|
+
if (content && typeof content === "object" && addressed &&
|
|
116
|
+
(content.id == null ||
|
|
117
|
+
((typeof content.id === "string" || typeof content.id === "number") &&
|
|
118
|
+
String(content.id) === String(addressedId)))) {
|
|
119
|
+
content.id = addressedId;
|
|
120
|
+
}
|
|
121
|
+
// flair#2333 (H9): avoids deterministic same-millisecond collisions (random UUID).
|
|
122
|
+
if (!addressed && (content.id == null || content.id === ""))
|
|
123
|
+
content.id = `${content.authorId}-${new Date().toISOString()}-${randomUUID()}`;
|
|
124
|
+
// Binding runs before validation. At the root collection, or an addressed
|
|
125
|
+
// path whose body id was not bound, a remaining id the shared id rule does
|
|
126
|
+
// not read is refused with invalid_event_id (400) before the ownership lookup.
|
|
127
|
+
const idDenial = unreadableEventIdRefusal(content.id);
|
|
128
|
+
if (idDenial)
|
|
129
|
+
return idDenial;
|
|
130
|
+
// A trusted in-process call keeps its existing stamp; every verified agent's
|
|
131
|
+
// createdAt is assigned below, once the write passes its other checks.
|
|
132
|
+
if (auth.kind === "internal")
|
|
133
|
+
content.createdAt = new Date().toISOString();
|
|
50
134
|
// attention-plane vocabulary gate (flair#675): `entities`, if present,
|
|
51
135
|
// must be well-formed vocabulary strings — see resources/entity-vocab.ts.
|
|
52
136
|
// Field is additive/optional; absent entities is not an error.
|
|
53
137
|
const entitiesError = invalidEntitiesResponse(content.entities);
|
|
54
138
|
if (entitiesError)
|
|
55
139
|
return entitiesError;
|
|
140
|
+
// flair#2333 (N2): refuses a non-admin POST naming a row observed at the
|
|
141
|
+
// guard's lookup as owned by another agent. This read-then-write check is
|
|
142
|
+
// not atomic; a row appearing after the lookup is not covered.
|
|
143
|
+
const ownerDenial = await guardOwnerFieldImmutable(this, () => databases.flair.OrgEvent.get(content.id, {}), content, RECORD_TYPES.OrgEvent.ownerField);
|
|
144
|
+
if (ownerDenial)
|
|
145
|
+
return ownerDenial;
|
|
146
|
+
// createdAt: server time with no stored row; the stored value with one; a
|
|
147
|
+
// record whose id the check does not read is refused. (The id rule above
|
|
148
|
+
// means only a non-empty string or a non-empty array of strings reaches it.)
|
|
149
|
+
if (auth.kind !== "internal") {
|
|
150
|
+
const createdAtDenial = await this._assignCreatedAt(content, "replace", (record) => record.id);
|
|
151
|
+
if (createdAtDenial)
|
|
152
|
+
return createdAtDenial;
|
|
153
|
+
}
|
|
56
154
|
// Harper 5: table resources use put() for create/upsert (post() removed).
|
|
57
155
|
return databases.flair.OrgEvent.put(content);
|
|
58
156
|
}
|
|
59
157
|
// PATCH routes past put(), so authorId immutability is enforced on both verbs
|
|
60
158
|
// via the one shared delegate.
|
|
61
159
|
async patch(content, query) {
|
|
160
|
+
const bodyDenial = guardObjectBody(content);
|
|
161
|
+
if (bodyDenial)
|
|
162
|
+
return bodyDenial;
|
|
62
163
|
const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "authorId");
|
|
63
164
|
if (denial)
|
|
64
165
|
return denial;
|
|
166
|
+
// createdAt: PATCH writes the row its URL names, so the stored value is read
|
|
167
|
+
// there; a URL with no id the check reads (the collection) is refused. An
|
|
168
|
+
// omitted createdAt is left out of the merge and keeps that value.
|
|
169
|
+
const auth = await this._auth();
|
|
170
|
+
if (auth.kind !== "internal") {
|
|
171
|
+
const pathId = this.getId?.();
|
|
172
|
+
const createdAtDenial = await this._assignCreatedAt(content, "merge", () => pathId);
|
|
173
|
+
if (createdAtDenial)
|
|
174
|
+
return createdAtDenial;
|
|
175
|
+
}
|
|
65
176
|
return super.patch(content, query);
|
|
66
177
|
}
|
|
67
178
|
async put(content) {
|
|
179
|
+
const bodyDenial = guardObjectBody(content, { allowArrayObjects: true });
|
|
180
|
+
if (bodyDenial)
|
|
181
|
+
throw bodyDenial;
|
|
68
182
|
const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "authorId");
|
|
69
183
|
if (__ownerDenial)
|
|
70
184
|
return __ownerDenial;
|
|
@@ -82,6 +196,15 @@ export class OrgEvent extends databases.flair.OrgEvent {
|
|
|
82
196
|
const entitiesError = invalidEntitiesResponse(content.entities);
|
|
83
197
|
if (entitiesError)
|
|
84
198
|
return entitiesError;
|
|
199
|
+
// createdAt: server time with no stored row; the stored value with one,
|
|
200
|
+
// read under each record's own id; a record whose id the check does not
|
|
201
|
+
// read is refused. A refusal is thrown, so one refused record fails the whole
|
|
202
|
+
// request and nothing in it is written.
|
|
203
|
+
if (auth.kind !== "internal") {
|
|
204
|
+
const createdAtDenial = await this._assignCreatedAt(content, "replace", (record) => record.id);
|
|
205
|
+
if (createdAtDenial)
|
|
206
|
+
throw createdAtDenial;
|
|
207
|
+
}
|
|
85
208
|
return databases.flair.OrgEvent.put(content);
|
|
86
209
|
}
|
|
87
210
|
async delete(id, context) {
|