@agimon-ai/po-identity 0.0.2-alpha.87 → 0.0.2-alpha.89
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/dist/apiContracts.cjs +5 -5
- package/dist/apiContracts.d.mts +2 -2
- package/dist/apiContracts.mjs +5 -5
- package/dist/extensions/server.cjs +1 -1
- package/dist/extensions/server.mjs +1 -1
- package/dist/services/identityHome/globalTier.cjs +110 -0
- package/dist/services/identityHome/globalTier.d.mts +13 -0
- package/dist/services/identityHome/globalTier.mjs +108 -0
- package/dist/services/identityHome/index.cjs +85 -31
- package/dist/services/identityHome/index.d.mts +2 -0
- package/dist/services/identityHome/index.mjs +85 -31
- package/dist/services/identityHome/roster.cjs +1 -0
- package/dist/services/identityHome/roster.mjs +1 -0
- package/package.json +6 -6
package/dist/apiContracts.cjs
CHANGED
|
@@ -63,7 +63,7 @@ const proof = {
|
|
|
63
63
|
};
|
|
64
64
|
const post = (path, description, schema, authentication) => ({
|
|
65
65
|
id: `identity:${path}`,
|
|
66
|
-
scope: "
|
|
66
|
+
scope: "host",
|
|
67
67
|
path: `/api/auth/${path}`,
|
|
68
68
|
method: "POST",
|
|
69
69
|
description,
|
|
@@ -92,7 +92,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
|
|
|
92
92
|
http: [
|
|
93
93
|
{
|
|
94
94
|
id: "identity:providers",
|
|
95
|
-
scope: "
|
|
95
|
+
scope: "host",
|
|
96
96
|
path: "/api/auth/providers",
|
|
97
97
|
method: "GET",
|
|
98
98
|
description: "Configured sign-in provider names only",
|
|
@@ -105,7 +105,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
|
|
|
105
105
|
},
|
|
106
106
|
...["jwks", "revocations"].map((path) => ({
|
|
107
107
|
id: `identity:${path}`,
|
|
108
|
-
scope: "
|
|
108
|
+
scope: "host",
|
|
109
109
|
path: `/api/auth/${path}`,
|
|
110
110
|
method: "GET",
|
|
111
111
|
description: path === "jwks" ? "Issuer public signing keys" : "Cursor-based issuer revocations without addresses",
|
|
@@ -147,7 +147,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
|
|
|
147
147
|
post("devices/enroll", "Enroll with an account session and new-key enroll proof; later devices require C10 approval or trusted-hub attestation", proof, "owner"),
|
|
148
148
|
{
|
|
149
149
|
id: "identity:devices",
|
|
150
|
-
scope: "
|
|
150
|
+
scope: "host",
|
|
151
151
|
path: "/api/auth/devices",
|
|
152
152
|
method: "GET",
|
|
153
153
|
description: "List same-person devices, without keys or routing metadata",
|
|
@@ -173,7 +173,7 @@ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
|
|
|
173
173
|
}, "device"),
|
|
174
174
|
{
|
|
175
175
|
id: "identity:devices/approval:lookup",
|
|
176
|
-
scope: "
|
|
176
|
+
scope: "host",
|
|
177
177
|
path: "/api/auth/devices/approval",
|
|
178
178
|
method: "GET",
|
|
179
179
|
description: "Same-person approval challenge lookup and polling",
|
package/dist/apiContracts.d.mts
CHANGED
|
@@ -156,7 +156,7 @@ export declare const apiContracts: {
|
|
|
156
156
|
schemas?: Record<string, boolean | object> | undefined;
|
|
157
157
|
http: {
|
|
158
158
|
id: string;
|
|
159
|
-
scope: "
|
|
159
|
+
scope: "host" | "session" | "workspace";
|
|
160
160
|
basePath?: string | undefined;
|
|
161
161
|
path: string;
|
|
162
162
|
method: "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
|
|
@@ -184,7 +184,7 @@ export declare const apiContracts: {
|
|
|
184
184
|
}[];
|
|
185
185
|
sockets: {
|
|
186
186
|
id: string;
|
|
187
|
-
scope: "
|
|
187
|
+
scope: "host" | "session" | "workspace";
|
|
188
188
|
description: string;
|
|
189
189
|
availability?: string | undefined;
|
|
190
190
|
service: string;
|
package/dist/apiContracts.mjs
CHANGED
|
@@ -59,7 +59,7 @@ const proof = {
|
|
|
59
59
|
};
|
|
60
60
|
const post = (path, description, schema, authentication) => ({
|
|
61
61
|
id: `identity:${path}`,
|
|
62
|
-
scope: "
|
|
62
|
+
scope: "host",
|
|
63
63
|
path: `/api/auth/${path}`,
|
|
64
64
|
method: "POST",
|
|
65
65
|
description,
|
|
@@ -88,7 +88,7 @@ const apiContracts = defineApiContract({
|
|
|
88
88
|
http: [
|
|
89
89
|
{
|
|
90
90
|
id: "identity:providers",
|
|
91
|
-
scope: "
|
|
91
|
+
scope: "host",
|
|
92
92
|
path: "/api/auth/providers",
|
|
93
93
|
method: "GET",
|
|
94
94
|
description: "Configured sign-in provider names only",
|
|
@@ -101,7 +101,7 @@ const apiContracts = defineApiContract({
|
|
|
101
101
|
},
|
|
102
102
|
...["jwks", "revocations"].map((path) => ({
|
|
103
103
|
id: `identity:${path}`,
|
|
104
|
-
scope: "
|
|
104
|
+
scope: "host",
|
|
105
105
|
path: `/api/auth/${path}`,
|
|
106
106
|
method: "GET",
|
|
107
107
|
description: path === "jwks" ? "Issuer public signing keys" : "Cursor-based issuer revocations without addresses",
|
|
@@ -143,7 +143,7 @@ const apiContracts = defineApiContract({
|
|
|
143
143
|
post("devices/enroll", "Enroll with an account session and new-key enroll proof; later devices require C10 approval or trusted-hub attestation", proof, "owner"),
|
|
144
144
|
{
|
|
145
145
|
id: "identity:devices",
|
|
146
|
-
scope: "
|
|
146
|
+
scope: "host",
|
|
147
147
|
path: "/api/auth/devices",
|
|
148
148
|
method: "GET",
|
|
149
149
|
description: "List same-person devices, without keys or routing metadata",
|
|
@@ -169,7 +169,7 @@ const apiContracts = defineApiContract({
|
|
|
169
169
|
}, "device"),
|
|
170
170
|
{
|
|
171
171
|
id: "identity:devices/approval:lookup",
|
|
172
|
-
scope: "
|
|
172
|
+
scope: "host",
|
|
173
173
|
path: "/api/auth/devices/approval",
|
|
174
174
|
method: "GET",
|
|
175
175
|
description: "Same-person approval challenge lookup and polling",
|
|
@@ -13,7 +13,7 @@ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
|
|
|
13
13
|
/** Only selected global compositions install an issuer. Pairing-only hosts keep the attach gate. */
|
|
14
14
|
const serverPlugin = (0, require("@agimon-ai/po-core/serverPlugin").defineServerPlugin)({
|
|
15
15
|
name: "@agimon-ai/po-identity",
|
|
16
|
-
|
|
16
|
+
host: async (plugin) => {
|
|
17
17
|
const environment = plugin.host.context.environment;
|
|
18
18
|
if (!environment) throw new Error("Identity home requires an admitted server environment");
|
|
19
19
|
const configuration = require_index$1.identityConfiguration(environment);
|
|
@@ -8,7 +8,7 @@ import { defineServerPlugin } from "@agimon-ai/po-core/serverPlugin";
|
|
|
8
8
|
/** Only selected global compositions install an issuer. Pairing-only hosts keep the attach gate. */
|
|
9
9
|
const serverPlugin = defineServerPlugin({
|
|
10
10
|
name: "@agimon-ai/po-identity",
|
|
11
|
-
|
|
11
|
+
host: async (plugin) => {
|
|
12
12
|
const environment = plugin.host.context.environment;
|
|
13
13
|
if (!environment) throw new Error("Identity home requires an admitted server environment");
|
|
14
14
|
const configuration = identityConfiguration(environment);
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
//#region src/services/identityHome/globalTier.ts
|
|
2
|
+
var GlobalTierRefusal = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
constructor(status, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
/** Largest stored global settings document, in UTF-8 bytes. The HTTP body cap is the same. */
|
|
10
|
+
const MEMBER_SETTINGS_MAX_BYTES = 16384;
|
|
11
|
+
async function settingsHash(yaml) {
|
|
12
|
+
return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(yaml))).toString("base64url");
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Issuer-held global tier: per-membership settings and host visibility. Visibility lives beside the
|
|
16
|
+
* signed C6 host entries and never changes their bytes; it only filters what discovery returns.
|
|
17
|
+
*/
|
|
18
|
+
function createGlobalTier(database, now, membership) {
|
|
19
|
+
async function readMemberSettings(subject, org) {
|
|
20
|
+
return database.transaction(async (tx) => {
|
|
21
|
+
await membership(tx, subject, org);
|
|
22
|
+
return await tx.get("SELECT yaml, hash, updatedAt FROM member_settings WHERE org = ? AND subject = ?", org, subject) ?? {
|
|
23
|
+
yaml: "",
|
|
24
|
+
hash: await settingsHash(""),
|
|
25
|
+
updatedAt: null
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function writeMemberSettings(subject, org, yaml, expectedHash) {
|
|
30
|
+
if (new TextEncoder().encode(yaml).byteLength > 16384) throw new GlobalTierRefusal(413, "Settings too large");
|
|
31
|
+
const hash = await settingsHash(yaml);
|
|
32
|
+
const empty = await settingsHash("");
|
|
33
|
+
return database.transaction(async (tx) => {
|
|
34
|
+
await membership(tx, subject, org);
|
|
35
|
+
if (((await tx.get("SELECT hash FROM member_settings WHERE org = ? AND subject = ?", org, subject))?.hash ?? empty) !== expectedHash) throw new GlobalTierRefusal(409, "Settings changed");
|
|
36
|
+
const updatedAt = now();
|
|
37
|
+
await tx.run("INSERT INTO member_settings (org, subject, yaml, hash, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, subject) DO UPDATE SET yaml = excluded.yaml, hash = excluded.hash, updatedAt = excluded.updatedAt", org, subject, yaml, hash, updatedAt);
|
|
38
|
+
return {
|
|
39
|
+
hash,
|
|
40
|
+
updatedAt
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Org-visible hosts plus the caller's own. Hidden hosts are absent, so their endpoints never leave. */
|
|
45
|
+
async function visibleHosts(subject, org) {
|
|
46
|
+
return database.transaction(async (tx) => {
|
|
47
|
+
await membership(tx, subject, org);
|
|
48
|
+
return {
|
|
49
|
+
networkId: org,
|
|
50
|
+
hosts: (await tx.all(`SELECT h.entry, h.subject, COALESCE(v.visibility, 'org') AS visibility
|
|
51
|
+
FROM identity_roster_host h
|
|
52
|
+
JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject
|
|
53
|
+
LEFT JOIN host_visibility v ON v.org = h.networkId AND v.hostId = h.hostId
|
|
54
|
+
WHERE h.networkId = ? AND h.evicted = 0 AND (COALESCE(v.visibility, 'org') = 'org' OR h.subject = ?)
|
|
55
|
+
ORDER BY h.hostId`, org, subject)).map((row) => ({
|
|
56
|
+
entry: JSON.parse(row.entry),
|
|
57
|
+
visibility: row.visibility,
|
|
58
|
+
owned: row.subject === subject
|
|
59
|
+
}))
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Member-facing roster reads omit hosts another member keeps private, and the voter and term changes
|
|
65
|
+
* that name them. Evictions stay: clients purge a paired host only on an explicit eviction record.
|
|
66
|
+
* Host-proof and voter reads keep the full issuer-signed snapshot.
|
|
67
|
+
*/
|
|
68
|
+
async function memberRosterView(subject, org, snapshot) {
|
|
69
|
+
const hidden = new Set((await database.all("SELECT v.hostId FROM host_visibility v JOIN identity_roster_host h ON h.networkId = v.org AND h.hostId = v.hostId WHERE v.org = ? AND v.visibility = 'member' AND h.subject != ?", org, subject)).map((row) => row.hostId));
|
|
70
|
+
const { payload } = snapshot;
|
|
71
|
+
return {
|
|
72
|
+
tag: snapshot.tag,
|
|
73
|
+
payload: {
|
|
74
|
+
...payload,
|
|
75
|
+
hosts: payload.hosts.filter((entry) => !hidden.has(entry.payload.hostId)),
|
|
76
|
+
changes: payload.changes.filter((entry) => entry.payload.change.kind === "evict" || !hidden.has(entry.payload.hostId))
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** `org` needs an owner or admin. The host's owner, or an owner or admin, may set `member`. */
|
|
81
|
+
async function setHostVisibility(subject, org, hostId, visibility) {
|
|
82
|
+
if (visibility !== "org" && visibility !== "member") throw new GlobalTierRefusal(400, "Invalid visibility");
|
|
83
|
+
return database.transaction(async (tx) => {
|
|
84
|
+
const role = await membership(tx, subject, org);
|
|
85
|
+
const host = await tx.get("SELECT h.subject FROM identity_roster_host h JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject WHERE h.networkId = ? AND h.hostId = ? AND h.evicted = 0", org, hostId);
|
|
86
|
+
const manager = role === "owner" || role === "admin";
|
|
87
|
+
if (!host || !manager && host.subject !== subject) throw new GlobalTierRefusal(404, "Host unavailable");
|
|
88
|
+
if (visibility === "org" && !manager) throw new GlobalTierRefusal(403, "Owner or admin required");
|
|
89
|
+
const updatedAt = now();
|
|
90
|
+
await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, hostId) DO UPDATE SET visibility = excluded.visibility, setBy = excluded.setBy, updatedAt = excluded.updatedAt", org, hostId, visibility, subject, updatedAt);
|
|
91
|
+
return {
|
|
92
|
+
hostId,
|
|
93
|
+
visibility,
|
|
94
|
+
setBy: subject,
|
|
95
|
+
updatedAt
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
readMemberSettings,
|
|
101
|
+
writeMemberSettings,
|
|
102
|
+
visibleHosts,
|
|
103
|
+
memberRosterView,
|
|
104
|
+
setHostVisibility
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
exports.GlobalTierRefusal = GlobalTierRefusal;
|
|
109
|
+
exports.MEMBER_SETTINGS_MAX_BYTES = MEMBER_SETTINGS_MAX_BYTES;
|
|
110
|
+
exports.createGlobalTier = createGlobalTier;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { FederationRoster } from "@agimon-ai/po-core";
|
|
2
|
+
import { SignedFederationEnvelope } from "@agimon-ai/po-web-security";
|
|
3
|
+
import { SqliteDatabase, SqliteExecutor } from "@earendil-works/pi-durable/storage/sqlite";
|
|
4
|
+
//#region src/services/identityHome/globalTier.d.ts
|
|
5
|
+
type SignedRoster = SignedFederationEnvelope<FederationRoster, 'po/roster/v1'>;
|
|
6
|
+
/**
|
|
7
|
+
* Roster as a member reads it: another member's private hosts are removed, so the issuer's whole-list
|
|
8
|
+
* signature is dropped. Host entries keep their own signed bytes. Without the issuer signature this
|
|
9
|
+
* view can never be applied as C6 state, so a member cannot replay it to make a host drop entries.
|
|
10
|
+
*/
|
|
11
|
+
export type MemberRosterView = Pick<SignedRoster, 'tag' | 'payload'>;
|
|
12
|
+
//#endregion
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
//#region src/services/identityHome/globalTier.ts
|
|
2
|
+
var GlobalTierRefusal = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
constructor(status, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
/** Largest stored global settings document, in UTF-8 bytes. The HTTP body cap is the same. */
|
|
10
|
+
const MEMBER_SETTINGS_MAX_BYTES = 16384;
|
|
11
|
+
async function settingsHash(yaml) {
|
|
12
|
+
return Buffer.from(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(yaml))).toString("base64url");
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Issuer-held global tier: per-membership settings and host visibility. Visibility lives beside the
|
|
16
|
+
* signed C6 host entries and never changes their bytes; it only filters what discovery returns.
|
|
17
|
+
*/
|
|
18
|
+
function createGlobalTier(database, now, membership) {
|
|
19
|
+
async function readMemberSettings(subject, org) {
|
|
20
|
+
return database.transaction(async (tx) => {
|
|
21
|
+
await membership(tx, subject, org);
|
|
22
|
+
return await tx.get("SELECT yaml, hash, updatedAt FROM member_settings WHERE org = ? AND subject = ?", org, subject) ?? {
|
|
23
|
+
yaml: "",
|
|
24
|
+
hash: await settingsHash(""),
|
|
25
|
+
updatedAt: null
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function writeMemberSettings(subject, org, yaml, expectedHash) {
|
|
30
|
+
if (new TextEncoder().encode(yaml).byteLength > 16384) throw new GlobalTierRefusal(413, "Settings too large");
|
|
31
|
+
const hash = await settingsHash(yaml);
|
|
32
|
+
const empty = await settingsHash("");
|
|
33
|
+
return database.transaction(async (tx) => {
|
|
34
|
+
await membership(tx, subject, org);
|
|
35
|
+
if (((await tx.get("SELECT hash FROM member_settings WHERE org = ? AND subject = ?", org, subject))?.hash ?? empty) !== expectedHash) throw new GlobalTierRefusal(409, "Settings changed");
|
|
36
|
+
const updatedAt = now();
|
|
37
|
+
await tx.run("INSERT INTO member_settings (org, subject, yaml, hash, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, subject) DO UPDATE SET yaml = excluded.yaml, hash = excluded.hash, updatedAt = excluded.updatedAt", org, subject, yaml, hash, updatedAt);
|
|
38
|
+
return {
|
|
39
|
+
hash,
|
|
40
|
+
updatedAt
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Org-visible hosts plus the caller's own. Hidden hosts are absent, so their endpoints never leave. */
|
|
45
|
+
async function visibleHosts(subject, org) {
|
|
46
|
+
return database.transaction(async (tx) => {
|
|
47
|
+
await membership(tx, subject, org);
|
|
48
|
+
return {
|
|
49
|
+
networkId: org,
|
|
50
|
+
hosts: (await tx.all(`SELECT h.entry, h.subject, COALESCE(v.visibility, 'org') AS visibility
|
|
51
|
+
FROM identity_roster_host h
|
|
52
|
+
JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject
|
|
53
|
+
LEFT JOIN host_visibility v ON v.org = h.networkId AND v.hostId = h.hostId
|
|
54
|
+
WHERE h.networkId = ? AND h.evicted = 0 AND (COALESCE(v.visibility, 'org') = 'org' OR h.subject = ?)
|
|
55
|
+
ORDER BY h.hostId`, org, subject)).map((row) => ({
|
|
56
|
+
entry: JSON.parse(row.entry),
|
|
57
|
+
visibility: row.visibility,
|
|
58
|
+
owned: row.subject === subject
|
|
59
|
+
}))
|
|
60
|
+
};
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Member-facing roster reads omit hosts another member keeps private, and the voter and term changes
|
|
65
|
+
* that name them. Evictions stay: clients purge a paired host only on an explicit eviction record.
|
|
66
|
+
* Host-proof and voter reads keep the full issuer-signed snapshot.
|
|
67
|
+
*/
|
|
68
|
+
async function memberRosterView(subject, org, snapshot) {
|
|
69
|
+
const hidden = new Set((await database.all("SELECT v.hostId FROM host_visibility v JOIN identity_roster_host h ON h.networkId = v.org AND h.hostId = v.hostId WHERE v.org = ? AND v.visibility = 'member' AND h.subject != ?", org, subject)).map((row) => row.hostId));
|
|
70
|
+
const { payload } = snapshot;
|
|
71
|
+
return {
|
|
72
|
+
tag: snapshot.tag,
|
|
73
|
+
payload: {
|
|
74
|
+
...payload,
|
|
75
|
+
hosts: payload.hosts.filter((entry) => !hidden.has(entry.payload.hostId)),
|
|
76
|
+
changes: payload.changes.filter((entry) => entry.payload.change.kind === "evict" || !hidden.has(entry.payload.hostId))
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** `org` needs an owner or admin. The host's owner, or an owner or admin, may set `member`. */
|
|
81
|
+
async function setHostVisibility(subject, org, hostId, visibility) {
|
|
82
|
+
if (visibility !== "org" && visibility !== "member") throw new GlobalTierRefusal(400, "Invalid visibility");
|
|
83
|
+
return database.transaction(async (tx) => {
|
|
84
|
+
const role = await membership(tx, subject, org);
|
|
85
|
+
const host = await tx.get("SELECT h.subject FROM identity_roster_host h JOIN member m ON m.organizationId = h.networkId AND m.userId = h.subject WHERE h.networkId = ? AND h.hostId = ? AND h.evicted = 0", org, hostId);
|
|
86
|
+
const manager = role === "owner" || role === "admin";
|
|
87
|
+
if (!host || !manager && host.subject !== subject) throw new GlobalTierRefusal(404, "Host unavailable");
|
|
88
|
+
if (visibility === "org" && !manager) throw new GlobalTierRefusal(403, "Owner or admin required");
|
|
89
|
+
const updatedAt = now();
|
|
90
|
+
await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, ?, ?, ?) ON CONFLICT(org, hostId) DO UPDATE SET visibility = excluded.visibility, setBy = excluded.setBy, updatedAt = excluded.updatedAt", org, hostId, visibility, subject, updatedAt);
|
|
91
|
+
return {
|
|
92
|
+
hostId,
|
|
93
|
+
visibility,
|
|
94
|
+
setBy: subject,
|
|
95
|
+
updatedAt
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
readMemberSettings,
|
|
101
|
+
writeMemberSettings,
|
|
102
|
+
visibleHosts,
|
|
103
|
+
memberRosterView,
|
|
104
|
+
setHostVisibility
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
//#endregion
|
|
108
|
+
export { GlobalTierRefusal, MEMBER_SETTINGS_MAX_BYTES, createGlobalTier };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_apiContracts = require("../../apiContracts.cjs");
|
|
2
2
|
const require_index = require("../appleTokens/index.cjs");
|
|
3
3
|
const require_index$1 = require("../sqliteAdapter/index.cjs");
|
|
4
|
+
const require_globalTier = require("./globalTier.cjs");
|
|
4
5
|
const require_roster = require("./roster.cjs");
|
|
5
6
|
let node_crypto = require("node:crypto");
|
|
6
7
|
let _agimon_ai_po_core = require("@agimon-ai/po-core");
|
|
@@ -46,9 +47,7 @@ async function createIdentityHome(config, ports) {
|
|
|
46
47
|
disabledPaths: [
|
|
47
48
|
"/token",
|
|
48
49
|
"/delete-user",
|
|
49
|
-
"/delete-user/callback"
|
|
50
|
-
"/organization/invite-member",
|
|
51
|
-
"/organization/accept-invitation"
|
|
50
|
+
"/delete-user/callback"
|
|
52
51
|
],
|
|
53
52
|
trustedOrigins: [config.issuer, "po://"],
|
|
54
53
|
rateLimit: {
|
|
@@ -75,8 +74,15 @@ async function createIdentityHome(config, ports) {
|
|
|
75
74
|
socialProviders,
|
|
76
75
|
plugins: [
|
|
77
76
|
(0, better_auth_plugins.organization)({
|
|
78
|
-
allowUserToCreateOrganization:
|
|
79
|
-
|
|
77
|
+
allowUserToCreateOrganization: true,
|
|
78
|
+
requireEmailVerificationOnInvitation: true,
|
|
79
|
+
async sendInvitationEmail({ id, email, organization: invitedTo, inviter }) {
|
|
80
|
+
await ports.email.send({
|
|
81
|
+
to: email,
|
|
82
|
+
subject: `Join ${invitedTo.name} on Po`,
|
|
83
|
+
text: `${inviter.user.name || inviter.user.email} invited you to ${invitedTo.name}. Sign in to Po with this address and accept invitation ${id}.`
|
|
84
|
+
});
|
|
85
|
+
},
|
|
80
86
|
ac,
|
|
81
87
|
roles: {
|
|
82
88
|
owner: ac.newRole(better_auth_plugins_organization_access.ownerAc.statements),
|
|
@@ -219,6 +225,14 @@ async function createIdentityHome(config, ports) {
|
|
|
219
225
|
{
|
|
220
226
|
version: 9,
|
|
221
227
|
statements: ["CREATE TABLE IF NOT EXISTS \"rateLimit\" (\"id\" TEXT PRIMARY KEY, \"key\" TEXT NOT NULL UNIQUE, \"count\" INTEGER NOT NULL, \"lastRequest\" INTEGER NOT NULL)"]
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
version: 10,
|
|
231
|
+
statements: [
|
|
232
|
+
"CREATE TABLE IF NOT EXISTS member_settings (org TEXT NOT NULL, subject TEXT NOT NULL, yaml TEXT NOT NULL, hash TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, subject))",
|
|
233
|
+
"CREATE TABLE IF NOT EXISTS host_visibility (org TEXT NOT NULL, hostId TEXT NOT NULL, visibility TEXT NOT NULL CHECK(visibility IN ('org','member')), setBy TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, hostId))",
|
|
234
|
+
"CREATE TRIGGER IF NOT EXISTS member_settings_member_remove AFTER DELETE ON member BEGIN DELETE FROM member_settings WHERE org = OLD.organizationId AND subject = OLD.userId; END"
|
|
235
|
+
]
|
|
222
236
|
}
|
|
223
237
|
], { table: "identity_registry_migrations" });
|
|
224
238
|
const auth = (0, better_auth.betterAuth)({
|
|
@@ -226,6 +240,7 @@ async function createIdentityHome(config, ports) {
|
|
|
226
240
|
database: require_index$1.poAdapter(database)
|
|
227
241
|
});
|
|
228
242
|
const roster = await require_roster.createIssuerRoster(database, config.issuer, config.jwtKeyWrap, now, membership);
|
|
243
|
+
const globalTier = require_globalTier.createGlobalTier(database, now, membership);
|
|
229
244
|
async function membership(tx, subject, org) {
|
|
230
245
|
const person = await tx.get("SELECT id FROM user WHERE id = ?", subject);
|
|
231
246
|
const member = await tx.get("SELECT role FROM member WHERE userId = ? AND organizationId = ?", subject, org);
|
|
@@ -813,6 +828,7 @@ async function createIdentityHome(config, ports) {
|
|
|
813
828
|
await tx.run("DELETE FROM identity_outbox WHERE kind='materialize-workspace' AND json_extract(payload,'$.orgId')=?", org);
|
|
814
829
|
for (const table of ["member", "invitation"]) await tx.run(`DELETE FROM ${table} WHERE organizationId=?`, org);
|
|
815
830
|
await tx.run("DELETE FROM identity_workspace WHERE orgId=?", org);
|
|
831
|
+
for (const table of ["member_settings", "host_visibility"]) await tx.run(`DELETE FROM ${table} WHERE org=?`, org);
|
|
816
832
|
await tx.run("DELETE FROM identity_personal_org WHERE organizationId=?", org);
|
|
817
833
|
await tx.run("DELETE FROM first_workspace WHERE organizationId=?", org);
|
|
818
834
|
await tx.run("DELETE FROM organization WHERE id=?", org);
|
|
@@ -982,6 +998,37 @@ async function createIdentityHome(config, ports) {
|
|
|
982
998
|
const text = new TextDecoder().decode(bytes);
|
|
983
999
|
return json ? JSON.parse(text) : text;
|
|
984
1000
|
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Caller of an issuer route: a C1 identity token bound to a current device, or a Better Auth session
|
|
1003
|
+
* cookie. Cookie writes also need `x-po-csrf: 1`, which a cross-site form cannot send.
|
|
1004
|
+
*/
|
|
1005
|
+
async function requestSubject(request, audience, mutating = false) {
|
|
1006
|
+
const origin = request.headers.get("origin");
|
|
1007
|
+
if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
|
|
1008
|
+
const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
|
|
1009
|
+
if (!token) {
|
|
1010
|
+
if (mutating && request.headers.get("x-po-csrf") !== "1") throw new IdentityRefusal(403, "CSRF header required");
|
|
1011
|
+
const subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
|
|
1012
|
+
if (!subject) throw new IdentityRefusal(401, "Sign in required");
|
|
1013
|
+
return subject;
|
|
1014
|
+
}
|
|
1015
|
+
try {
|
|
1016
|
+
const jwks = await auth.api.getJwks();
|
|
1017
|
+
const { payload } = await (0, jose.jwtVerify)(token, (0, jose.createLocalJWKSet)(jwks), {
|
|
1018
|
+
issuer: config.issuer,
|
|
1019
|
+
...audience === void 0 ? {} : { audience },
|
|
1020
|
+
algorithms: ["ES256"],
|
|
1021
|
+
currentDate: new Date(now() + 3e4)
|
|
1022
|
+
});
|
|
1023
|
+
if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
|
|
1024
|
+
const cnf = payload.cnf;
|
|
1025
|
+
if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
|
|
1026
|
+
await orgRole(payload.sub, payload.org);
|
|
1027
|
+
return payload.sub;
|
|
1028
|
+
} catch {
|
|
1029
|
+
throw new IdentityRefusal(401, "Current identity token required");
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
985
1032
|
async function fetchHandler(request) {
|
|
986
1033
|
let path;
|
|
987
1034
|
try {
|
|
@@ -998,44 +1045,50 @@ async function createIdentityHome(config, ports) {
|
|
|
998
1045
|
const own = path === "/api/networks/own-hub-link";
|
|
999
1046
|
const remove = path === "/api/networks/remove-hub";
|
|
1000
1047
|
if (path === "/api/networks/hub-removal-receipt" && request.method === "GET") return Response.json(await roster.removalReceiptFromHost(request), { headers: { "cache-control": "no-store" } });
|
|
1048
|
+
const visible = /^\/api\/networks\/([^/]+)\/hosts\/visible$/.exec(path);
|
|
1049
|
+
const visibility = /^\/api\/networks\/([^/]+)\/hosts\/([^/]+)\/visibility$/.exec(path);
|
|
1050
|
+
if (visible && request.method === "GET") return Response.json(await globalTier.visibleHosts(await requestSubject(request, visible[1]), visible[1]), { headers: { "cache-control": "no-store" } });
|
|
1051
|
+
if (visibility && request.method === "PUT") {
|
|
1052
|
+
const subject = await requestSubject(request, visibility[1], true);
|
|
1053
|
+
const body = await readBody(request);
|
|
1054
|
+
return Response.json(await globalTier.setHostVisibility(subject, visibility[1], visibility[2], body?.visibility));
|
|
1055
|
+
}
|
|
1056
|
+
if (visible || visibility) return new Response("Method not allowed", { status: 405 });
|
|
1001
1057
|
if (!match && !own && !remove) return new Response("not found", { status: 404 });
|
|
1002
1058
|
if (match?.[2] === "roster" && request.method === "GET" && request.headers.has("x-po-roster-proof")) return Response.json(await roster.rosterFromHost(request, match[1]), { headers: { "cache-control": "no-store" } });
|
|
1003
|
-
const
|
|
1004
|
-
if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
|
|
1005
|
-
let subject;
|
|
1006
|
-
const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
|
|
1007
|
-
if (token) try {
|
|
1008
|
-
const jwks = await auth.api.getJwks();
|
|
1009
|
-
const { payload } = await (0, jose.jwtVerify)(token, (0, jose.createLocalJWKSet)(jwks), {
|
|
1010
|
-
issuer: config.issuer,
|
|
1011
|
-
...match ? { audience: match[1] } : {},
|
|
1012
|
-
algorithms: ["ES256"],
|
|
1013
|
-
currentDate: new Date(now() + 3e4)
|
|
1014
|
-
});
|
|
1015
|
-
if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
|
|
1016
|
-
const cnf = payload.cnf;
|
|
1017
|
-
if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
|
|
1018
|
-
await orgRole(payload.sub, payload.org);
|
|
1019
|
-
subject = payload.sub;
|
|
1020
|
-
} catch {
|
|
1021
|
-
throw new IdentityRefusal(401, "Current identity token required");
|
|
1022
|
-
}
|
|
1023
|
-
else subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
|
|
1024
|
-
if (!subject) throw new IdentityRefusal(401, "Sign in required");
|
|
1059
|
+
const subject = await requestSubject(request, match?.[1]);
|
|
1025
1060
|
if (own && request.method === "POST") return Response.json({ networkId: await personalOrg(subject) });
|
|
1026
1061
|
if (remove && request.method === "POST") return Response.json(await roster.removeHub(subject, await readBody(request)), { headers: { "cache-control": "no-store" } });
|
|
1027
|
-
if (match?.[2] === "roster" && request.method === "GET") return Response.json(await roster.networkRoster(subject, match[1]), { headers: { "cache-control": "no-store" } });
|
|
1062
|
+
if (match?.[2] === "roster" && request.method === "GET") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.networkRoster(subject, match[1])), { headers: { "cache-control": "no-store" } });
|
|
1028
1063
|
if (match && request.method === "POST") {
|
|
1029
1064
|
const body = await readBody(request);
|
|
1030
|
-
if (match[2] === "hosts") return Response.json(await roster.registerRosterHost(subject, match[1], body?.entry));
|
|
1031
|
-
if (match[2] === "changes") return Response.json(await roster.registerRosterChange(subject, match[1], body?.change));
|
|
1065
|
+
if (match[2] === "hosts") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterHost(subject, match[1], body?.entry)));
|
|
1066
|
+
if (match[2] === "changes") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterChange(subject, match[1], body?.change)));
|
|
1032
1067
|
}
|
|
1033
1068
|
return new Response("Method not allowed", { status: 405 });
|
|
1034
1069
|
} catch (error) {
|
|
1035
|
-
if (error instanceof IdentityRefusal || error instanceof require_roster.RosterRefusal) return Response.json({ error: error.message }, { status: error.status });
|
|
1070
|
+
if (error instanceof IdentityRefusal || error instanceof require_roster.RosterRefusal || error instanceof require_globalTier.GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
|
|
1036
1071
|
if (error instanceof SyntaxError || error instanceof TypeError) return Response.json({ error: "Invalid roster request" }, { status: 400 });
|
|
1037
1072
|
throw error;
|
|
1038
1073
|
}
|
|
1074
|
+
if (path === "/api/account/settings") try {
|
|
1075
|
+
const query = new URL(request.url).searchParams;
|
|
1076
|
+
const org = query.get("org") ?? "";
|
|
1077
|
+
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(org)) throw new IdentityRefusal(400, "Organization required");
|
|
1078
|
+
const headers = { "cache-control": "no-store" };
|
|
1079
|
+
if (request.method === "GET") return Response.json(await globalTier.readMemberSettings(await requestSubject(request, org), org), { headers });
|
|
1080
|
+
if (request.method === "PUT") {
|
|
1081
|
+
const subject = await requestSubject(request, org, true);
|
|
1082
|
+
const expectedHash = query.get("expectedHash");
|
|
1083
|
+
if (!expectedHash) throw new IdentityRefusal(428, "expectedHash required");
|
|
1084
|
+
const yaml = await readBody(request, false);
|
|
1085
|
+
return Response.json(await globalTier.writeMemberSettings(subject, org, yaml, expectedHash), { headers });
|
|
1086
|
+
}
|
|
1087
|
+
return new Response("Method not allowed", { status: 405 });
|
|
1088
|
+
} catch (error) {
|
|
1089
|
+
if (error instanceof IdentityRefusal || error instanceof require_globalTier.GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
|
|
1090
|
+
throw error;
|
|
1091
|
+
}
|
|
1039
1092
|
if (!path.startsWith("/api/auth/")) return new Response("not found", { status: 404 });
|
|
1040
1093
|
if (path.replace(/\/+$/, "") === "/api/auth/token") return new Response("Device signature required", { status: 401 });
|
|
1041
1094
|
if (path === "/api/auth/device-key" && request.method === "POST") {
|
|
@@ -1246,6 +1299,7 @@ async function createIdentityHome(config, ports) {
|
|
|
1246
1299
|
return {
|
|
1247
1300
|
database,
|
|
1248
1301
|
...roster,
|
|
1302
|
+
memberRosterView: globalTier.memberRosterView,
|
|
1249
1303
|
fetch: fetchHandler,
|
|
1250
1304
|
personalOrg,
|
|
1251
1305
|
ensurePersonalOrg,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { IdentityProof, IdentityProvisioningItem, IdentityWorkspaceAllocation, PersonalOrgTrigger, identityProofFields } from "../../apiContracts.mjs";
|
|
2
|
+
import { MemberRosterView } from "./globalTier.mjs";
|
|
2
3
|
import { AppleTokenConfig } from "../appleTokens/index.mjs";
|
|
3
4
|
import { IdentityEmailSender } from "../emailSender/index.mjs";
|
|
4
5
|
import { FederationEnvelope } from "@agimon-ai/po-core";
|
|
@@ -76,6 +77,7 @@ export declare function createIdentityHome(config: IdentityHomeConfig, ports: Id
|
|
|
76
77
|
}, "po/hub-removal-receipt/v1">>;
|
|
77
78
|
removalReceiptFromHost: (request: Request) => Promise<FederationEnvelope<"po/hub-removal-receipt/v1">>;
|
|
78
79
|
database: import("@earendil-works/chord/sqlite").SqliteDatabase;
|
|
80
|
+
memberRosterView: (subject: string, org: string, snapshot: import("@agimon-ai/po-web-security").SignedFederationEnvelope<import("@agimon-ai/po-core").FederationRoster, "po/roster/v1">) => Promise<MemberRosterView>;
|
|
79
81
|
fetch: (request: Request) => Promise<Response>;
|
|
80
82
|
personalOrg: (subject: string) => Promise<string>;
|
|
81
83
|
ensurePersonalOrg: (subject: string, trigger: PersonalOrgTrigger) => Promise<IdentityWorkspaceAllocation>;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { identityProofFields } from "../../apiContracts.mjs";
|
|
2
2
|
import { appleTokenService } from "../appleTokens/index.mjs";
|
|
3
3
|
import { openIdentity, poAdapter } from "../sqliteAdapter/index.mjs";
|
|
4
|
+
import { GlobalTierRefusal, createGlobalTier } from "./globalTier.mjs";
|
|
4
5
|
import { RosterRefusal, createIssuerRoster } from "./roster.mjs";
|
|
5
6
|
import { createPublicKey } from "node:crypto";
|
|
6
7
|
import { federationEnrollmentGeneration } from "@agimon-ai/po-core";
|
|
@@ -46,9 +47,7 @@ async function createIdentityHome(config, ports) {
|
|
|
46
47
|
disabledPaths: [
|
|
47
48
|
"/token",
|
|
48
49
|
"/delete-user",
|
|
49
|
-
"/delete-user/callback"
|
|
50
|
-
"/organization/invite-member",
|
|
51
|
-
"/organization/accept-invitation"
|
|
50
|
+
"/delete-user/callback"
|
|
52
51
|
],
|
|
53
52
|
trustedOrigins: [config.issuer, "po://"],
|
|
54
53
|
rateLimit: {
|
|
@@ -75,8 +74,15 @@ async function createIdentityHome(config, ports) {
|
|
|
75
74
|
socialProviders,
|
|
76
75
|
plugins: [
|
|
77
76
|
organization({
|
|
78
|
-
allowUserToCreateOrganization:
|
|
79
|
-
|
|
77
|
+
allowUserToCreateOrganization: true,
|
|
78
|
+
requireEmailVerificationOnInvitation: true,
|
|
79
|
+
async sendInvitationEmail({ id, email, organization: invitedTo, inviter }) {
|
|
80
|
+
await ports.email.send({
|
|
81
|
+
to: email,
|
|
82
|
+
subject: `Join ${invitedTo.name} on Po`,
|
|
83
|
+
text: `${inviter.user.name || inviter.user.email} invited you to ${invitedTo.name}. Sign in to Po with this address and accept invitation ${id}.`
|
|
84
|
+
});
|
|
85
|
+
},
|
|
80
86
|
ac,
|
|
81
87
|
roles: {
|
|
82
88
|
owner: ac.newRole(ownerAc.statements),
|
|
@@ -219,6 +225,14 @@ async function createIdentityHome(config, ports) {
|
|
|
219
225
|
{
|
|
220
226
|
version: 9,
|
|
221
227
|
statements: ["CREATE TABLE IF NOT EXISTS \"rateLimit\" (\"id\" TEXT PRIMARY KEY, \"key\" TEXT NOT NULL UNIQUE, \"count\" INTEGER NOT NULL, \"lastRequest\" INTEGER NOT NULL)"]
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
version: 10,
|
|
231
|
+
statements: [
|
|
232
|
+
"CREATE TABLE IF NOT EXISTS member_settings (org TEXT NOT NULL, subject TEXT NOT NULL, yaml TEXT NOT NULL, hash TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, subject))",
|
|
233
|
+
"CREATE TABLE IF NOT EXISTS host_visibility (org TEXT NOT NULL, hostId TEXT NOT NULL, visibility TEXT NOT NULL CHECK(visibility IN ('org','member')), setBy TEXT NOT NULL, updatedAt INTEGER NOT NULL, PRIMARY KEY(org, hostId))",
|
|
234
|
+
"CREATE TRIGGER IF NOT EXISTS member_settings_member_remove AFTER DELETE ON member BEGIN DELETE FROM member_settings WHERE org = OLD.organizationId AND subject = OLD.userId; END"
|
|
235
|
+
]
|
|
222
236
|
}
|
|
223
237
|
], { table: "identity_registry_migrations" });
|
|
224
238
|
const auth = betterAuth({
|
|
@@ -226,6 +240,7 @@ async function createIdentityHome(config, ports) {
|
|
|
226
240
|
database: poAdapter(database)
|
|
227
241
|
});
|
|
228
242
|
const roster = await createIssuerRoster(database, config.issuer, config.jwtKeyWrap, now, membership);
|
|
243
|
+
const globalTier = createGlobalTier(database, now, membership);
|
|
229
244
|
async function membership(tx, subject, org) {
|
|
230
245
|
const person = await tx.get("SELECT id FROM user WHERE id = ?", subject);
|
|
231
246
|
const member = await tx.get("SELECT role FROM member WHERE userId = ? AND organizationId = ?", subject, org);
|
|
@@ -813,6 +828,7 @@ async function createIdentityHome(config, ports) {
|
|
|
813
828
|
await tx.run("DELETE FROM identity_outbox WHERE kind='materialize-workspace' AND json_extract(payload,'$.orgId')=?", org);
|
|
814
829
|
for (const table of ["member", "invitation"]) await tx.run(`DELETE FROM ${table} WHERE organizationId=?`, org);
|
|
815
830
|
await tx.run("DELETE FROM identity_workspace WHERE orgId=?", org);
|
|
831
|
+
for (const table of ["member_settings", "host_visibility"]) await tx.run(`DELETE FROM ${table} WHERE org=?`, org);
|
|
816
832
|
await tx.run("DELETE FROM identity_personal_org WHERE organizationId=?", org);
|
|
817
833
|
await tx.run("DELETE FROM first_workspace WHERE organizationId=?", org);
|
|
818
834
|
await tx.run("DELETE FROM organization WHERE id=?", org);
|
|
@@ -982,6 +998,37 @@ async function createIdentityHome(config, ports) {
|
|
|
982
998
|
const text = new TextDecoder().decode(bytes);
|
|
983
999
|
return json ? JSON.parse(text) : text;
|
|
984
1000
|
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Caller of an issuer route: a C1 identity token bound to a current device, or a Better Auth session
|
|
1003
|
+
* cookie. Cookie writes also need `x-po-csrf: 1`, which a cross-site form cannot send.
|
|
1004
|
+
*/
|
|
1005
|
+
async function requestSubject(request, audience, mutating = false) {
|
|
1006
|
+
const origin = request.headers.get("origin");
|
|
1007
|
+
if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
|
|
1008
|
+
const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
|
|
1009
|
+
if (!token) {
|
|
1010
|
+
if (mutating && request.headers.get("x-po-csrf") !== "1") throw new IdentityRefusal(403, "CSRF header required");
|
|
1011
|
+
const subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
|
|
1012
|
+
if (!subject) throw new IdentityRefusal(401, "Sign in required");
|
|
1013
|
+
return subject;
|
|
1014
|
+
}
|
|
1015
|
+
try {
|
|
1016
|
+
const jwks = await auth.api.getJwks();
|
|
1017
|
+
const { payload } = await jwtVerify(token, createLocalJWKSet(jwks), {
|
|
1018
|
+
issuer: config.issuer,
|
|
1019
|
+
...audience === void 0 ? {} : { audience },
|
|
1020
|
+
algorithms: ["ES256"],
|
|
1021
|
+
currentDate: new Date(now() + 3e4)
|
|
1022
|
+
});
|
|
1023
|
+
if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
|
|
1024
|
+
const cnf = payload.cnf;
|
|
1025
|
+
if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
|
|
1026
|
+
await orgRole(payload.sub, payload.org);
|
|
1027
|
+
return payload.sub;
|
|
1028
|
+
} catch {
|
|
1029
|
+
throw new IdentityRefusal(401, "Current identity token required");
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
985
1032
|
async function fetchHandler(request) {
|
|
986
1033
|
let path;
|
|
987
1034
|
try {
|
|
@@ -998,44 +1045,50 @@ async function createIdentityHome(config, ports) {
|
|
|
998
1045
|
const own = path === "/api/networks/own-hub-link";
|
|
999
1046
|
const remove = path === "/api/networks/remove-hub";
|
|
1000
1047
|
if (path === "/api/networks/hub-removal-receipt" && request.method === "GET") return Response.json(await roster.removalReceiptFromHost(request), { headers: { "cache-control": "no-store" } });
|
|
1048
|
+
const visible = /^\/api\/networks\/([^/]+)\/hosts\/visible$/.exec(path);
|
|
1049
|
+
const visibility = /^\/api\/networks\/([^/]+)\/hosts\/([^/]+)\/visibility$/.exec(path);
|
|
1050
|
+
if (visible && request.method === "GET") return Response.json(await globalTier.visibleHosts(await requestSubject(request, visible[1]), visible[1]), { headers: { "cache-control": "no-store" } });
|
|
1051
|
+
if (visibility && request.method === "PUT") {
|
|
1052
|
+
const subject = await requestSubject(request, visibility[1], true);
|
|
1053
|
+
const body = await readBody(request);
|
|
1054
|
+
return Response.json(await globalTier.setHostVisibility(subject, visibility[1], visibility[2], body?.visibility));
|
|
1055
|
+
}
|
|
1056
|
+
if (visible || visibility) return new Response("Method not allowed", { status: 405 });
|
|
1001
1057
|
if (!match && !own && !remove) return new Response("not found", { status: 404 });
|
|
1002
1058
|
if (match?.[2] === "roster" && request.method === "GET" && request.headers.has("x-po-roster-proof")) return Response.json(await roster.rosterFromHost(request, match[1]), { headers: { "cache-control": "no-store" } });
|
|
1003
|
-
const
|
|
1004
|
-
if (origin && origin !== config.issuer && origin !== "po://") throw new IdentityRefusal(403, "Invalid origin");
|
|
1005
|
-
let subject;
|
|
1006
|
-
const token = request.headers.get("authorization")?.match(/^Bearer (.+)$/)?.[1];
|
|
1007
|
-
if (token) try {
|
|
1008
|
-
const jwks = await auth.api.getJwks();
|
|
1009
|
-
const { payload } = await jwtVerify(token, createLocalJWKSet(jwks), {
|
|
1010
|
-
issuer: config.issuer,
|
|
1011
|
-
...match ? { audience: match[1] } : {},
|
|
1012
|
-
algorithms: ["ES256"],
|
|
1013
|
-
currentDate: new Date(now() + 3e4)
|
|
1014
|
-
});
|
|
1015
|
-
if (typeof payload.sub !== "string" || payload.act || typeof payload.org !== "string") throw new Error("Identity token required");
|
|
1016
|
-
const cnf = payload.cnf;
|
|
1017
|
-
if (!await database.get("SELECT id FROM identity_device WHERE subject=? AND jkt=? AND revoked=0 AND (organizationId IS NULL OR organizationId=?)", payload.sub, cnf?.jkt ?? "", payload.org) || (payload.revocation_epoch ?? 0) !== await epoch(database, payload.sub)) throw new Error("Device revoked");
|
|
1018
|
-
await orgRole(payload.sub, payload.org);
|
|
1019
|
-
subject = payload.sub;
|
|
1020
|
-
} catch {
|
|
1021
|
-
throw new IdentityRefusal(401, "Current identity token required");
|
|
1022
|
-
}
|
|
1023
|
-
else subject = (await auth.api.getSession({ headers: request.headers }))?.user.id;
|
|
1024
|
-
if (!subject) throw new IdentityRefusal(401, "Sign in required");
|
|
1059
|
+
const subject = await requestSubject(request, match?.[1]);
|
|
1025
1060
|
if (own && request.method === "POST") return Response.json({ networkId: await personalOrg(subject) });
|
|
1026
1061
|
if (remove && request.method === "POST") return Response.json(await roster.removeHub(subject, await readBody(request)), { headers: { "cache-control": "no-store" } });
|
|
1027
|
-
if (match?.[2] === "roster" && request.method === "GET") return Response.json(await roster.networkRoster(subject, match[1]), { headers: { "cache-control": "no-store" } });
|
|
1062
|
+
if (match?.[2] === "roster" && request.method === "GET") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.networkRoster(subject, match[1])), { headers: { "cache-control": "no-store" } });
|
|
1028
1063
|
if (match && request.method === "POST") {
|
|
1029
1064
|
const body = await readBody(request);
|
|
1030
|
-
if (match[2] === "hosts") return Response.json(await roster.registerRosterHost(subject, match[1], body?.entry));
|
|
1031
|
-
if (match[2] === "changes") return Response.json(await roster.registerRosterChange(subject, match[1], body?.change));
|
|
1065
|
+
if (match[2] === "hosts") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterHost(subject, match[1], body?.entry)));
|
|
1066
|
+
if (match[2] === "changes") return Response.json(await globalTier.memberRosterView(subject, match[1], await roster.registerRosterChange(subject, match[1], body?.change)));
|
|
1032
1067
|
}
|
|
1033
1068
|
return new Response("Method not allowed", { status: 405 });
|
|
1034
1069
|
} catch (error) {
|
|
1035
|
-
if (error instanceof IdentityRefusal || error instanceof RosterRefusal) return Response.json({ error: error.message }, { status: error.status });
|
|
1070
|
+
if (error instanceof IdentityRefusal || error instanceof RosterRefusal || error instanceof GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
|
|
1036
1071
|
if (error instanceof SyntaxError || error instanceof TypeError) return Response.json({ error: "Invalid roster request" }, { status: 400 });
|
|
1037
1072
|
throw error;
|
|
1038
1073
|
}
|
|
1074
|
+
if (path === "/api/account/settings") try {
|
|
1075
|
+
const query = new URL(request.url).searchParams;
|
|
1076
|
+
const org = query.get("org") ?? "";
|
|
1077
|
+
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(org)) throw new IdentityRefusal(400, "Organization required");
|
|
1078
|
+
const headers = { "cache-control": "no-store" };
|
|
1079
|
+
if (request.method === "GET") return Response.json(await globalTier.readMemberSettings(await requestSubject(request, org), org), { headers });
|
|
1080
|
+
if (request.method === "PUT") {
|
|
1081
|
+
const subject = await requestSubject(request, org, true);
|
|
1082
|
+
const expectedHash = query.get("expectedHash");
|
|
1083
|
+
if (!expectedHash) throw new IdentityRefusal(428, "expectedHash required");
|
|
1084
|
+
const yaml = await readBody(request, false);
|
|
1085
|
+
return Response.json(await globalTier.writeMemberSettings(subject, org, yaml, expectedHash), { headers });
|
|
1086
|
+
}
|
|
1087
|
+
return new Response("Method not allowed", { status: 405 });
|
|
1088
|
+
} catch (error) {
|
|
1089
|
+
if (error instanceof IdentityRefusal || error instanceof GlobalTierRefusal) return Response.json({ error: error.message }, { status: error.status });
|
|
1090
|
+
throw error;
|
|
1091
|
+
}
|
|
1039
1092
|
if (!path.startsWith("/api/auth/")) return new Response("not found", { status: 404 });
|
|
1040
1093
|
if (path.replace(/\/+$/, "") === "/api/auth/token") return new Response("Device signature required", { status: 401 });
|
|
1041
1094
|
if (path === "/api/auth/device-key" && request.method === "POST") {
|
|
@@ -1246,6 +1299,7 @@ async function createIdentityHome(config, ports) {
|
|
|
1246
1299
|
return {
|
|
1247
1300
|
database,
|
|
1248
1301
|
...roster,
|
|
1302
|
+
memberRosterView: globalTier.memberRosterView,
|
|
1249
1303
|
fetch: fetchHandler,
|
|
1250
1304
|
personalOrg,
|
|
1251
1305
|
ensurePersonalOrg,
|
|
@@ -108,6 +108,7 @@ async function createIssuerRoster(database, issuer, wrap, now, membership) {
|
|
|
108
108
|
await currentEpoch(tx, network);
|
|
109
109
|
await tx.run("UPDATE identity_roster_epoch SET epoch = epoch + 1 WHERE networkId = ?", network);
|
|
110
110
|
await tx.run("INSERT INTO identity_roster_host (networkId,hostId,subject,entry,enrollmentGeneration) VALUES (?,?,?,?,?) ON CONFLICT(networkId,hostId) DO UPDATE SET entry=excluded.entry,enrollmentGeneration=excluded.enrollmentGeneration,evicted=0,changedEpoch=NULL", network, p.hostId, subject, JSON.stringify(entry), generation);
|
|
111
|
+
if (!held && !cloud) await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, 'member', ?, ?) ON CONFLICT(org, hostId) DO NOTHING", network, p.hostId, subject, now());
|
|
111
112
|
return snapshot(tx, network);
|
|
112
113
|
});
|
|
113
114
|
}
|
|
@@ -108,6 +108,7 @@ async function createIssuerRoster(database, issuer, wrap, now, membership) {
|
|
|
108
108
|
await currentEpoch(tx, network);
|
|
109
109
|
await tx.run("UPDATE identity_roster_epoch SET epoch = epoch + 1 WHERE networkId = ?", network);
|
|
110
110
|
await tx.run("INSERT INTO identity_roster_host (networkId,hostId,subject,entry,enrollmentGeneration) VALUES (?,?,?,?,?) ON CONFLICT(networkId,hostId) DO UPDATE SET entry=excluded.entry,enrollmentGeneration=excluded.enrollmentGeneration,evicted=0,changedEpoch=NULL", network, p.hostId, subject, JSON.stringify(entry), generation);
|
|
111
|
+
if (!held && !cloud) await tx.run("INSERT INTO host_visibility (org, hostId, visibility, setBy, updatedAt) VALUES (?, ?, 'member', ?, ?) ON CONFLICT(org, hostId) DO NOTHING", network, p.hostId, subject, now());
|
|
111
112
|
return snapshot(tx, network);
|
|
112
113
|
});
|
|
113
114
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-identity",
|
|
3
|
-
"version": "0.0.2-alpha.
|
|
3
|
+
"version": "0.0.2-alpha.89",
|
|
4
4
|
"description": "Portable identity home for Po",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
"access": "public"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@agimon-ai/po-core": "0.0.0-alpha.
|
|
51
|
-
"@agimon-ai/po-web-security": "0.0.0-alpha.
|
|
50
|
+
"@agimon-ai/po-core": "0.0.0-alpha.142",
|
|
51
|
+
"@agimon-ai/po-web-security": "0.0.0-alpha.142",
|
|
52
52
|
"@better-auth/expo": "1.7.12",
|
|
53
53
|
"@better-auth/passkey": "1.7.12",
|
|
54
54
|
"@better-auth/sso": "1.7.12",
|
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
"jose": "6.2.2"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
|
-
"@agimon-ai/po-network": "0.0.2-alpha.
|
|
62
|
-
"@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.
|
|
61
|
+
"@agimon-ai/po-network": "0.0.2-alpha.89",
|
|
62
|
+
"@agimon-ai/vibe-lint-plugin-po-core": "0.0.0-alpha.142",
|
|
63
63
|
"@types/node": "26.4.1",
|
|
64
64
|
"tsdown": "0.23.0",
|
|
65
65
|
"typescript": "7.0.2",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"entry": "./src/extensions/server.ts",
|
|
73
73
|
"dist": "./dist/extensions/server.mjs",
|
|
74
74
|
"scopes": [
|
|
75
|
-
"
|
|
75
|
+
"host"
|
|
76
76
|
],
|
|
77
77
|
"contracts": {
|
|
78
78
|
"entry": "./src/exports/apiContracts.ts",
|