or3-provider-sqlite 0.0.31 → 0.0.33
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 +11 -2
- package/dist/module.json +1 -1
- package/dist/runtime/server/admin/stores/sqlite-store.d.ts +141 -2
- package/dist/runtime/server/admin/stores/sqlite-store.js +18 -3
- package/dist/runtime/server/auth/sqlite-auth-workspace-store.d.ts +21 -11
- package/dist/runtime/server/auth/sqlite-auth-workspace-store.js +124 -189
- package/dist/runtime/server/db/migrate.js +3 -1
- package/dist/runtime/server/db/migrations/037_workspace_members_by_user.d.ts +3 -0
- package/dist/runtime/server/db/migrations/037_workspace_members_by_user.js +6 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -288,8 +288,10 @@ model execution there; ordinary sync and other D1 features are unchanged.
|
|
|
288
288
|
|
|
289
289
|
### Workspace store
|
|
290
290
|
|
|
291
|
+
Migration 037 adds a nonunique index on `workspace_members.user_id`. Workspace lists and default-workspace recovery can look up an individual user's memberships directly. Rolling back migration 037 removes the index and preserves membership rows.
|
|
292
|
+
|
|
291
293
|
- `getOrCreateUser` — maps `(provider, provider_user_id)` to internal user (idempotent)
|
|
292
|
-
- `getOrCreateDefaultWorkspace`
|
|
294
|
+
- `getOrCreateDefaultWorkspace` returns the active workspace when its membership is valid. It repairs a stale selection using the earliest live membership and creates a personal workspace on first login.
|
|
293
295
|
- Full workspace CRUD with role-based access checks
|
|
294
296
|
|
|
295
297
|
## Backup
|
|
@@ -386,6 +388,9 @@ or failed builds fall back to installed packages with a warning.
|
|
|
386
388
|
`OR3_LOCAL_PROVIDERS=false` disables local selection. Production builds use the
|
|
387
389
|
installed package, so local development does not publish these changes.
|
|
388
390
|
|
|
391
|
+
Manual runs of **Publish npm package** qualify the selected revision. To
|
|
392
|
+
publish the qualified tarball, push a `v<version>` tag matching `package.json`.
|
|
393
|
+
|
|
389
394
|
### Canonical compaction history reader (unreleased)
|
|
390
395
|
|
|
391
396
|
`canonicalChatHistory: 'v1'` and `readChatHistory` read current `s_threads`/`s_messages`, with explicit workspace membership (owner/editor/viewer), bounded by-ID queries and canonical `(index, order_key, id)` keyset pages. Migration 022 adds transactional per-thread revision triggers. Migration 023 matches the index to legacy missing-order-key normalization and preserves the existing orphan-row cleanup lifecycle; revision bookkeeping does not add a foreign key to otherwise independent sync rows. Current-chat tool result writes do not invalidate ancestor search cursors. The reader never consults retained sync logs. D1 omits the capability.
|
|
@@ -430,7 +435,7 @@ the supported profile is qualified.
|
|
|
430
435
|
|
|
431
436
|
## Instance signup invitations
|
|
432
437
|
|
|
433
|
-
The updated host distinguishes signup invites from existing team invites. Signup invites create a private workspace
|
|
438
|
+
The updated host distinguishes signup invites from existing team invites. Signup invites create a private workspace for the recipient. A team invite also grants the chosen role in the shared workspace. When someone joins from a link or registration form, their first chat opens in their private workspace. They can select the joined team from the workspace switcher. This requires the updated host and rebuilt provider artifacts, rather than the existing published release alone.
|
|
434
439
|
|
|
435
440
|
Native SQLite implements five optional AuthWorkspaceStore methods with one additive signup_invites migration and one immediate acceptance transaction. User, identity mapping, recipient-only workspace membership, active pointer, and acceptance receipt commit together. Replay performs no provisioning writes. D1 deliberately does not advertise these methods. Dates are milliseconds; history pages contain at most 100 rows without hashes, with 90-day terminal retention and cleanup capped at 100 records per create/list call.
|
|
436
441
|
|
|
@@ -559,3 +564,7 @@ A disposable native SQLite qualification on macOS arm64 used 1,000,000 log rows,
|
|
|
559
564
|
| 033 | 034–036 | 0.528 s | 72.44 MiB | 956.80 MiB |
|
|
560
565
|
|
|
561
566
|
Both runs retained every log/canonical row, finished ledger 36 and invalidated the snapshot items. These sampled local measurements do not qualify production hardware, physical allocated space or remote D1 limits; plan additional space for source/rollback backups. Migration 033 preserves malformed payload bytes for subsequent unavailable-record handling and retains its original deterministic UUID mapping and ledger no-rerun behavior.
|
|
567
|
+
|
|
568
|
+
### Files and Projects folders
|
|
569
|
+
|
|
570
|
+
On OR3 Chat hosts that support Files and Projects folders, this provider syncs folder names and item locations as ordinary workspace KV records.
|
package/dist/module.json
CHANGED
|
@@ -1,4 +1,143 @@
|
|
|
1
|
-
import type { AdminUserStore, WorkspaceAccessStore, WorkspaceSettingsStore } from '~~/server/admin/stores/types';
|
|
2
|
-
|
|
1
|
+
import type { AdminUserStore, WorkspaceAccessStore, WorkspaceSettingsStore, WorkspaceSummary } from '~~/server/admin/stores/types';
|
|
2
|
+
type Role = 'owner' | 'editor' | 'viewer';
|
|
3
|
+
interface CustomerSummary {
|
|
4
|
+
userId: string;
|
|
5
|
+
email?: string;
|
|
6
|
+
displayName?: string;
|
|
7
|
+
createdAt: number;
|
|
8
|
+
lastContactAt: number | null;
|
|
9
|
+
}
|
|
10
|
+
interface CustomerPage {
|
|
11
|
+
items: CustomerSummary[];
|
|
12
|
+
nextCursor: string | null;
|
|
13
|
+
}
|
|
14
|
+
interface CustomerWorkspace {
|
|
15
|
+
id: string;
|
|
16
|
+
name: string;
|
|
17
|
+
role: Role;
|
|
18
|
+
ownerUserId: string;
|
|
19
|
+
createdAt: number;
|
|
20
|
+
deleted: boolean;
|
|
21
|
+
deletedAt?: number;
|
|
22
|
+
memberCount: number;
|
|
23
|
+
lastContactAt: number | null;
|
|
24
|
+
}
|
|
25
|
+
declare class SqliteWorkspaceAccessStore implements WorkspaceAccessStore {
|
|
26
|
+
getStorageGenerationCandidates(input: {
|
|
27
|
+
workspaceId: string;
|
|
28
|
+
storageProviderId: 'fs' | 's3';
|
|
29
|
+
retentionSeconds: number;
|
|
30
|
+
limit: number;
|
|
31
|
+
cursor?: string;
|
|
32
|
+
}): Promise<{
|
|
33
|
+
items: {
|
|
34
|
+
generation: import("~~/server/storage/gateway/generation-lifecycle").ExternalStorageGenerationRecord;
|
|
35
|
+
status: "deleted" | "blocked" | "claimed" | "eligible";
|
|
36
|
+
reason: "missing" | "not_current" | "in_use" | "unknown_references" | "active_upload" | "claim_conflict" | "retention" | "proof_incomplete" | null;
|
|
37
|
+
}[];
|
|
38
|
+
complete: boolean;
|
|
39
|
+
nextCursor: string | null;
|
|
40
|
+
observedAt: number;
|
|
41
|
+
workspaceId: string;
|
|
42
|
+
retentionSeconds: number;
|
|
43
|
+
estimatedLogicalBytes: number | null;
|
|
44
|
+
scope: "managed_generations_only";
|
|
45
|
+
legacyIncluded: false;
|
|
46
|
+
}>;
|
|
47
|
+
private get db();
|
|
48
|
+
recordSyncObservation(input: {
|
|
49
|
+
userId: string;
|
|
50
|
+
workspaceId: string;
|
|
51
|
+
operation: 'push' | 'pull' | 'snapshot' | 'cursor';
|
|
52
|
+
observedAt: number;
|
|
53
|
+
outcome: 'success' | 'failure';
|
|
54
|
+
code?: string;
|
|
55
|
+
}): Promise<void>;
|
|
56
|
+
getCustomerSyncObservations(input: {
|
|
57
|
+
userId: string;
|
|
58
|
+
}): Promise<{
|
|
59
|
+
workspaceId: string;
|
|
60
|
+
lastSuccessAt: number | null;
|
|
61
|
+
lastSuccessOperation: string | null;
|
|
62
|
+
lastFailureAt: number | null;
|
|
63
|
+
lastFailureCode: string | null;
|
|
64
|
+
}[]>;
|
|
65
|
+
listMembers(input: {
|
|
66
|
+
workspaceId: string;
|
|
67
|
+
}): Promise<{
|
|
68
|
+
userId: string;
|
|
69
|
+
email: string | undefined;
|
|
70
|
+
role: Role;
|
|
71
|
+
}[]>;
|
|
72
|
+
upsertExistingMember(input: Parameters<SqliteWorkspaceAccessStore['upsertMember']>[0]): Promise<void>;
|
|
73
|
+
upsertMember(input: {
|
|
74
|
+
workspaceId: string;
|
|
75
|
+
emailOrProviderId: string;
|
|
76
|
+
role: Role;
|
|
77
|
+
provider?: string;
|
|
78
|
+
}, allowProvision?: boolean): Promise<void>;
|
|
79
|
+
private unknownMember;
|
|
80
|
+
setMemberRole(input: {
|
|
81
|
+
workspaceId: string;
|
|
82
|
+
userId: string;
|
|
83
|
+
role: Role;
|
|
84
|
+
}): Promise<void>;
|
|
85
|
+
removeMember(input: {
|
|
86
|
+
workspaceId: string;
|
|
87
|
+
userId: string;
|
|
88
|
+
}): Promise<void>;
|
|
89
|
+
listWorkspaces(input: {
|
|
90
|
+
search?: string;
|
|
91
|
+
includeDeleted?: boolean;
|
|
92
|
+
page: number;
|
|
93
|
+
perPage: number;
|
|
94
|
+
}): Promise<{
|
|
95
|
+
items: WorkspaceSummary[];
|
|
96
|
+
total: number;
|
|
97
|
+
}>;
|
|
98
|
+
getWorkspace(input: {
|
|
99
|
+
workspaceId: string;
|
|
100
|
+
}): Promise<WorkspaceSummary | null>;
|
|
101
|
+
createWorkspace(input: {
|
|
102
|
+
name: string;
|
|
103
|
+
description?: string;
|
|
104
|
+
ownerUserId: string;
|
|
105
|
+
}): Promise<{
|
|
106
|
+
workspaceId: string;
|
|
107
|
+
}>;
|
|
108
|
+
softDeleteWorkspace(input: {
|
|
109
|
+
workspaceId: string;
|
|
110
|
+
deletedAt: number;
|
|
111
|
+
}): Promise<void>;
|
|
112
|
+
restoreWorkspace(input: {
|
|
113
|
+
workspaceId: string;
|
|
114
|
+
}): Promise<void>;
|
|
115
|
+
/** Bounded, read-only canonical directory. Keyset-paginated by creation time; never provisions. */
|
|
116
|
+
listCustomers(input: {
|
|
117
|
+
query?: string;
|
|
118
|
+
cursor?: string | null;
|
|
119
|
+
limit: number;
|
|
120
|
+
}): Promise<CustomerPage>;
|
|
121
|
+
/** Batch lookup by internal IDs. Unknown IDs are omitted, never invented. */
|
|
122
|
+
getCustomersByIds(input: {
|
|
123
|
+
userIds: string[];
|
|
124
|
+
}): Promise<CustomerSummary[]>;
|
|
125
|
+
/** Owned workspaces (including retained deleted ones) and memberships for one canonical user. */
|
|
126
|
+
getCustomerWorkspaces(input: {
|
|
127
|
+
userId: string;
|
|
128
|
+
}): Promise<CustomerWorkspace[]>;
|
|
129
|
+
/** Last sync cursor write by this user (server contact, not proof of a completed sync). */
|
|
130
|
+
private withLastContact;
|
|
131
|
+
searchUsers(input: {
|
|
132
|
+
query: string;
|
|
133
|
+
limit?: number;
|
|
134
|
+
}): Promise<{
|
|
135
|
+
userId: string;
|
|
136
|
+
email: string | undefined;
|
|
137
|
+
displayName: string | undefined;
|
|
138
|
+
}[]>;
|
|
139
|
+
}
|
|
140
|
+
export declare function createSqliteWorkspaceAccessStore(): SqliteWorkspaceAccessStore;
|
|
3
141
|
export declare function createSqliteWorkspaceSettingsStore(): WorkspaceSettingsStore;
|
|
4
142
|
export declare function createSqliteAdminUserStore(): AdminUserStore;
|
|
143
|
+
export {};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "h3";
|
|
1
2
|
import { sql } from "kysely";
|
|
2
3
|
import { getSqliteDb } from "../../db/kysely.js";
|
|
3
4
|
import { SqliteExternalStorageGenerationCoordinator } from "../../storage/sqlite-generation-coordinator.js";
|
|
@@ -62,7 +63,10 @@ class SqliteWorkspaceAccessStore {
|
|
|
62
63
|
role: row.role
|
|
63
64
|
}));
|
|
64
65
|
}
|
|
65
|
-
|
|
66
|
+
upsertExistingMember(input) {
|
|
67
|
+
return this.upsertMember(input, false);
|
|
68
|
+
}
|
|
69
|
+
async upsertMember(input, allowProvision = true) {
|
|
66
70
|
const workspace = await this.db.selectFrom("workspaces").select(["id", "deleted"]).where("id", "=", input.workspaceId).executeTakeFirst();
|
|
67
71
|
if (!workspace || workspace.deleted === 1) {
|
|
68
72
|
throw new Error("Workspace not found");
|
|
@@ -70,13 +74,20 @@ class SqliteWorkspaceAccessStore {
|
|
|
70
74
|
const lookup = input.emailOrProviderId.trim();
|
|
71
75
|
const provider = input.provider?.trim();
|
|
72
76
|
const now = nowEpoch();
|
|
77
|
+
let users = this.db.selectFrom("users").select("id");
|
|
78
|
+
if (!allowProvision) {
|
|
79
|
+
users = users.where((eb) => eb.exists(
|
|
80
|
+
eb.selectFrom("auth_accounts").select("user_id").whereRef("auth_accounts.user_id", "=", "users.id")
|
|
81
|
+
));
|
|
82
|
+
}
|
|
73
83
|
let userId = null;
|
|
74
84
|
if (isEmail(lookup)) {
|
|
75
85
|
const normalized = normalizeEmail(lookup);
|
|
76
|
-
const existing = await
|
|
86
|
+
const existing = await users.where("email", "=", normalized).executeTakeFirst();
|
|
77
87
|
if (existing) {
|
|
78
88
|
userId = existing.id;
|
|
79
89
|
} else {
|
|
90
|
+
if (!allowProvision) throw this.unknownMember();
|
|
80
91
|
userId = globalThis.crypto.randomUUID();
|
|
81
92
|
await this.db.insertInto("users").values({
|
|
82
93
|
id: userId,
|
|
@@ -91,12 +102,13 @@ class SqliteWorkspaceAccessStore {
|
|
|
91
102
|
if (account) {
|
|
92
103
|
userId = account.user_id;
|
|
93
104
|
} else {
|
|
94
|
-
const byUserId = await
|
|
105
|
+
const byUserId = await users.where("id", "=", lookup).executeTakeFirst();
|
|
95
106
|
if (byUserId) {
|
|
96
107
|
userId = byUserId.id;
|
|
97
108
|
}
|
|
98
109
|
}
|
|
99
110
|
if (!userId) {
|
|
111
|
+
if (!allowProvision) throw this.unknownMember();
|
|
100
112
|
userId = globalThis.crypto.randomUUID();
|
|
101
113
|
await this.db.insertInto("users").values({
|
|
102
114
|
id: userId,
|
|
@@ -133,6 +145,9 @@ class SqliteWorkspaceAccessStore {
|
|
|
133
145
|
created_at: now
|
|
134
146
|
}).execute();
|
|
135
147
|
}
|
|
148
|
+
unknownMember() {
|
|
149
|
+
return createError({ statusCode: 404, statusMessage: "Send a team invite so this person can register." });
|
|
150
|
+
}
|
|
136
151
|
async setMemberRole(input) {
|
|
137
152
|
await this.db.transaction().execute(async (tx) => {
|
|
138
153
|
const member = await tx.selectFrom("workspace_members").select("role").where("workspace_id", "=", input.workspaceId).where("user_id", "=", input.userId).executeTakeFirst();
|
|
@@ -6,6 +6,22 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { AuthWorkspaceStore, SignupInviteSummary, SignupProvisionResult, SignupValidationResult, InviteProvisionResult, InviteValidationResult } from '~~/server/auth/store/types';
|
|
8
8
|
import type { WorkspaceRole } from '~~/app/core/hooks/hook-types';
|
|
9
|
+
type TeamInviteInput = {
|
|
10
|
+
workspaceId: string;
|
|
11
|
+
email: string;
|
|
12
|
+
tokenHash: string;
|
|
13
|
+
};
|
|
14
|
+
type TeamInviteIdentity = {
|
|
15
|
+
provider: string;
|
|
16
|
+
providerUserId: string;
|
|
17
|
+
displayName?: string;
|
|
18
|
+
};
|
|
19
|
+
type TeamInviteResult = InviteProvisionResult & {
|
|
20
|
+
personalWorkspace?: {
|
|
21
|
+
workspaceId: string;
|
|
22
|
+
workspaceName: string;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
9
25
|
export declare class SqliteAuthWorkspaceStore implements AuthWorkspaceStore {
|
|
10
26
|
constructor();
|
|
11
27
|
private cleanupSignupInvites;
|
|
@@ -77,7 +93,7 @@ export declare class SqliteAuthWorkspaceStore implements AuthWorkspaceStore {
|
|
|
77
93
|
userId: string;
|
|
78
94
|
workspaceId: string;
|
|
79
95
|
}): Promise<WorkspaceRole | null>;
|
|
80
|
-
listUserWorkspaces(userId: string): Promise<Array<{
|
|
96
|
+
listUserWorkspaces(userId: string, workspaceId?: string): Promise<Array<{
|
|
81
97
|
id: string;
|
|
82
98
|
name: string;
|
|
83
99
|
description?: string | null;
|
|
@@ -145,14 +161,8 @@ export declare class SqliteAuthWorkspaceStore implements AuthWorkspaceStore {
|
|
|
145
161
|
email: string;
|
|
146
162
|
tokenHash: string;
|
|
147
163
|
}): Promise<InviteValidationResult>;
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
providerUserId: string;
|
|
151
|
-
email: string;
|
|
152
|
-
displayName?: string;
|
|
153
|
-
workspaceId: string;
|
|
154
|
-
tokenHash: string;
|
|
155
|
-
}): Promise<InviteProvisionResult>;
|
|
164
|
+
acceptInviteWithPersonalWorkspace(input: TeamInviteInput & TeamInviteIdentity): Promise<TeamInviteResult>;
|
|
165
|
+
acceptInviteAndProvisionUser(input: TeamInviteInput & TeamInviteIdentity, personal?: boolean): Promise<TeamInviteResult>;
|
|
156
166
|
consumeInvite(input: {
|
|
157
167
|
workspaceId: string;
|
|
158
168
|
email: string;
|
|
@@ -167,8 +177,8 @@ export declare class SqliteAuthWorkspaceStore implements AuthWorkspaceStore {
|
|
|
167
177
|
}>;
|
|
168
178
|
private getOrCreateUserInD1;
|
|
169
179
|
private validateInviteInD1;
|
|
170
|
-
private
|
|
180
|
+
private acceptTeamInviteInD1;
|
|
171
181
|
private consumeInviteInD1;
|
|
172
|
-
private inviteProvisionFailureInD1;
|
|
173
182
|
}
|
|
174
183
|
export declare function createSqliteAuthWorkspaceStore(): AuthWorkspaceStore;
|
|
184
|
+
export {};
|
|
@@ -9,6 +9,9 @@ function nowEpoch() {
|
|
|
9
9
|
function normalizeEmail(email) {
|
|
10
10
|
return email.trim().toLowerCase();
|
|
11
11
|
}
|
|
12
|
+
const liveInviteWorkspace = "EXISTS (SELECT 1 FROM workspaces WHERE id = auth_invites.workspace_id AND deleted = 0)";
|
|
13
|
+
const currentMembership = `EXISTS (SELECT 1 FROM workspace_members m JOIN workspaces w ON w.id = m.workspace_id
|
|
14
|
+
WHERE m.user_id = users.id AND m.workspace_id = users.active_workspace_id AND w.deleted = 0)`;
|
|
12
15
|
export class SqliteAuthWorkspaceStore {
|
|
13
16
|
constructor() {
|
|
14
17
|
if (isD1Driver()) {
|
|
@@ -204,7 +207,7 @@ export class SqliteAuthWorkspaceStore {
|
|
|
204
207
|
const membership = await db.selectFrom("workspace_members").innerJoin("workspaces", "workspaces.id", "workspace_members.workspace_id").select([
|
|
205
208
|
"workspaces.id",
|
|
206
209
|
"workspaces.name"
|
|
207
|
-
]).where("workspace_members.user_id", "=", userId).where("workspaces.deleted", "=", 0).orderBy("workspace_members.created_at", "asc").executeTakeFirst();
|
|
210
|
+
]).where("workspace_members.user_id", "=", userId).where("workspaces.deleted", "=", 0).orderBy("workspace_members.created_at", "asc").limit(1).executeTakeFirst();
|
|
208
211
|
if (membership) {
|
|
209
212
|
await db.updateTable("users").set({ active_workspace_id: membership.id }).where("id", "=", userId).execute();
|
|
210
213
|
return {
|
|
@@ -261,28 +264,29 @@ export class SqliteAuthWorkspaceStore {
|
|
|
261
264
|
}
|
|
262
265
|
async getWorkspaceRole(input) {
|
|
263
266
|
const db = this.db;
|
|
264
|
-
const member = await db.selectFrom("workspace_members").select("role").where("workspace_id", "=", input.workspaceId).where("user_id", "=", input.userId).executeTakeFirst();
|
|
267
|
+
const member = await db.selectFrom("workspace_members").innerJoin("workspaces", "workspaces.id", "workspace_members.workspace_id").select("workspace_members.role").where("workspaces.deleted", "=", 0).where("workspace_members.workspace_id", "=", input.workspaceId).where("user_id", "=", input.userId).executeTakeFirst();
|
|
265
268
|
if (!member) return null;
|
|
266
269
|
return member.role;
|
|
267
270
|
}
|
|
268
|
-
async listUserWorkspaces(userId) {
|
|
271
|
+
async listUserWorkspaces(userId, workspaceId) {
|
|
269
272
|
const db = this.db;
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const rows = await db.selectFrom("workspace_members").innerJoin("workspaces", "workspaces.id", "workspace_members.workspace_id").select([
|
|
273
|
+
let query = db.selectFrom("workspace_members").innerJoin("workspaces", "workspaces.id", "workspace_members.workspace_id").leftJoin("users", "users.id", "workspace_members.user_id").select([
|
|
274
|
+
"users.active_workspace_id",
|
|
273
275
|
"workspaces.id",
|
|
274
276
|
"workspaces.name",
|
|
275
277
|
"workspaces.description",
|
|
276
278
|
"workspaces.created_at",
|
|
277
279
|
"workspace_members.role"
|
|
278
|
-
]).where("workspace_members.user_id", "=", userId).where("workspaces.deleted", "=", 0)
|
|
280
|
+
]).where("workspace_members.user_id", "=", userId).where("workspaces.deleted", "=", 0);
|
|
281
|
+
if (workspaceId !== void 0) query = query.where("workspace_members.workspace_id", "=", workspaceId);
|
|
282
|
+
const rows = await query.execute();
|
|
279
283
|
return rows.map((r) => ({
|
|
280
284
|
id: r.id,
|
|
281
285
|
name: r.name,
|
|
282
286
|
description: r.description,
|
|
283
287
|
role: r.role,
|
|
284
288
|
createdAt: r.created_at,
|
|
285
|
-
isActive: r.id ===
|
|
289
|
+
isActive: r.id === r.active_workspace_id
|
|
286
290
|
}));
|
|
287
291
|
}
|
|
288
292
|
async createWorkspace(input) {
|
|
@@ -464,7 +468,7 @@ export class SqliteAuthWorkspaceStore {
|
|
|
464
468
|
const invite = raw.prepare(
|
|
465
469
|
`SELECT role, status, email, expires_at
|
|
466
470
|
FROM auth_invites
|
|
467
|
-
WHERE workspace_id = ? AND token_hash = ?
|
|
471
|
+
WHERE workspace_id = ? AND token_hash = ? AND ${liveInviteWorkspace}
|
|
468
472
|
LIMIT 1`
|
|
469
473
|
).get(input.workspaceId, input.tokenHash);
|
|
470
474
|
if (!invite) return { ok: false, reason: "not_found" };
|
|
@@ -478,19 +482,20 @@ export class SqliteAuthWorkspaceStore {
|
|
|
478
482
|
}
|
|
479
483
|
return { ok: true, role: invite.role };
|
|
480
484
|
}
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
+
acceptInviteWithPersonalWorkspace(input) {
|
|
486
|
+
return this.acceptInviteAndProvisionUser(input, true);
|
|
487
|
+
}
|
|
488
|
+
async acceptInviteAndProvisionUser(input, personal = false) {
|
|
489
|
+
if (isD1Driver()) return this.acceptTeamInviteInD1(input, input, personal);
|
|
485
490
|
this.db;
|
|
486
491
|
const raw = getRawDb();
|
|
487
|
-
const now = nowEpoch();
|
|
488
492
|
const normalizedEmail = normalizeEmail(input.email);
|
|
489
493
|
return raw.transaction(() => {
|
|
494
|
+
const now = nowEpoch();
|
|
490
495
|
const invite = raw.prepare(
|
|
491
496
|
`SELECT id, role, status, email, expires_at
|
|
492
497
|
FROM auth_invites
|
|
493
|
-
WHERE workspace_id = ? AND token_hash = ?
|
|
498
|
+
WHERE workspace_id = ? AND token_hash = ? AND ${liveInviteWorkspace}
|
|
494
499
|
LIMIT 1`
|
|
495
500
|
).get(input.workspaceId, input.tokenHash);
|
|
496
501
|
if (!invite) return { ok: false, reason: "not_found" };
|
|
@@ -526,6 +531,20 @@ export class SqliteAuthWorkspaceStore {
|
|
|
526
531
|
).run(uid(), userId, input.provider, input.providerUserId, now);
|
|
527
532
|
}
|
|
528
533
|
this.onInviteProvisionStep("user_created");
|
|
534
|
+
let personalWorkspace;
|
|
535
|
+
if (personal) {
|
|
536
|
+
const hasActive = !createdUser && raw.prepare(`SELECT 1 FROM users WHERE id = ? AND ${currentMembership}`).get(userId);
|
|
537
|
+
if (!hasActive) {
|
|
538
|
+
const id = uid();
|
|
539
|
+
const name = "My Workspace";
|
|
540
|
+
raw.prepare("INSERT INTO workspaces (id, name, owner_user_id, created_at) VALUES (?, ?, ?, ?)").run(id, name, userId, now);
|
|
541
|
+
raw.prepare("INSERT INTO workspace_members (id, workspace_id, user_id, role, created_at) VALUES (?, ?, ?, 'owner', ?)").run(uid(), id, userId, now);
|
|
542
|
+
raw.prepare("UPDATE users SET active_workspace_id = ? WHERE id = ?").run(id, userId);
|
|
543
|
+
personalWorkspace = { workspaceId: id, workspaceName: name };
|
|
544
|
+
}
|
|
545
|
+
} else {
|
|
546
|
+
raw.prepare("UPDATE users SET active_workspace_id = ? WHERE id = ?").run(input.workspaceId, userId);
|
|
547
|
+
}
|
|
529
548
|
const existingMembership = raw.prepare(
|
|
530
549
|
`SELECT id FROM workspace_members
|
|
531
550
|
WHERE workspace_id = ? AND user_id = ?
|
|
@@ -542,10 +561,6 @@ export class SqliteAuthWorkspaceStore {
|
|
|
542
561
|
VALUES (?, ?, ?, ?, ?)`
|
|
543
562
|
).run(uid(), input.workspaceId, userId, invite.role, now);
|
|
544
563
|
}
|
|
545
|
-
raw.prepare("UPDATE users SET active_workspace_id = ? WHERE id = ?").run(
|
|
546
|
-
input.workspaceId,
|
|
547
|
-
userId
|
|
548
|
-
);
|
|
549
564
|
this.onInviteProvisionStep("membership_created");
|
|
550
565
|
const consumed = raw.prepare(
|
|
551
566
|
`UPDATE auth_invites
|
|
@@ -560,7 +575,8 @@ export class SqliteAuthWorkspaceStore {
|
|
|
560
575
|
ok: true,
|
|
561
576
|
userId,
|
|
562
577
|
role: invite.role,
|
|
563
|
-
createdUser
|
|
578
|
+
createdUser,
|
|
579
|
+
...personalWorkspace ? { personalWorkspace } : {}
|
|
564
580
|
};
|
|
565
581
|
}).immediate();
|
|
566
582
|
}
|
|
@@ -570,9 +586,9 @@ export class SqliteAuthWorkspaceStore {
|
|
|
570
586
|
}
|
|
571
587
|
this.db;
|
|
572
588
|
const raw = getRawDb();
|
|
573
|
-
const now = nowEpoch();
|
|
574
589
|
const normalized = normalizeEmail(input.email);
|
|
575
590
|
return raw.transaction(() => {
|
|
591
|
+
const now = nowEpoch();
|
|
576
592
|
raw.prepare(
|
|
577
593
|
`UPDATE auth_invites
|
|
578
594
|
SET status = 'expired', updated_at = ?
|
|
@@ -584,7 +600,7 @@ export class SqliteAuthWorkspaceStore {
|
|
|
584
600
|
`SELECT *
|
|
585
601
|
FROM auth_invites
|
|
586
602
|
WHERE workspace_id = ?
|
|
587
|
-
AND email = ?
|
|
603
|
+
AND email = ? AND ${liveInviteWorkspace}
|
|
588
604
|
ORDER BY created_at ASC
|
|
589
605
|
LIMIT 1`
|
|
590
606
|
).get(input.workspaceId, normalized);
|
|
@@ -689,7 +705,7 @@ export class SqliteAuthWorkspaceStore {
|
|
|
689
705
|
const [invite] = await d1All(
|
|
690
706
|
`SELECT role, status, email, expires_at
|
|
691
707
|
FROM auth_invites
|
|
692
|
-
WHERE workspace_id = ? AND token_hash = ?
|
|
708
|
+
WHERE workspace_id = ? AND token_hash = ? AND ${liveInviteWorkspace}
|
|
693
709
|
LIMIT 1`,
|
|
694
710
|
input.workspaceId,
|
|
695
711
|
input.tokenHash
|
|
@@ -705,180 +721,99 @@ export class SqliteAuthWorkspaceStore {
|
|
|
705
721
|
}
|
|
706
722
|
return { ok: true, role: invite.role };
|
|
707
723
|
}
|
|
708
|
-
async
|
|
724
|
+
async acceptTeamInviteInD1(input, identity, personal = false) {
|
|
725
|
+
const email = normalizeEmail(input.email);
|
|
726
|
+
const candidate = uid();
|
|
727
|
+
const privateId = personal ? uid() : void 0;
|
|
709
728
|
const now = nowEpoch();
|
|
710
|
-
const
|
|
711
|
-
const
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
{
|
|
735
|
-
sql: `
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
SELECT ?, ?, ?, role, ?
|
|
757
|
-
FROM auth_invites
|
|
758
|
-
WHERE workspace_id = ?
|
|
759
|
-
AND token_hash = ?
|
|
760
|
-
AND status = 'accepted'
|
|
761
|
-
AND accepted_user_id = ?
|
|
729
|
+
const principal = "provider" in identity ? identity : null;
|
|
730
|
+
const ownerSql = principal ? "(SELECT user_id FROM auth_accounts WHERE provider = ? AND provider_user_id = ?)" : "?";
|
|
731
|
+
const ownerParameters = "acceptedUserId" in identity ? [identity.acceptedUserId] : [identity.provider, identity.providerUserId];
|
|
732
|
+
const invite = [input.workspaceId, input.tokenHash, email];
|
|
733
|
+
const inviteWhere = `workspace_id = ? AND token_hash = ? AND email = ? AND ${liveInviteWorkspace}`;
|
|
734
|
+
const statements = [{
|
|
735
|
+
sql: `SELECT json_extract('{}', CASE WHEN (SELECT expires_at FROM auth_invites
|
|
736
|
+
WHERE ${inviteWhere} AND status = 'pending' ORDER BY created_at, id LIMIT 1) > unixepoch()
|
|
737
|
+
THEN '$' ELSE 'OR3_TEAM_INVITE_UNAVAILABLE' END)`,
|
|
738
|
+
parameters: invite
|
|
739
|
+
}];
|
|
740
|
+
if (principal) {
|
|
741
|
+
statements.push({
|
|
742
|
+
sql: `INSERT INTO users (id, email, display_name, created_at)
|
|
743
|
+
SELECT ?, ?, ?, ? WHERE ${ownerSql} IS NULL`,
|
|
744
|
+
parameters: [candidate, email, principal.displayName ?? null, now, ...ownerParameters]
|
|
745
|
+
}, {
|
|
746
|
+
sql: `INSERT INTO auth_accounts (id, user_id, provider, provider_user_id, created_at)
|
|
747
|
+
SELECT ?, id, ?, ?, ? FROM users WHERE id = ?`,
|
|
748
|
+
parameters: [uid(), principal.provider, principal.providerUserId, now, candidate]
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
const privateWorkspaceStatement = statements.length;
|
|
752
|
+
if (privateId) {
|
|
753
|
+
statements.push({
|
|
754
|
+
sql: `INSERT INTO workspaces (id, name, owner_user_id, created_at)
|
|
755
|
+
SELECT ?, 'My Workspace', id, ? FROM users WHERE id = ${ownerSql} AND NOT ${currentMembership}`,
|
|
756
|
+
parameters: [privateId, now, ...ownerParameters]
|
|
757
|
+
}, {
|
|
758
|
+
sql: `INSERT INTO workspace_members (id, workspace_id, user_id, role, created_at)
|
|
759
|
+
SELECT ?, id, owner_user_id, 'owner', ? FROM workspaces WHERE id = ?`,
|
|
760
|
+
parameters: [uid(), now, privateId]
|
|
761
|
+
}, {
|
|
762
|
+
sql: `UPDATE users SET active_workspace_id = ? WHERE id = (SELECT owner_user_id FROM workspaces WHERE id = ?)`,
|
|
763
|
+
parameters: [privateId, privateId]
|
|
764
|
+
});
|
|
765
|
+
} else {
|
|
766
|
+
statements.push({
|
|
767
|
+
sql: `UPDATE users SET active_workspace_id = ? WHERE id = ${ownerSql}`,
|
|
768
|
+
parameters: [input.workspaceId, ...ownerParameters]
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
statements.push({
|
|
772
|
+
sql: `INSERT INTO workspace_members (id, workspace_id, user_id, role, created_at)
|
|
773
|
+
SELECT ?, workspace_id, ${ownerSql}, role, ? FROM auth_invites
|
|
774
|
+
WHERE ${inviteWhere} AND status = 'pending' ORDER BY created_at, id LIMIT 1
|
|
762
775
|
ON CONFLICT(workspace_id, user_id) DO UPDATE SET role = excluded.role`,
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
SELECT 1 FROM workspace_members
|
|
778
|
-
WHERE workspace_id = ? AND user_id = ?
|
|
779
|
-
)`,
|
|
780
|
-
parameters: [input.workspaceId, userId, input.workspaceId, userId]
|
|
781
|
-
}
|
|
782
|
-
]);
|
|
783
|
-
if ((results[0]?.meta?.changes ?? 0) !== 1) {
|
|
784
|
-
return this.inviteProvisionFailureInD1(input.workspaceId, normalizedEmail, input.tokenHash);
|
|
776
|
+
parameters: [uid(), ...ownerParameters, now, ...invite]
|
|
777
|
+
}, {
|
|
778
|
+
sql: `UPDATE auth_invites SET status = 'accepted', accepted_at = ?, accepted_user_id = ${ownerSql}, updated_at = ?
|
|
779
|
+
WHERE id = (SELECT id FROM auth_invites WHERE ${inviteWhere} AND status = 'pending' ORDER BY created_at, id LIMIT 1)
|
|
780
|
+
RETURNING accepted_user_id AS userId, role`,
|
|
781
|
+
parameters: [now, ...ownerParameters, now, ...invite]
|
|
782
|
+
});
|
|
783
|
+
let rows;
|
|
784
|
+
try {
|
|
785
|
+
rows = await d1Batch(statements);
|
|
786
|
+
} catch (error) {
|
|
787
|
+
if (!String(error).includes("OR3_TEAM_INVITE_UNAVAILABLE")) throw error;
|
|
788
|
+
const validation = await this.validateInviteInD1(input);
|
|
789
|
+
return validation.ok ? { ok: false, reason: "already_used" } : validation;
|
|
785
790
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
791
|
+
const row = rows.at(-1)?.results?.[0];
|
|
792
|
+
if (!row) throw new Error("Missing atomic invitation receipt");
|
|
793
|
+
const createdUser = row.userId === candidate;
|
|
794
|
+
const createdPrivate = privateId !== void 0 && Number(rows[privateWorkspaceStatement]?.meta?.changes) === 1;
|
|
795
|
+
return {
|
|
796
|
+
ok: true,
|
|
797
|
+
...row,
|
|
798
|
+
createdUser,
|
|
799
|
+
...createdPrivate ? { personalWorkspace: { workspaceId: privateId, workspaceName: "My Workspace" } } : {}
|
|
800
|
+
};
|
|
789
801
|
}
|
|
790
802
|
async consumeInviteInD1(input) {
|
|
791
|
-
const
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
AND expires_at <= ?`,
|
|
798
|
-
now,
|
|
799
|
-
input.workspaceId,
|
|
800
|
-
now
|
|
801
|
-
);
|
|
802
|
-
const [invite] = await d1All(
|
|
803
|
-
`SELECT * FROM auth_invites
|
|
804
|
-
WHERE workspace_id = ? AND email = ?
|
|
805
|
-
ORDER BY created_at ASC
|
|
806
|
-
LIMIT 1`,
|
|
807
|
-
input.workspaceId,
|
|
808
|
-
normalized
|
|
809
|
-
);
|
|
810
|
-
if (!invite) return { ok: false, reason: "not_found" };
|
|
811
|
-
if (invite.status === "revoked") return { ok: false, reason: "revoked" };
|
|
812
|
-
if (invite.status === "accepted") return { ok: false, reason: "already_used" };
|
|
813
|
-
if (invite.status === "expired" || invite.expires_at <= now) {
|
|
814
|
-
return { ok: false, reason: "expired" };
|
|
815
|
-
}
|
|
816
|
-
if (invite.token_hash !== input.tokenHash) {
|
|
817
|
-
return { ok: false, reason: "token_mismatch" };
|
|
818
|
-
}
|
|
819
|
-
const results = await d1Batch([
|
|
820
|
-
{
|
|
821
|
-
sql: `UPDATE auth_invites
|
|
822
|
-
SET status = 'accepted', accepted_at = ?, accepted_user_id = ?, updated_at = ?
|
|
823
|
-
WHERE id = ? AND status = 'pending' AND token_hash = ?`,
|
|
824
|
-
parameters: [
|
|
825
|
-
now,
|
|
826
|
-
input.acceptedUserId,
|
|
827
|
-
now,
|
|
828
|
-
invite.id,
|
|
829
|
-
input.tokenHash
|
|
830
|
-
]
|
|
831
|
-
},
|
|
832
|
-
{
|
|
833
|
-
sql: `INSERT INTO workspace_members (
|
|
834
|
-
id, workspace_id, user_id, role, created_at
|
|
835
|
-
)
|
|
836
|
-
SELECT ?, ?, ?, role, ?
|
|
837
|
-
FROM auth_invites
|
|
838
|
-
WHERE id = ?
|
|
839
|
-
AND status = 'accepted'
|
|
840
|
-
AND accepted_user_id = ?
|
|
841
|
-
ON CONFLICT(workspace_id, user_id) DO UPDATE SET role = excluded.role`,
|
|
842
|
-
parameters: [
|
|
843
|
-
uid(),
|
|
844
|
-
input.workspaceId,
|
|
845
|
-
input.acceptedUserId,
|
|
846
|
-
now,
|
|
847
|
-
invite.id,
|
|
848
|
-
input.acceptedUserId
|
|
849
|
-
]
|
|
850
|
-
},
|
|
851
|
-
{
|
|
852
|
-
sql: `UPDATE users SET active_workspace_id = ?
|
|
853
|
-
WHERE id = ?
|
|
854
|
-
AND EXISTS (
|
|
855
|
-
SELECT 1 FROM workspace_members
|
|
856
|
-
WHERE workspace_id = ? AND user_id = ?
|
|
857
|
-
)`,
|
|
858
|
-
parameters: [
|
|
859
|
-
input.workspaceId,
|
|
860
|
-
input.acceptedUserId,
|
|
803
|
+
const result = await this.acceptTeamInviteInD1(input, { acceptedUserId: input.acceptedUserId });
|
|
804
|
+
if (!result.ok) {
|
|
805
|
+
if (result.reason === "email_mismatch") return { ok: false, reason: "not_found" };
|
|
806
|
+
if (result.reason === "not_found") {
|
|
807
|
+
const [known] = await d1All(
|
|
808
|
+
`SELECT 1 FROM auth_invites WHERE workspace_id = ? AND email = ? AND ${liveInviteWorkspace} LIMIT 1`,
|
|
861
809
|
input.workspaceId,
|
|
862
|
-
input.
|
|
863
|
-
|
|
810
|
+
normalizeEmail(input.email)
|
|
811
|
+
);
|
|
812
|
+
if (known) return { ok: false, reason: "token_mismatch" };
|
|
864
813
|
}
|
|
865
|
-
|
|
866
|
-
if ((results[0]?.meta?.changes ?? 0) !== 1) {
|
|
867
|
-
const [latest] = await d1All("SELECT status FROM auth_invites WHERE id = ?", invite.id);
|
|
868
|
-
if (!latest) return { ok: false, reason: "not_found" };
|
|
869
|
-
if (latest.status === "revoked") return { ok: false, reason: "revoked" };
|
|
870
|
-
if (latest.status === "accepted") return { ok: false, reason: "already_used" };
|
|
871
|
-
return { ok: false, reason: "expired" };
|
|
814
|
+
return { ok: false, reason: result.reason };
|
|
872
815
|
}
|
|
873
|
-
return { ok: true, role:
|
|
874
|
-
}
|
|
875
|
-
async inviteProvisionFailureInD1(workspaceId, email, tokenHash) {
|
|
876
|
-
const validation = await this.validateInviteInD1({
|
|
877
|
-
workspaceId,
|
|
878
|
-
email,
|
|
879
|
-
tokenHash
|
|
880
|
-
});
|
|
881
|
-
return validation.ok ? { ok: false, reason: "already_used" } : validation;
|
|
816
|
+
return { ok: true, role: result.role };
|
|
882
817
|
}
|
|
883
818
|
}
|
|
884
819
|
export function createSqliteAuthWorkspaceStore() {
|
|
@@ -74,6 +74,7 @@ import * as m033 from "./migrations/033_tool_result_operation_ids.js";
|
|
|
74
74
|
import * as m034 from "./migrations/034_sync_intent_fingerprint.js";
|
|
75
75
|
import * as m035 from "./migrations/035_sync_unavailable_records.js";
|
|
76
76
|
import * as m036 from "./migrations/036_sync_history_incarnation.js";
|
|
77
|
+
import * as m037 from "./migrations/037_workspace_members_by_user.js";
|
|
77
78
|
import { readHistoryIncarnation } from "../sync/history-incarnation.js";
|
|
78
79
|
const migrations = {
|
|
79
80
|
"001_init": m001,
|
|
@@ -111,7 +112,8 @@ const migrations = {
|
|
|
111
112
|
"033_tool_result_operation_ids": m033,
|
|
112
113
|
"034_sync_intent_fingerprint": m034,
|
|
113
114
|
"035_sync_unavailable_records": m035,
|
|
114
|
-
"036_sync_history_incarnation": m036
|
|
115
|
+
"036_sync_history_incarnation": m036,
|
|
116
|
+
"037_workspace_members_by_user": m037
|
|
115
117
|
};
|
|
116
118
|
class StaticMigrationProvider {
|
|
117
119
|
async getMigrations() {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export async function up(db) {
|
|
2
|
+
await db.schema.createIndex("idx_workspace_members_user").ifNotExists().on("workspace_members").column("user_id").execute();
|
|
3
|
+
}
|
|
4
|
+
export async function down(db) {
|
|
5
|
+
await db.schema.dropIndex("idx_workspace_members_user").ifExists().execute();
|
|
6
|
+
}
|