@ankhorage/infra 0.3.1 → 0.3.3

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.
Files changed (32) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -2
  3. package/dist/adapters/minikube/auth/supabase/index.d.ts.map +1 -1
  4. package/dist/adapters/minikube/auth/supabase/index.js +12 -161
  5. package/dist/adapters/minikube/auth/supabase/index.js.map +1 -1
  6. package/dist/adapters/minikube/auth/supabase/profile.d.ts +21 -0
  7. package/dist/adapters/minikube/auth/supabase/profile.d.ts.map +1 -0
  8. package/dist/adapters/minikube/auth/supabase/profile.js +452 -0
  9. package/dist/adapters/minikube/auth/supabase/profile.js.map +1 -0
  10. package/dist/adapters/minikube/base/index.d.ts.map +1 -1
  11. package/dist/adapters/minikube/base/index.js +849 -53
  12. package/dist/adapters/minikube/base/index.js.map +1 -1
  13. package/dist/{cli.d.ts → cli/bin.d.ts} +3 -3
  14. package/dist/cli/bin.d.ts.map +1 -0
  15. package/dist/{cli.js → cli/bin.js} +3 -3
  16. package/dist/cli/bin.js.map +1 -0
  17. package/dist/readme-usage.js +1 -1
  18. package/dist/readme-usage.js.map +1 -1
  19. package/package.json +2 -2
  20. package/src/adapters/minikube/auth/supabase/index.test.ts +152 -18
  21. package/src/adapters/minikube/auth/supabase/index.ts +16 -203
  22. package/src/adapters/minikube/auth/supabase/profile.integration.test.ts +860 -0
  23. package/src/adapters/minikube/auth/supabase/profile.ts +526 -0
  24. package/src/adapters/minikube/base/index.test.ts +100 -6
  25. package/src/adapters/minikube/base/index.ts +879 -53
  26. package/src/{cli.ts → cli/bin.ts} +3 -3
  27. package/src/{cli.test.ts → cli/cli.test.ts} +3 -3
  28. package/src/index.test.ts +13 -2
  29. package/src/package.test.ts +1 -1
  30. package/src/readme-usage.ts +1 -1
  31. package/dist/cli.d.ts.map +0 -1
  32. package/dist/cli.js.map +0 -1
@@ -0,0 +1,452 @@
1
+ import { createHash } from 'node:crypto';
2
+ const DEFAULT_PROFILE_FIELDS = ['email', 'firstName', 'lastName'];
3
+ const DEFAULT_PROFILE_PRIMARY_KEY = 'authUserId';
4
+ const DEFAULT_PROFILE_CREATE_STRATEGY = 'trigger';
5
+ const DEFAULT_PROFILE_UPDATE_STRATEGY = 'api';
6
+ const PROFILE_POLICY_VERSION = 1;
7
+ const PROFILE_RECONCILER_VERSION = 1;
8
+ const PROFILE_ARTIFACT_KEY = 'auth.profile';
9
+ export const MANAGED_PROFILE_COLUMNS = [
10
+ 'email',
11
+ 'display_name',
12
+ 'first_name',
13
+ 'last_name',
14
+ 'avatar_url',
15
+ 'username',
16
+ 'phone',
17
+ ];
18
+ export function resolveSupabaseProfileModel(manifest) {
19
+ const table = normalizeIdentifier(manifest.auth?.profile?.table ?? '');
20
+ const fields = normalizeFieldList(manifest.auth?.profile?.fields);
21
+ const primaryKey = manifest.auth?.profile?.primaryKey ?? DEFAULT_PROFILE_PRIMARY_KEY;
22
+ const createStrategy = manifest.auth?.profile?.createStrategy ?? DEFAULT_PROFILE_CREATE_STRATEGY;
23
+ const updateStrategy = manifest.auth?.profile?.updateStrategy ?? DEFAULT_PROFILE_UPDATE_STRATEGY;
24
+ const columns = resolveProfileColumns(fields);
25
+ const hash = table
26
+ ? getProfileDesiredStateHash({
27
+ table,
28
+ primaryKey,
29
+ createStrategy,
30
+ updateStrategy,
31
+ columns,
32
+ })
33
+ : '';
34
+ return {
35
+ enabled: table.length > 0,
36
+ table,
37
+ primaryKey,
38
+ createStrategy,
39
+ updateStrategy,
40
+ columns,
41
+ desiredStateHash: hash,
42
+ };
43
+ }
44
+ export function getSupabaseProfileReconciliation(profileModel) {
45
+ const table = quoteIdentifier(profileModel.table);
46
+ const functionName = quoteIdentifier(`handle_new_${profileModel.table}_user`);
47
+ const triggerName = quoteIdentifier(`on_auth_user_created_${profileModel.table}`);
48
+ const configuredColumns = new Set(profileModel.columns.map((column) => column.column));
49
+ const addColumnSql = profileModel.columns
50
+ .map((column) => `alter table public.${table} add column if not exists ${quoteIdentifier(column.column)} ${column.sqlType};`)
51
+ .join('\n');
52
+ const dropStaleManagedColumnSql = MANAGED_PROFILE_COLUMNS.filter((column) => !configuredColumns.has(column))
53
+ .map((column) => `alter table public.${table} drop column if exists ${quoteIdentifier(column)};`)
54
+ .join('\n');
55
+ const insertColumns = ['id', ...profileModel.columns.map((column) => column.column)]
56
+ .map(quoteIdentifier)
57
+ .join(', ');
58
+ const insertValues = ['new.id', ...profileModel.columns.map((column) => column.fromNewUser)].join(', ');
59
+ const updateAssignments = profileModel.columns
60
+ .filter((column) => column.field === 'email')
61
+ .map((column) => `${quoteIdentifier(column.column)} = excluded.${quoteIdentifier(column.column)}`);
62
+ const conflictUpdate = [...updateAssignments, 'updated_at = now()'].join(',\n ');
63
+ const updateGrantColumns = profileModel.columns.map((column) => quoteIdentifier(column.column));
64
+ const updateGrantSql = updateGrantColumns.length > 0
65
+ ? `grant update (${updateGrantColumns.join(', ')}) on table public.${table} to authenticated;`
66
+ : '';
67
+ const triggerSql = profileModel.createStrategy === 'trigger'
68
+ ? `
69
+ create or replace function public.${functionName}()
70
+ returns trigger
71
+ language plpgsql
72
+ security definer
73
+ set search_path = pg_catalog, pg_temp
74
+ as $$
75
+ begin
76
+ insert into public.${table} (${insertColumns})
77
+ values (${insertValues})
78
+ on conflict (id) do update set
79
+ ${conflictUpdate};
80
+
81
+ return new;
82
+ end;
83
+ $$;
84
+
85
+ revoke execute on function public.${functionName}() from PUBLIC;
86
+ revoke execute on function public.${functionName}() from anon;
87
+ revoke execute on function public.${functionName}() from authenticated;
88
+
89
+ drop trigger if exists ${triggerName} on auth.users;
90
+ create trigger ${triggerName}
91
+ after insert on auth.users
92
+ for each row execute function public.${functionName}();
93
+ `
94
+ : `
95
+ drop trigger if exists ${triggerName} on auth.users;
96
+ drop function if exists public.${functionName}();
97
+ `;
98
+ return `-- Generated by @ankhorage/infra from manifest.auth.profile.
99
+ -- Desired-state reconciliation for local Supabase; not a migration-history entry.
100
+
101
+ begin;
102
+
103
+ create schema if not exists ankhorage_internal;
104
+
105
+ create table if not exists ankhorage_internal.generated_schema_state (
106
+ artifact_key text primary key,
107
+ table_name text,
108
+ content_hash text not null,
109
+ applied_at timestamptz not null
110
+ );
111
+
112
+ alter table ankhorage_internal.generated_schema_state
113
+ add column if not exists table_name text;
114
+
115
+ do $$
116
+ declare
117
+ previous_table_name text;
118
+ has_previous_state boolean;
119
+ begin
120
+ select table_name, true
121
+ into previous_table_name, has_previous_state
122
+ from ankhorage_internal.generated_schema_state
123
+ where artifact_key = '${PROFILE_ARTIFACT_KEY}';
124
+
125
+ if has_previous_state and previous_table_name is null then
126
+ raise exception 'existing auth.profile generated state is missing table identity; reset local Supabase or add an explicit cleanup migration before applying generated profile reconciliation';
127
+ end if;
128
+
129
+ if has_previous_state and previous_table_name <> '${escapeSqlLiteral(profileModel.table)}' then
130
+ raise exception 'profile.table changed from % to %; reset local Supabase or add an explicit cleanup migration before applying generated profile reconciliation', previous_table_name, '${escapeSqlLiteral(profileModel.table)}';
131
+ end if;
132
+ end;
133
+ $$;
134
+
135
+ create table if not exists public.${table} (
136
+ id uuid primary key references auth.users(id) on delete cascade,
137
+ created_at timestamptz not null default now(),
138
+ updated_at timestamptz not null default now()
139
+ );
140
+
141
+ alter table public.${table} add column if not exists id uuid;
142
+ alter table public.${table} add column if not exists created_at timestamptz not null default now();
143
+ alter table public.${table} add column if not exists updated_at timestamptz not null default now();
144
+ ${addColumnSql}
145
+ alter table public.${table} drop column if exists role;
146
+ ${dropStaleManagedColumnSql}
147
+
148
+ do $$
149
+ begin
150
+ if exists (
151
+ select 1
152
+ from pg_constraint c
153
+ where c.conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
154
+ and c.contype = 'p'
155
+ and c.conkey <> array[
156
+ (
157
+ select a.attnum
158
+ from pg_attribute a
159
+ where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
160
+ and a.attname = 'id'
161
+ and not a.attisdropped
162
+ )
163
+ ]::smallint[]
164
+ ) then
165
+ raise exception 'profile table public.${escapeSqlLiteral(profileModel.table)} has a primary key that is not exactly id';
166
+ end if;
167
+
168
+ if not exists (
169
+ select 1
170
+ from pg_constraint
171
+ where conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
172
+ and contype = 'p'
173
+ ) then
174
+ alter table public.${table}
175
+ add constraint ${quoteIdentifier(`${profileModel.table}_pkey`)} primary key (id);
176
+ end if;
177
+ end;
178
+ $$;
179
+
180
+ do $$
181
+ begin
182
+ if exists (
183
+ select 1
184
+ from pg_constraint c
185
+ where c.conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
186
+ and c.contype = 'f'
187
+ and c.confrelid = 'auth.users'::regclass
188
+ and c.conkey && array[
189
+ (
190
+ select a.attnum
191
+ from pg_attribute a
192
+ where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
193
+ and a.attname = 'id'
194
+ and not a.attisdropped
195
+ )
196
+ ]::smallint[]
197
+ and (
198
+ c.confdeltype <> 'c'
199
+ or c.conkey <> array[
200
+ (
201
+ select a.attnum
202
+ from pg_attribute a
203
+ where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
204
+ and a.attname = 'id'
205
+ and not a.attisdropped
206
+ )
207
+ ]::smallint[]
208
+ or c.confkey <> array[
209
+ (
210
+ select a.attnum
211
+ from pg_attribute a
212
+ where a.attrelid = 'auth.users'::regclass
213
+ and a.attname = 'id'
214
+ and not a.attisdropped
215
+ )
216
+ ]::smallint[]
217
+ )
218
+ ) then
219
+ raise exception 'profile table public.${escapeSqlLiteral(profileModel.table)} has an auth.users foreign key that is not exactly id -> auth.users(id) on delete cascade';
220
+ end if;
221
+
222
+ if not exists (
223
+ select 1
224
+ from pg_constraint c
225
+ where c.conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
226
+ and c.confrelid = 'auth.users'::regclass
227
+ and c.contype = 'f'
228
+ and c.confdeltype = 'c'
229
+ and c.conkey = array[
230
+ (
231
+ select a.attnum
232
+ from pg_attribute a
233
+ where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass
234
+ and a.attname = 'id'
235
+ and not a.attisdropped
236
+ )
237
+ ]::smallint[]
238
+ and c.confkey = array[
239
+ (
240
+ select a.attnum
241
+ from pg_attribute a
242
+ where a.attrelid = 'auth.users'::regclass
243
+ and a.attname = 'id'
244
+ and not a.attisdropped
245
+ )
246
+ ]::smallint[]
247
+ ) then
248
+ alter table public.${table}
249
+ add constraint ${quoteIdentifier(`${profileModel.table}_id_auth_users_fkey`)}
250
+ foreign key (id) references auth.users(id) on delete cascade;
251
+ end if;
252
+ end;
253
+ $$;
254
+
255
+ do $$
256
+ begin
257
+ if not exists (
258
+ select 1
259
+ from information_schema.columns c
260
+ where c.table_schema = 'public'
261
+ and c.table_name = '${escapeSqlLiteral(profileModel.table)}'
262
+ and c.column_name = 'id'
263
+ and c.udt_name = 'uuid'
264
+ and c.is_nullable = 'NO'
265
+ ) then
266
+ raise exception 'profile id column must be uuid not null';
267
+ end if;
268
+
269
+ if not exists (
270
+ select 1
271
+ from information_schema.columns c
272
+ where c.table_schema = 'public'
273
+ and c.table_name = '${escapeSqlLiteral(profileModel.table)}'
274
+ and c.column_name = 'created_at'
275
+ and c.data_type = 'timestamp with time zone'
276
+ and c.is_nullable = 'NO'
277
+ and c.column_default = 'now()'
278
+ ) then
279
+ raise exception 'profile created_at column must be timestamptz not null default now()';
280
+ end if;
281
+
282
+ if not exists (
283
+ select 1
284
+ from information_schema.columns c
285
+ where c.table_schema = 'public'
286
+ and c.table_name = '${escapeSqlLiteral(profileModel.table)}'
287
+ and c.column_name = 'updated_at'
288
+ and c.data_type = 'timestamp with time zone'
289
+ and c.is_nullable = 'NO'
290
+ and c.column_default = 'now()'
291
+ ) then
292
+ raise exception 'profile updated_at column must be timestamptz not null default now()';
293
+ end if;
294
+ end;
295
+ $$;
296
+
297
+ alter table public.${table} enable row level security;
298
+
299
+ revoke all on table public.${table} from anon, authenticated;
300
+ grant select on table public.${table} to authenticated;
301
+ ${updateGrantSql}
302
+
303
+ drop policy if exists ${quoteIdentifier(`${profileModel.table}_select_own`)} on public.${table};
304
+ create policy ${quoteIdentifier(`${profileModel.table}_select_own`)}
305
+ on public.${table}
306
+ for select
307
+ to authenticated
308
+ using ((select auth.uid()) = id);
309
+
310
+ drop policy if exists ${quoteIdentifier(`${profileModel.table}_update_own`)} on public.${table};
311
+ create policy ${quoteIdentifier(`${profileModel.table}_update_own`)}
312
+ on public.${table}
313
+ for update
314
+ to authenticated
315
+ using ((select auth.uid()) = id)
316
+ with check ((select auth.uid()) = id);
317
+ ${triggerSql}
318
+ insert into ankhorage_internal.generated_schema_state (
319
+ artifact_key,
320
+ table_name,
321
+ content_hash,
322
+ applied_at
323
+ )
324
+ values (
325
+ '${PROFILE_ARTIFACT_KEY}',
326
+ '${escapeSqlLiteral(profileModel.table)}',
327
+ '${profileModel.desiredStateHash}',
328
+ now()
329
+ )
330
+ on conflict (artifact_key)
331
+ do update set
332
+ table_name = excluded.table_name,
333
+ content_hash = excluded.content_hash,
334
+ applied_at = excluded.applied_at;
335
+
336
+ commit;
337
+ `;
338
+ }
339
+ function mapProfileFieldToColumn(field) {
340
+ switch (field) {
341
+ case 'email':
342
+ return { field, column: 'email', sqlType: 'text', fromNewUser: 'new.email' };
343
+ case 'displayName':
344
+ return {
345
+ field,
346
+ column: 'display_name',
347
+ sqlType: 'text',
348
+ fromNewUser: "coalesce(new.raw_user_meta_data->>'displayName', new.raw_user_meta_data->>'display_name', split_part(new.email, '@', 1))",
349
+ };
350
+ case 'firstName':
351
+ return {
352
+ field,
353
+ column: 'first_name',
354
+ sqlType: 'text',
355
+ fromNewUser: "coalesce(new.raw_user_meta_data->>'firstName', new.raw_user_meta_data->>'first_name')",
356
+ };
357
+ case 'lastName':
358
+ return {
359
+ field,
360
+ column: 'last_name',
361
+ sqlType: 'text',
362
+ fromNewUser: "coalesce(new.raw_user_meta_data->>'lastName', new.raw_user_meta_data->>'last_name')",
363
+ };
364
+ case 'avatarUrl':
365
+ return {
366
+ field,
367
+ column: 'avatar_url',
368
+ sqlType: 'text',
369
+ fromNewUser: "coalesce(new.raw_user_meta_data->>'avatarUrl', new.raw_user_meta_data->>'avatar_url')",
370
+ };
371
+ case 'username':
372
+ return {
373
+ field,
374
+ column: 'username',
375
+ sqlType: 'text',
376
+ fromNewUser: "new.raw_user_meta_data->>'username'",
377
+ };
378
+ case 'phone':
379
+ return { field, column: 'phone', sqlType: 'text', fromNewUser: 'new.phone' };
380
+ default:
381
+ return null;
382
+ }
383
+ }
384
+ function quoteIdentifier(value) {
385
+ return `"${value.replaceAll('"', '""')}"`;
386
+ }
387
+ function getProfileDesiredStateHash(args) {
388
+ const state = {
389
+ artifactKey: PROFILE_ARTIFACT_KEY,
390
+ table: args.table,
391
+ primaryKey: args.primaryKey,
392
+ createStrategy: args.createStrategy,
393
+ updateStrategy: args.updateStrategy,
394
+ managedColumns: args.columns.map((column) => ({
395
+ field: column.field,
396
+ column: column.column,
397
+ sqlType: column.sqlType,
398
+ })),
399
+ policyVersion: PROFILE_POLICY_VERSION,
400
+ reconcilerVersion: PROFILE_RECONCILER_VERSION,
401
+ };
402
+ return createHash('sha256').update(JSON.stringify(state)).digest('hex');
403
+ }
404
+ function resolveProfileColumns(fields) {
405
+ const columns = new Map();
406
+ for (const field of fields) {
407
+ const column = mapProfileFieldToColumn(field);
408
+ if (!column) {
409
+ throw new Error(`Unsupported Supabase profile field "${field}". Supported fields: ${getSupportedProfileFields().join(', ')}.`);
410
+ }
411
+ if (columns.has(column.column)) {
412
+ continue;
413
+ }
414
+ columns.set(column.column, column);
415
+ }
416
+ return [...columns.values()].sort((left, right) => MANAGED_PROFILE_COLUMNS.indexOf(left.column) -
417
+ MANAGED_PROFILE_COLUMNS.indexOf(right.column));
418
+ }
419
+ function normalizeFieldList(values) {
420
+ const source = values ?? DEFAULT_PROFILE_FIELDS;
421
+ const next = [];
422
+ for (const value of source) {
423
+ const normalized = value.trim();
424
+ if (!normalized) {
425
+ throw new Error('Invalid Supabase profile field "". Profile fields must be non-empty.');
426
+ }
427
+ if (next.includes(normalized)) {
428
+ continue;
429
+ }
430
+ next.push(normalized);
431
+ }
432
+ return next;
433
+ }
434
+ function getSupportedProfileFields() {
435
+ return ['email', 'displayName', 'firstName', 'lastName', 'avatarUrl', 'username', 'phone'];
436
+ }
437
+ function normalizeIdentifier(value) {
438
+ const trimmed = value.trim();
439
+ if (!trimmed)
440
+ return '';
441
+ if (trimmed === 'users') {
442
+ throw new Error('Invalid Supabase profile table identifier "users". public.users is reserved for identity conflict detection; use a dedicated profile table such as "profiles".');
443
+ }
444
+ if (!/^[a-z_][a-z0-9_]*$/.test(trimmed)) {
445
+ throw new Error(`Invalid Supabase profile table identifier "${trimmed}". Use snake_case letters, numbers, and underscores.`);
446
+ }
447
+ return trimmed;
448
+ }
449
+ function escapeSqlLiteral(value) {
450
+ return value.replaceAll("'", "''");
451
+ }
452
+ //# sourceMappingURL=profile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile.js","sourceRoot":"","sources":["../../../../../src/adapters/minikube/auth/supabase/profile.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;AAClE,MAAM,2BAA2B,GAAG,YAAY,CAAC;AACjD,MAAM,+BAA+B,GAAG,SAAS,CAAC;AAClD,MAAM,+BAA+B,GAAG,KAAK,CAAC;AAC9C,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,oBAAoB,GAAG,cAAc,CAAC;AAE5C,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,OAAO;IACP,cAAc;IACd,YAAY;IACZ,WAAW;IACX,YAAY;IACZ,UAAU;IACV,OA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../../../types';\n\nconst DEFAULT_PROFILE_FIELDS = ['email', 'firstName', 'lastName'];\nconst DEFAULT_PROFILE_PRIMARY_KEY = 'authUserId';\nconst DEFAULT_PROFILE_CREATE_STRATEGY = 'trigger';\nconst DEFAULT_PROFILE_UPDATE_STRATEGY = 'api';\nconst PROFILE_POLICY_VERSION = 1;\nconst PROFILE_RECONCILER_VERSION = 1;\nconst PROFILE_ARTIFACT_KEY = 'auth.profile';\n\nexport const MANAGED_PROFILE_COLUMNS = [\n 'email',\n 'display_name',\n 'first_name',\n 'last_name',\n 'avatar_url',\n 'username',\n 'phone',\n] as const;\n\ninterface ProfileColumnSpec {\n readonly field: string;\n readonly column: string;\n readonly sqlType: string;\n readonly fromNewUser: string;\n}\n\nexport interface ResolvedProfileModel {\n readonly enabled: boolean;\n readonly table: string;\n readonly primaryKey: string;\n readonly createStrategy: string;\n readonly updateStrategy: string;\n readonly columns: readonly ProfileColumnSpec[];\n readonly desiredStateHash: string;\n}\n\nexport function resolveSupabaseProfileModel(manifest: InfraManifestInput): ResolvedProfileModel {\n const table = normalizeIdentifier(manifest.auth?.profile?.table ?? '');\n const fields = normalizeFieldList(manifest.auth?.profile?.fields);\n const primaryKey = manifest.auth?.profile?.primaryKey ?? DEFAULT_PROFILE_PRIMARY_KEY;\n const createStrategy = manifest.auth?.profile?.createStrategy ?? DEFAULT_PROFILE_CREATE_STRATEGY;\n const updateStrategy = manifest.auth?.profile?.updateStrategy ?? DEFAULT_PROFILE_UPDATE_STRATEGY;\n const columns = resolveProfileColumns(fields);\n\n const hash = table\n ? getProfileDesiredStateHash({\n table,\n primaryKey,\n createStrategy,\n updateStrategy,\n columns,\n })\n : '';\n\n return {\n enabled: table.length > 0,\n table,\n primaryKey,\n createStrategy,\n updateStrategy,\n columns,\n desiredStateHash: hash,\n };\n}\n\nexport function getSupabaseProfileReconciliation(profileModel: ResolvedProfileModel): string {\n const table = quoteIdentifier(profileModel.table);\n const functionName = quoteIdentifier(`handle_new_${profileModel.table}_user`);\n const triggerName = quoteIdentifier(`on_auth_user_created_${profileModel.table}`);\n const configuredColumns = new Set(profileModel.columns.map((column) => column.column));\n const addColumnSql = profileModel.columns\n .map(\n (column) =>\n `alter table public.${table} add column if not exists ${quoteIdentifier(column.column)} ${column.sqlType};`,\n )\n .join('\\n');\n const dropStaleManagedColumnSql = MANAGED_PROFILE_COLUMNS.filter(\n (column) => !configuredColumns.has(column),\n )\n .map(\n (column) => `alter table public.${table} drop column if exists ${quoteIdentifier(column)};`,\n )\n .join('\\n');\n const insertColumns = ['id', ...profileModel.columns.map((column) => column.column)]\n .map(quoteIdentifier)\n .join(', ');\n const insertValues = ['new.id', ...profileModel.columns.map((column) => column.fromNewUser)].join(\n ', ',\n );\n const updateAssignments = profileModel.columns\n .filter((column) => column.field === 'email')\n .map(\n (column) => `${quoteIdentifier(column.column)} = excluded.${quoteIdentifier(column.column)}`,\n );\n const conflictUpdate = [...updateAssignments, 'updated_at = now()'].join(',\\n ');\n const updateGrantColumns = profileModel.columns.map((column) => quoteIdentifier(column.column));\n const updateGrantSql =\n updateGrantColumns.length > 0\n ? `grant update (${updateGrantColumns.join(', ')}) on table public.${table} to authenticated;`\n : '';\n const triggerSql =\n profileModel.createStrategy === 'trigger'\n ? `\ncreate or replace function public.${functionName}()\nreturns trigger\nlanguage plpgsql\nsecurity definer\nset search_path = pg_catalog, pg_temp\nas $$\nbegin\n insert into public.${table} (${insertColumns})\n values (${insertValues})\n on conflict (id) do update set\n ${conflictUpdate};\n\n return new;\nend;\n$$;\n\nrevoke execute on function public.${functionName}() from PUBLIC;\nrevoke execute on function public.${functionName}() from anon;\nrevoke execute on function public.${functionName}() from authenticated;\n\ndrop trigger if exists ${triggerName} on auth.users;\ncreate trigger ${triggerName}\n after insert on auth.users\n for each row execute function public.${functionName}();\n`\n : `\ndrop trigger if exists ${triggerName} on auth.users;\ndrop function if exists public.${functionName}();\n`;\n\n return `-- Generated by @ankhorage/infra from manifest.auth.profile.\n-- Desired-state reconciliation for local Supabase; not a migration-history entry.\n\nbegin;\n\ncreate schema if not exists ankhorage_internal;\n\ncreate table if not exists ankhorage_internal.generated_schema_state (\n artifact_key text primary key,\n table_name text,\n content_hash text not null,\n applied_at timestamptz not null\n);\n\nalter table ankhorage_internal.generated_schema_state\n add column if not exists table_name text;\n\ndo $$\ndeclare\n previous_table_name text;\n has_previous_state boolean;\nbegin\n select table_name, true\n into previous_table_name, has_previous_state\n from ankhorage_internal.generated_schema_state\n where artifact_key = '${PROFILE_ARTIFACT_KEY}';\n\n if has_previous_state and previous_table_name is null then\n raise exception 'existing auth.profile generated state is missing table identity; reset local Supabase or add an explicit cleanup migration before applying generated profile reconciliation';\n end if;\n\n if has_previous_state and previous_table_name <> '${escapeSqlLiteral(profileModel.table)}' then\n raise exception 'profile.table changed from % to %; reset local Supabase or add an explicit cleanup migration before applying generated profile reconciliation', previous_table_name, '${escapeSqlLiteral(profileModel.table)}';\n end if;\nend;\n$$;\n\ncreate table if not exists public.${table} (\n id uuid primary key references auth.users(id) on delete cascade,\n created_at timestamptz not null default now(),\n updated_at timestamptz not null default now()\n);\n\nalter table public.${table} add column if not exists id uuid;\nalter table public.${table} add column if not exists created_at timestamptz not null default now();\nalter table public.${table} add column if not exists updated_at timestamptz not null default now();\n${addColumnSql}\nalter table public.${table} drop column if exists role;\n${dropStaleManagedColumnSql}\n\ndo $$\nbegin\n if exists (\n select 1\n from pg_constraint c\n where c.conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and c.contype = 'p'\n and c.conkey <> array[\n (\n select a.attnum\n from pg_attribute a\n where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and a.attname = 'id'\n and not a.attisdropped\n )\n ]::smallint[]\n ) then\n raise exception 'profile table public.${escapeSqlLiteral(profileModel.table)} has a primary key that is not exactly id';\n end if;\n\n if not exists (\n select 1\n from pg_constraint\n where conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and contype = 'p'\n ) then\n alter table public.${table}\n add constraint ${quoteIdentifier(`${profileModel.table}_pkey`)} primary key (id);\n end if;\nend;\n$$;\n\ndo $$\nbegin\n if exists (\n select 1\n from pg_constraint c\n where c.conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and c.contype = 'f'\n and c.confrelid = 'auth.users'::regclass\n and c.conkey && array[\n (\n select a.attnum\n from pg_attribute a\n where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and a.attname = 'id'\n and not a.attisdropped\n )\n ]::smallint[]\n and (\n c.confdeltype <> 'c'\n or c.conkey <> array[\n (\n select a.attnum\n from pg_attribute a\n where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and a.attname = 'id'\n and not a.attisdropped\n )\n ]::smallint[]\n or c.confkey <> array[\n (\n select a.attnum\n from pg_attribute a\n where a.attrelid = 'auth.users'::regclass\n and a.attname = 'id'\n and not a.attisdropped\n )\n ]::smallint[]\n )\n ) then\n raise exception 'profile table public.${escapeSqlLiteral(profileModel.table)} has an auth.users foreign key that is not exactly id -> auth.users(id) on delete cascade';\n end if;\n\n if not exists (\n select 1\n from pg_constraint c\n where c.conrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and c.confrelid = 'auth.users'::regclass\n and c.contype = 'f'\n and c.confdeltype = 'c'\n and c.conkey = array[\n (\n select a.attnum\n from pg_attribute a\n where a.attrelid = 'public.${escapeSqlLiteral(profileModel.table)}'::regclass\n and a.attname = 'id'\n and not a.attisdropped\n )\n ]::smallint[]\n and c.confkey = array[\n (\n select a.attnum\n from pg_attribute a\n where a.attrelid = 'auth.users'::regclass\n and a.attname = 'id'\n and not a.attisdropped\n )\n ]::smallint[]\n ) then\n alter table public.${table}\n add constraint ${quoteIdentifier(`${profileModel.table}_id_auth_users_fkey`)}\n foreign key (id) references auth.users(id) on delete cascade;\n end if;\nend;\n$$;\n\ndo $$\nbegin\n if not exists (\n select 1\n from information_schema.columns c\n where c.table_schema = 'public'\n and c.table_name = '${escapeSqlLiteral(profileModel.table)}'\n and c.column_name = 'id'\n and c.udt_name = 'uuid'\n and c.is_nullable = 'NO'\n ) then\n raise exception 'profile id column must be uuid not null';\n end if;\n\n if not exists (\n select 1\n from information_schema.columns c\n where c.table_schema = 'public'\n and c.table_name = '${escapeSqlLiteral(profileModel.table)}'\n and c.column_name = 'created_at'\n and c.data_type = 'timestamp with time zone'\n and c.is_nullable = 'NO'\n and c.column_default = 'now()'\n ) then\n raise exception 'profile created_at column must be timestamptz not null default now()';\n end if;\n\n if not exists (\n select 1\n from information_schema.columns c\n where c.table_schema = 'public'\n and c.table_name = '${escapeSqlLiteral(profileModel.table)}'\n and c.column_name = 'updated_at'\n and c.data_type = 'timestamp with time zone'\n and c.is_nullable = 'NO'\n and c.column_default = 'now()'\n ) then\n raise exception 'profile updated_at column must be timestamptz not null default now()';\n end if;\nend;\n$$;\n\nalter table public.${table} enable row level security;\n\nrevoke all on table public.${table} from anon, authenticated;\ngrant select on table public.${table} to authenticated;\n${updateGrantSql}\n\ndrop policy if exists ${quoteIdentifier(`${profileModel.table}_select_own`)} on public.${table};\ncreate policy ${quoteIdentifier(`${profileModel.table}_select_own`)}\n on public.${table}\n for select\n to authenticated\n using ((select auth.uid()) = id);\n\ndrop policy if exists ${quoteIdentifier(`${profileModel.table}_update_own`)} on public.${table};\ncreate policy ${quoteIdentifier(`${profileModel.table}_update_own`)}\n on public.${table}\n for update\n to authenticated\n using ((select auth.uid()) = id)\n with check ((select auth.uid()) = id);\n${triggerSql}\ninsert into ankhorage_internal.generated_schema_state (\n artifact_key,\n table_name,\n content_hash,\n applied_at\n)\nvalues (\n '${PROFILE_ARTIFACT_KEY}',\n '${escapeSqlLiteral(profileModel.table)}',\n '${profileModel.desiredStateHash}',\n now()\n)\non conflict (artifact_key)\ndo update set\n table_name = excluded.table_name,\n content_hash = excluded.content_hash,\n applied_at = excluded.applied_at;\n\ncommit;\n`;\n}\n\nfunction mapProfileFieldToColumn(field: string): ProfileColumnSpec | null {\n switch (field) {\n case 'email':\n return { field, column: 'email', sqlType: 'text', fromNewUser: 'new.email' };\n case 'displayName':\n return {\n field,\n column: 'display_name',\n sqlType: 'text',\n fromNewUser:\n \"coalesce(new.raw_user_meta_data->>'displayName', new.raw_user_meta_data->>'display_name', split_part(new.email, '@', 1))\",\n };\n case 'firstName':\n return {\n field,\n column: 'first_name',\n sqlType: 'text',\n fromNewUser:\n \"coalesce(new.raw_user_meta_data->>'firstName', new.raw_user_meta_data->>'first_name')\",\n };\n case 'lastName':\n return {\n field,\n column: 'last_name',\n sqlType: 'text',\n fromNewUser:\n \"coalesce(new.raw_user_meta_data->>'lastName', new.raw_user_meta_data->>'last_name')\",\n };\n case 'avatarUrl':\n return {\n field,\n column: 'avatar_url',\n sqlType: 'text',\n fromNewUser:\n \"coalesce(new.raw_user_meta_data->>'avatarUrl', new.raw_user_meta_data->>'avatar_url')\",\n };\n case 'username':\n return {\n field,\n column: 'username',\n sqlType: 'text',\n fromNewUser: \"new.raw_user_meta_data->>'username'\",\n };\n case 'phone':\n return { field, column: 'phone', sqlType: 'text', fromNewUser: 'new.phone' };\n default:\n return null;\n }\n}\n\nfunction quoteIdentifier(value: string): string {\n return `\"${value.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction getProfileDesiredStateHash(args: {\n readonly table: string;\n readonly primaryKey: string;\n readonly createStrategy: string;\n readonly updateStrategy: string;\n readonly columns: readonly ProfileColumnSpec[];\n}): string {\n const state = {\n artifactKey: PROFILE_ARTIFACT_KEY,\n table: args.table,\n primaryKey: args.primaryKey,\n createStrategy: args.createStrategy,\n updateStrategy: args.updateStrategy,\n managedColumns: args.columns.map((column) => ({\n field: column.field,\n column: column.column,\n sqlType: column.sqlType,\n })),\n policyVersion: PROFILE_POLICY_VERSION,\n reconcilerVersion: PROFILE_RECONCILER_VERSION,\n };\n\n return createHash('sha256').update(JSON.stringify(state)).digest('hex');\n}\n\nfunction resolveProfileColumns(fields: readonly string[]): ProfileColumnSpec[] {\n const columns = new Map<string, ProfileColumnSpec>();\n\n for (const field of fields) {\n const column = mapProfileFieldToColumn(field);\n if (!column) {\n throw new Error(\n `Unsupported Supabase profile field \"${field}\". Supported fields: ${getSupportedProfileFields().join(', ')}.`,\n );\n }\n\n if (columns.has(column.column)) {\n continue;\n }\n columns.set(column.column, column);\n }\n\n return [...columns.values()].sort(\n (left, right) =>\n MANAGED_PROFILE_COLUMNS.indexOf(left.column as (typeof MANAGED_PROFILE_COLUMNS)[number]) -\n MANAGED_PROFILE_COLUMNS.indexOf(right.column as (typeof MANAGED_PROFILE_COLUMNS)[number]),\n );\n}\n\nfunction normalizeFieldList(values: readonly string[] | undefined): string[] {\n const source = values ?? DEFAULT_PROFILE_FIELDS;\n const next: string[] = [];\n\n for (const value of source) {\n const normalized = value.trim();\n if (!normalized) {\n throw new Error('Invalid Supabase profile field \"\". Profile fields must be non-empty.');\n }\n\n if (next.includes(normalized)) {\n continue;\n }\n next.push(normalized);\n }\n\n return next;\n}\n\nfunction getSupportedProfileFields(): string[] {\n return ['email', 'displayName', 'firstName', 'lastName', 'avatarUrl', 'username', 'phone'];\n}\n\nfunction normalizeIdentifier(value: string): string {\n const trimmed = value.trim();\n if (!trimmed) return '';\n\n if (trimmed === 'users') {\n throw new Error(\n 'Invalid Supabase profile table identifier \"users\". public.users is reserved for identity conflict detection; use a dedicated profile table such as \"profiles\".',\n );\n }\n\n if (!/^[a-z_][a-z0-9_]*$/.test(trimmed)) {\n throw new Error(\n `Invalid Supabase profile table identifier \"${trimmed}\". Use snake_case letters, numbers, and underscores.`,\n );\n }\n\n return trimmed;\n}\n\nfunction escapeSqlLiteral(value: string): string {\n return value.replaceAll(\"'\", \"''\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/adapters/minikube/base/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAuBzD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IAClD,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;CAC3B,GAAG,2BAA2B,EAAE,CAwGhC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/adapters/minikube/base/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AA4BzD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE;IAClD,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;CAC3B,GAAG,2BAA2B,EAAE,CAyHhC"}