@stacksjs/orm 0.75.538 → 0.75.541

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 (49) hide show
  1. package/dist/gdpr/engine.d.ts +14 -0
  2. package/dist/gdpr/engine.js +1 -1
  3. package/dist/gdpr/index.d.ts +1 -0
  4. package/dist/gdpr/index.js +1 -1
  5. package/dist/gdpr/plan.js +1 -1
  6. package/dist/models/Activity.ts +4 -0
  7. package/dist/models/AnalyticsEvent.ts +4 -0
  8. package/dist/models/Automation.ts +4 -0
  9. package/dist/models/AutomationRun.ts +4 -0
  10. package/dist/models/Board.ts +4 -1
  11. package/dist/models/BoardColumn.ts +4 -1
  12. package/dist/models/Campaign.ts +4 -0
  13. package/dist/models/CampaignSend.ts +4 -0
  14. package/dist/models/CampaignVariant.ts +4 -0
  15. package/dist/models/Card.ts +4 -1
  16. package/dist/models/CardAttachment.ts +4 -0
  17. package/dist/models/CommunicationSuppression.ts +4 -0
  18. package/dist/models/ConsentEvent.ts +4 -0
  19. package/dist/models/Deployment.ts +1 -0
  20. package/dist/models/EmailList.ts +4 -0
  21. package/dist/models/EmailListSubscriber.ts +4 -0
  22. package/dist/models/Error.ts +4 -0
  23. package/dist/models/FailedJob.ts +4 -0
  24. package/dist/models/FeedbackToken.ts +4 -0
  25. package/dist/models/GdprRequest.ts +4 -0
  26. package/dist/models/Job.ts +4 -0
  27. package/dist/models/Log.ts +4 -0
  28. package/dist/models/MagicLinkToken.ts +4 -0
  29. package/dist/models/MailPreference.ts +4 -0
  30. package/dist/models/Notification.ts +4 -0
  31. package/dist/models/NotificationDelivery.ts +4 -0
  32. package/dist/models/PersonalAccessToken.ts +4 -0
  33. package/dist/models/QueryLog.ts +4 -0
  34. package/dist/models/Referral.ts +4 -0
  35. package/dist/models/Release.ts +1 -0
  36. package/dist/models/Request.ts +4 -0
  37. package/dist/models/SenderDomain.ts +4 -0
  38. package/dist/models/Site.ts +1 -0
  39. package/dist/models/SiteDomain.ts +4 -0
  40. package/dist/models/SocialPost.ts +4 -0
  41. package/dist/models/StorageItemTask.ts +4 -1
  42. package/dist/models/Subscriber.ts +4 -0
  43. package/dist/models/Subscription.ts +4 -0
  44. package/dist/models/Team.ts +1 -0
  45. package/dist/models/TeamInvitation.ts +1 -0
  46. package/dist/models/TeamMember.ts +1 -0
  47. package/dist/models/UsageEvent.ts +4 -0
  48. package/dist/models/User.ts +15 -3
  49. package/package.json +23 -23
@@ -3,6 +3,20 @@ import type { GdprErasureResult, GdprExport, GdprModels, GdprPruneResult, GdprSu
3
3
  export declare function gdprTableExists(table: string, handle?: Handle): Promise<boolean>;
4
4
  /** Find the user a request is about, by id, email or uuid. */
5
5
  export declare function resolveGdprSubject(reference: number | string, options?: GdprRunOptions, handle?: Handle): Promise<GdprSubjectIdentity | null>;
6
+ /**
7
+ * Which of these rows are in their anonymized state: every personal column
8
+ * the row carries already holds what erasure writes there.
9
+ *
10
+ * For telling an erased account apart from a live one where both are listed.
11
+ * It asks the plan, not the audit log, on purpose: an erased account somebody
12
+ * has since given a real name and address is an account again, and a row a
13
+ * model override anonymizes to its own placeholder is still recognised.
14
+ *
15
+ * Judged on the columns present, so a projection that leaves out a hidden
16
+ * column (a password) can still be answered. A row carrying none of the
17
+ * model's personal columns says nothing either way, and is not anonymized.
18
+ */
19
+ export declare function anonymizedRows(modelName: string, rows: Row[], options?: GdprRunOptions): Promise<boolean[]>;
6
20
  /**
7
21
  * Everything the subject's declared personal data amounts to, as one document.
8
22
  *
@@ -1 +1 @@
1
- import{randomUUID}from"node:crypto";import{db,getDatabaseDialect,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{transaction}from"../transaction";import{assertGdprPlan,GDPR_SUBJECT_MODEL,resolveGdprPlan}from"./plan";export const GDPR_AUDIT_TABLE="gdpr_requests";const CHUNK=500;export class GdprSubjectNotFoundError extends Error{constructor(reference){super(`No user matches '${String(reference)}'.`);this.name="GdprSubjectNotFoundError"}}async function loadPlan(models){if(models)return assertGdprPlan(resolveGdprPlan(models));const{loadGdprModels}=await import("./models");return assertGdprPlan(resolveGdprPlan(await loadGdprModels()))}async function liveTables(handle=db){const dialect=String(getDatabaseDialect());const query=dialect==="sqlite"?`SELECT name FROM sqlite_master WHERE type = 'table'`:dialect==="mysql"?`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()`:dialect==="postgres"?`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = current_schema()`:null;if(!query)return null;const rows=await handle.unsafe(query).execute();return new Set(rows.map((row)=>String(row.name??row.NAME??"").toLowerCase()).filter(Boolean))}const MISSING_TABLE=/no such table|does not exist|doesn't exist|unknown table|undefined table|ER_NO_SUCH_TABLE/i;export async function gdprTableExists(table,handle=db){const tables=await liveTables(handle);if(tables)return tables.has(table.toLowerCase());try{await handle.selectFrom(table).selectAll().limit(1).execute();return true}catch(error){if(MISSING_TABLE.test(error instanceof Error?error.message:String(error)))return false;throw error}}function subjectPlanFor(plan){const user=plan.models.find((model)=>model.model===GDPR_SUBJECT_MODEL);return{table:user?.table??"users",primaryKey:user?.primaryKey??"id"}}function normalizeReference(reference){if(typeof reference==="number")return{kind:"id",value:reference};const trimmed=String(reference).trim();if(/^\d+$/.test(trimmed))return{kind:"id",value:Number(trimmed)};if(trimmed.includes("@"))return{kind:"email",value:trimmed};return{kind:"uuid",value:trimmed}}export async function resolveGdprSubject(reference,options={},handle=db){const plan=await loadPlan(options.models);return findSubject(plan,reference,handle)}async function findSubject(plan,reference,handle){const{table,primaryKey}=subjectPlanFor(plan);const ref=normalizeReference(reference);let row;if(ref.kind==="id"){row=(await handle.selectFrom(table).selectAll().where(primaryKey,"=",ref.value).limit(1).execute())[0]}else if(ref.kind==="email"){for(const candidate of new Set([ref.value,ref.value.toLowerCase()])){row=(await handle.selectFrom(table).selectAll().where("email","=",candidate).limit(1).execute())[0];if(row)break}}else{row=(await handle.selectFrom(table).selectAll().where("uuid","=",ref.value).limit(1).execute())[0]}if(!row)return null;return{id:row[primaryKey],email:typeof row.email==="string"?row.email:null}}function chunks(values,size=CHUNK){const out=[];for(let i=0;i<values.length;i+=size)out.push(values.slice(i,i+size));return out}function dedupe(rows,primaryKey){const seen=new Map;for(const row of rows)seen.set(String(row[primaryKey]),row);return[...seen.values()].sort((a,b)=>String(a[primaryKey]).localeCompare(String(b[primaryKey]),undefined,{numeric:true}))}async function matchRows(handle,plans,model,subject,memo){const cached=memo.get(model.model);if(cached)return cached;const link=model.subject;let rows=[];if(link?.kind==="column"){for(const column of link.columns){let query=handle.selectFrom(model.table).selectAll().where(column,"=",subject.id);for(const[key,value]of Object.entries(link.where))query=query.where(key,"=",value);rows.push(...await query.execute())}}else if(link?.kind==="email"){if(subject.email){for(const candidate of new Set([subject.email,subject.email.toLowerCase()]))rows.push(...await handle.selectFrom(model.table).selectAll().where(link.column,"=",candidate).execute())}}else if(link?.kind==="via"){const parent=plans.get(link.model);const parentRows=await matchRows(handle,plans,parent,subject,memo);const parentIds=parentRows.map((row)=>row[parent.primaryKey]).filter((id)=>id!==null&&id!==undefined);for(const ids of chunks(parentIds))rows.push(...await handle.selectFrom(model.table).selectAll().where(link.foreignKey,"in",ids).execute())}rows=dedupe(rows,model.primaryKey);memo.set(model.model,rows);return rows}function exportable(value){if(typeof value==="bigint")return Number.isSafeInteger(Number(value))?Number(value):value.toString();if(value instanceof Date)return value.toISOString();return value}function project(model,row){const out={};for(const column of model.exportColumns){if(column in row)out[column]=exportable(row[column])}for(const field of model.personal){if(field.export&&field.column in row)out[field.column]=exportable(row[field.column])}return out}function targetValues(model,row){const values={};for(const field of model.personal)values[field.column]=field.perRow?`erased-${String(row[model.primaryKey])}`:field.anonymizeTo;return values}function same(stored,target){if(stored===target)return true;if(stored===null||stored===undefined||target===null||target===undefined)return(stored===null||stored===undefined)&&(target===null||target===undefined);if(typeof target==="boolean")return Number(stored)===Number(target);return String(stored)===String(target)}function needsAnonymizing(model,row){const target=targetValues(model,row);return Object.entries(target).some(([column,value])=>!same(row[column],value))}async function anonymizeRows(handle,model,rows){if(!rows.length)return;if(model.personal.some((field)=>field.perRow)){for(const row of rows)await handle.updateTable(model.table).set(targetValues(model,row)).where(model.primaryKey,"=",row[model.primaryKey]).execute();return}const values=targetValues(model,rows[0]);for(const ids of chunks(rows.map((row)=>row[model.primaryKey])))await handle.updateTable(model.table).set(values).where(model.primaryKey,"in",ids).execute()}async function deleteRows(handle,model,rows){for(const ids of chunks(rows.map((row)=>row[model.primaryKey])))await handle.deleteFrom(model.table).where(model.primaryKey,"in",ids).execute()}async function recordAudit(handle,type,subjectId,actor,summary){const now=sqlDateTime(new Date);await handle.insertInto(GDPR_AUDIT_TABLE).values({uuid:randomUUID(),type,subject_id:subjectId!==null&&Number.isSafeInteger(Number(subjectId))?Number(subjectId):null,actor,status:"completed",summary:JSON.stringify(subjectId!==null&&!Number.isSafeInteger(Number(subjectId))?{subject:String(subjectId),...summary}:summary),occurred_at:now,created_at:now}).execute()}async function requireAuditTable(){if(!await gdprTableExists(GDPR_AUDIT_TABLE))throw new Error(`The '${GDPR_AUDIT_TABLE}' table does not exist, so this request cannot be recorded. Run \`buddy migrate\` first.`)}async function existingTables(models){const present=[];const skipped=[];const tables=await liveTables();const known=new Map;for(const model of models){if(!known.has(model.table))known.set(model.table,tables?tables.has(model.table.toLowerCase()):await gdprTableExists(model.table));if(known.get(model.table))present.push(model);else skipped.push(model.table)}return{present,skipped:[...new Set(skipped)].sort()}}export async function exportSubjectData(reference,options={}){const plan=await loadPlan(options.models);const subject=await findSubject(plan,reference,db);if(!subject)throw new GdprSubjectNotFoundError(reference);await requireAuditTable();const linked=plan.models.filter((model)=>model.subject);const{present}=await existingTables(linked);const plans=new Map(present.map((model)=>[model.model,model]));for(const model of present){if(model.subject?.kind==="via"&&!plans.has(model.subject.model))plans.delete(model.model)}const memo=new Map;const data={};const processing={};for(const model of[...plans.values()].sort((a,b)=>a.model.localeCompare(b.model))){const rows=await matchRows(db,plans,model,subject,memo);if(!rows.length)continue;data[model.model]=rows.map((row)=>project(model,row));processing[model.model]={purpose:model.purpose,basis:model.basis,retentionDays:model.retention?.days??null}}await recordAudit(db,"access",subject.id,options.actor??"system",{models:Object.fromEntries(Object.entries(data).map(([model,rows])=>[model,rows.length]))});return{subject:{id:subject.id},generatedAt:new Date().toISOString(),data,processing}}function erasureOrder(models){return[...models].sort((a,b)=>{const aSelf=a.model===GDPR_SUBJECT_MODEL?1:0;const bSelf=b.model===GDPR_SUBJECT_MODEL?1:0;if(aSelf!==bSelf)return aSelf-bSelf;if(a.depth!==b.depth)return b.depth-a.depth;return a.model.localeCompare(b.model)})}export async function eraseSubject(reference,options={}){const dryRun=options.dryRun===true;const plan=await loadPlan(options.models);const subject=await findSubject(plan,reference,db);if(!subject)throw new GdprSubjectNotFoundError(reference);if(!dryRun)await requireAuditTable();const linked=plan.models.filter((model)=>model.subject);const{present,skipped}=await existingTables(linked);const plans=new Map(present.map((model)=>[model.model,model]));for(const model of present){if(model.subject?.kind==="via"&&!plans.has(model.subject.model))plans.delete(model.model)}const work=async(handle)=>{const memo=new Map;for(const model of plans.values())await matchRows(handle,plans,model,subject,memo);const changes=[];for(const model of erasureOrder([...plans.values()])){const rows=memo.get(model.model)??[];if(model.erasure==="delete"){if(!dryRun)await deleteRows(handle,model,rows);changes.push({model:model.model,table:model.table,action:"delete",matched:rows.length,changed:rows.length,fields:[]})}else if(model.erasure==="anonymize"){const pending=rows.filter((row)=>needsAnonymizing(model,row));if(!dryRun)await anonymizeRows(handle,model,pending);changes.push({model:model.model,table:model.table,action:"anonymize",matched:rows.length,changed:pending.length,fields:model.personal.map((field)=>field.column)})}else{changes.push({model:model.model,table:model.table,action:"keep",matched:rows.length,changed:0,fields:[]})}}if(!dryRun){await recordAudit(handle,"erasure",subject.id,options.actor??"system",{changes:changes.map(({model,action,matched,changed})=>({model,action,matched,changed})),skipped})}return changes};const changes=dryRun?await work(db):await transaction(work);let credentialsRevoked=false;if(!dryRun&&options.revokeCredentials!==false)credentialsRevoked=await revokeCredentials(subject.id);return{subject:{id:subject.id},dryRun,changes:changes.sort((a,b)=>a.model.localeCompare(b.model)),skipped,credentialsRevoked}}async function revokeCredentials(subjectId){let auth;try{auth=await import("@stacksjs/auth")}catch{return false}const id=Number(subjectId);if(!Number.isSafeInteger(id))return false;if(auth.revokeAllTokens&&await gdprTableExists("oauth_access_tokens"))await auth.revokeAllTokens(id);if(auth.sessionDestroyAll)await auth.sessionDestroyAll(id);return true}const DAY_MS=86400000;export async function pruneRetainedData(options={}){const dryRun=options.dryRun===true;const now=options.now??new Date;if(!Number.isFinite(now.getTime()))throw new RangeError("Retention requires a valid date");if(options.batchSize!==undefined&&(!Number.isSafeInteger(options.batchSize)||options.batchSize<1||options.batchSize>1e4))throw new RangeError("Retention batchSize must be an integer from 1 to 10000");const next={};const plan=await loadPlan(options.models);const policies=plan.models.filter((model)=>model.retention);if(!policies.length)return{dryRun,cutoffs:{},changes:[],skipped:[],...options.batchSize===undefined?{}:{next}};if(!dryRun)await requireAuditTable();const{present,skipped}=await existingTables(policies);const changes=[];const cutoffs={};for(const model of present){const retention=model.retention;const cutoff=new Date(now.getTime()-retention.days*DAY_MS);const bound=sqlDateTime(new Date(cutoff.getTime()+DAY_MS));cutoffs[model.model]=cutoff.toISOString();const expired=[];let last=options.after?.[model.model];for(;;){const handle=db;let query=handle.selectFrom(model.table).selectAll().where(retention.column,"<",bound);if(last!==undefined)query=query.where(model.primaryKey,">",last);const size=options.batchSize??CHUNK;const page=await query.orderBy(model.primaryKey,"asc").limit(size).execute();if(!page.length)break;for(const row of page){const at=parseSqlDateTime(row[retention.column]);if(at&&at.getTime()<cutoff.getTime())expired.push(row)}last=page[page.length-1][model.primaryKey];if(options.batchSize!==undefined){if(page.length===size){if(typeof last==="bigint")last=last.toString();if(typeof last!=="string"&&typeof last!=="number")throw new TypeError("Retention requires a string or numeric primary key");next[model.model]=last}break}if(page.length<CHUNK)break}const pending=retention.action==="delete"?expired:expired.filter((row)=>needsAnonymizing(model,row));if(!dryRun&&pending.length){await transaction(async(handle)=>{if(retention.action==="delete")await deleteRows(handle,model,pending);else await anonymizeRows(handle,model,pending);if(options.batchSize!==undefined)await recordAudit(handle,"retention",null,options.actor??"scheduler",{changes:[{model:model.model,action:retention.action,matched:expired.length,changed:pending.length}],cutoffs:{[model.model]:cutoff.toISOString()}})})}changes.push({model:model.model,table:model.table,action:retention.action,matched:expired.length,changed:pending.length,fields:retention.action==="anonymize"?model.personal.map((field)=>field.column):[]})}if(!dryRun&&options.batchSize===undefined&&changes.some((change)=>change.changed>0)){await recordAudit(db,"retention",null,options.actor??"scheduler",{changes:changes.map(({model,action,matched,changed})=>({model,action,matched,changed})),cutoffs})}return{dryRun,cutoffs,changes:changes.sort((a,b)=>a.model.localeCompare(b.model)),skipped,...options.batchSize===undefined?{}:{next}}}
1
+ import{randomUUID}from"node:crypto";import{db,getDatabaseDialect,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{transaction}from"../transaction";import{assertGdprPlan,GDPR_SUBJECT_MODEL,resolveGdprPlan}from"./plan";export const GDPR_AUDIT_TABLE="gdpr_requests";const CHUNK=500;export class GdprSubjectNotFoundError extends Error{constructor(reference){super(`No user matches '${String(reference)}'.`);this.name="GdprSubjectNotFoundError"}}async function loadPlan(models){if(models)return assertGdprPlan(resolveGdprPlan(models));const{loadGdprModels}=await import("./models");return assertGdprPlan(resolveGdprPlan(await loadGdprModels()))}async function liveTables(handle=db){const dialect=String(getDatabaseDialect());const query=dialect==="sqlite"?`SELECT name FROM sqlite_master WHERE type = 'table'`:dialect==="mysql"?`SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE()`:dialect==="postgres"?`SELECT table_name AS name FROM information_schema.tables WHERE table_schema = current_schema()`:null;if(!query)return null;const rows=await handle.unsafe(query).execute();return new Set(rows.map((row)=>String(row.name??row.NAME??"").toLowerCase()).filter(Boolean))}const MISSING_TABLE=/no such table|does not exist|doesn't exist|unknown table|undefined table|ER_NO_SUCH_TABLE/i;export async function gdprTableExists(table,handle=db){const tables=await liveTables(handle);if(tables)return tables.has(table.toLowerCase());try{await handle.selectFrom(table).selectAll().limit(1).execute();return true}catch(error){if(MISSING_TABLE.test(error instanceof Error?error.message:String(error)))return false;throw error}}function subjectPlanFor(plan){const user=plan.models.find((model)=>model.model===GDPR_SUBJECT_MODEL);return{table:user?.table??"users",primaryKey:user?.primaryKey??"id"}}function normalizeReference(reference){if(typeof reference==="number")return{kind:"id",value:reference};const trimmed=String(reference).trim();if(/^\d+$/.test(trimmed))return{kind:"id",value:Number(trimmed)};if(trimmed.includes("@"))return{kind:"email",value:trimmed};return{kind:"uuid",value:trimmed}}export async function resolveGdprSubject(reference,options={},handle=db){const plan=await loadPlan(options.models);return findSubject(plan,reference,handle)}async function findSubject(plan,reference,handle){const{table,primaryKey}=subjectPlanFor(plan);const ref=normalizeReference(reference);let row;if(ref.kind==="id"){row=(await handle.selectFrom(table).selectAll().where(primaryKey,"=",ref.value).limit(1).execute())[0]}else if(ref.kind==="email"){for(const candidate of new Set([ref.value,ref.value.toLowerCase()])){row=(await handle.selectFrom(table).selectAll().where("email","=",candidate).limit(1).execute())[0];if(row)break}}else{row=(await handle.selectFrom(table).selectAll().where("uuid","=",ref.value).limit(1).execute())[0]}if(!row)return null;return{id:row[primaryKey],email:typeof row.email==="string"?row.email:null}}function chunks(values,size=CHUNK){const out=[];for(let i=0;i<values.length;i+=size)out.push(values.slice(i,i+size));return out}function dedupe(rows,primaryKey){const seen=new Map;for(const row of rows)seen.set(String(row[primaryKey]),row);return[...seen.values()].sort((a,b)=>String(a[primaryKey]).localeCompare(String(b[primaryKey]),undefined,{numeric:true}))}async function matchRows(handle,plans,model,subject,memo){const cached=memo.get(model.model);if(cached)return cached;const link=model.subject;let rows=[];if(link?.kind==="column"){for(const column of link.columns){let query=handle.selectFrom(model.table).selectAll().where(column,"=",subject.id);for(const[key,value]of Object.entries(link.where))query=query.where(key,"=",value);rows.push(...await query.execute())}}else if(link?.kind==="email"){if(subject.email){for(const candidate of new Set([subject.email,subject.email.toLowerCase()]))rows.push(...await handle.selectFrom(model.table).selectAll().where(link.column,"=",candidate).execute())}}else if(link?.kind==="via"){const parent=plans.get(link.model);const parentRows=await matchRows(handle,plans,parent,subject,memo);const parentIds=parentRows.map((row)=>row[parent.primaryKey]).filter((id)=>id!==null&&id!==undefined);for(const ids of chunks(parentIds))rows.push(...await handle.selectFrom(model.table).selectAll().where(link.foreignKey,"in",ids).execute())}rows=dedupe(rows,model.primaryKey);memo.set(model.model,rows);return rows}function exportable(value){if(typeof value==="bigint")return Number.isSafeInteger(Number(value))?Number(value):value.toString();if(value instanceof Date)return value.toISOString();return value}function project(model,row){const out={};for(const column of model.exportColumns){if(column in row)out[column]=exportable(row[column])}for(const field of model.personal){if(field.export&&field.column in row)out[field.column]=exportable(row[field.column])}return out}function targetValues(model,row){const values={};for(const field of model.personal)values[field.column]=field.perRow?`erased-${String(row[model.primaryKey])}`:field.anonymizeTo;return values}function same(stored,target){if(stored===target)return true;if(stored===null||stored===undefined||target===null||target===undefined)return(stored===null||stored===undefined)&&(target===null||target===undefined);if(typeof target==="boolean")return Number(stored)===Number(target);return String(stored)===String(target)}function needsAnonymizing(model,row){const target=targetValues(model,row);return Object.entries(target).some(([column,value])=>!same(row[column],value))}export async function anonymizedRows(modelName,rows,options={}){const plan=await loadPlan(options.models);const model=plan.models.find((candidate)=>candidate.model===modelName);if(!model||model.personal.length===0)return rows.map(()=>false);return rows.map((row)=>{const carried=Object.entries(targetValues(model,row)).filter(([column])=>(column in row));return carried.length>0&&carried.every(([column,value])=>same(row[column],value))})}async function anonymizeRows(handle,model,rows){if(!rows.length)return;if(model.personal.some((field)=>field.perRow)){for(const row of rows)await handle.updateTable(model.table).set(targetValues(model,row)).where(model.primaryKey,"=",row[model.primaryKey]).execute();return}const values=targetValues(model,rows[0]);for(const ids of chunks(rows.map((row)=>row[model.primaryKey])))await handle.updateTable(model.table).set(values).where(model.primaryKey,"in",ids).execute()}async function deleteRows(handle,model,rows){for(const ids of chunks(rows.map((row)=>row[model.primaryKey])))await handle.deleteFrom(model.table).where(model.primaryKey,"in",ids).execute()}async function recordAudit(handle,type,subjectId,actor,summary){const now=sqlDateTime(new Date);await handle.insertInto(GDPR_AUDIT_TABLE).values({uuid:randomUUID(),type,subject_id:subjectId!==null&&Number.isSafeInteger(Number(subjectId))?Number(subjectId):null,actor,status:"completed",summary:JSON.stringify(subjectId!==null&&!Number.isSafeInteger(Number(subjectId))?{subject:String(subjectId),...summary}:summary),occurred_at:now,created_at:now}).execute()}async function requireAuditTable(){if(!await gdprTableExists(GDPR_AUDIT_TABLE))throw new Error(`The '${GDPR_AUDIT_TABLE}' table does not exist, so this request cannot be recorded. Run \`buddy migrate\` first.`)}async function existingTables(models){const present=[];const skipped=[];const tables=await liveTables();const known=new Map;for(const model of models){if(!known.has(model.table))known.set(model.table,tables?tables.has(model.table.toLowerCase()):await gdprTableExists(model.table));if(known.get(model.table))present.push(model);else skipped.push(model.table)}return{present,skipped:[...new Set(skipped)].sort()}}export async function exportSubjectData(reference,options={}){const plan=await loadPlan(options.models);const subject=await findSubject(plan,reference,db);if(!subject)throw new GdprSubjectNotFoundError(reference);await requireAuditTable();const linked=plan.models.filter((model)=>model.subject);const{present}=await existingTables(linked);const plans=new Map(present.map((model)=>[model.model,model]));for(const model of present){if(model.subject?.kind==="via"&&!plans.has(model.subject.model))plans.delete(model.model)}const memo=new Map;const data={};const processing={};for(const model of[...plans.values()].sort((a,b)=>a.model.localeCompare(b.model))){const rows=await matchRows(db,plans,model,subject,memo);if(!rows.length)continue;data[model.model]=rows.map((row)=>project(model,row));processing[model.model]={purpose:model.purpose,basis:model.basis,retentionDays:model.retention?.days??null}}await recordAudit(db,"access",subject.id,options.actor??"system",{models:Object.fromEntries(Object.entries(data).map(([model,rows])=>[model,rows.length]))});return{subject:{id:subject.id},generatedAt:new Date().toISOString(),data,processing}}function erasureOrder(models){return[...models].sort((a,b)=>{const aSelf=a.model===GDPR_SUBJECT_MODEL?1:0;const bSelf=b.model===GDPR_SUBJECT_MODEL?1:0;if(aSelf!==bSelf)return aSelf-bSelf;if(a.depth!==b.depth)return b.depth-a.depth;return a.model.localeCompare(b.model)})}export async function eraseSubject(reference,options={}){const dryRun=options.dryRun===true;const plan=await loadPlan(options.models);const subject=await findSubject(plan,reference,db);if(!subject)throw new GdprSubjectNotFoundError(reference);if(!dryRun)await requireAuditTable();const linked=plan.models.filter((model)=>model.subject);const{present,skipped}=await existingTables(linked);const plans=new Map(present.map((model)=>[model.model,model]));for(const model of present){if(model.subject?.kind==="via"&&!plans.has(model.subject.model))plans.delete(model.model)}const work=async(handle)=>{const memo=new Map;for(const model of plans.values())await matchRows(handle,plans,model,subject,memo);const changes=[];for(const model of erasureOrder([...plans.values()])){const rows=memo.get(model.model)??[];if(model.erasure==="delete"){if(!dryRun)await deleteRows(handle,model,rows);changes.push({model:model.model,table:model.table,action:"delete",matched:rows.length,changed:rows.length,fields:[]})}else if(model.erasure==="anonymize"){const pending=rows.filter((row)=>needsAnonymizing(model,row));if(!dryRun)await anonymizeRows(handle,model,pending);changes.push({model:model.model,table:model.table,action:"anonymize",matched:rows.length,changed:pending.length,fields:model.personal.map((field)=>field.column)})}else{changes.push({model:model.model,table:model.table,action:"keep",matched:rows.length,changed:0,fields:[]})}}if(!dryRun){await recordAudit(handle,"erasure",subject.id,options.actor??"system",{changes:changes.map(({model,action,matched,changed})=>({model,action,matched,changed})),skipped})}return changes};const changes=dryRun?await work(db):await transaction(work);let credentialsRevoked=false;if(!dryRun&&options.revokeCredentials!==false)credentialsRevoked=await revokeCredentials(subject.id);return{subject:{id:subject.id},dryRun,changes:changes.sort((a,b)=>a.model.localeCompare(b.model)),skipped,credentialsRevoked}}async function revokeCredentials(subjectId){let auth;try{auth=await import("@stacksjs/auth")}catch{return false}const id=Number(subjectId);if(!Number.isSafeInteger(id))return false;if(auth.revokeAllTokens&&await gdprTableExists("oauth_access_tokens"))await auth.revokeAllTokens(id);if(auth.sessionDestroyAll)await auth.sessionDestroyAll(id);return true}const DAY_MS=86400000;export async function pruneRetainedData(options={}){const dryRun=options.dryRun===true;const now=options.now??new Date;if(!Number.isFinite(now.getTime()))throw new RangeError("Retention requires a valid date");if(options.batchSize!==undefined&&(!Number.isSafeInteger(options.batchSize)||options.batchSize<1||options.batchSize>1e4))throw new RangeError("Retention batchSize must be an integer from 1 to 10000");const next={};const plan=await loadPlan(options.models);const policies=plan.models.filter((model)=>model.retention);if(!policies.length)return{dryRun,cutoffs:{},changes:[],skipped:[],...options.batchSize===undefined?{}:{next}};if(!dryRun)await requireAuditTable();const{present,skipped}=await existingTables(policies);const changes=[];const cutoffs={};for(const model of present){const retention=model.retention;const cutoff=new Date(now.getTime()-retention.days*DAY_MS);const bound=sqlDateTime(new Date(cutoff.getTime()+DAY_MS));cutoffs[model.model]=cutoff.toISOString();const expired=[];let last=options.after?.[model.model];for(;;){const handle=db;let query=handle.selectFrom(model.table).selectAll().where(retention.column,"<",bound);if(last!==undefined)query=query.where(model.primaryKey,">",last);const size=options.batchSize??CHUNK;const page=await query.orderBy(model.primaryKey,"asc").limit(size).execute();if(!page.length)break;for(const row of page){const at=parseSqlDateTime(row[retention.column]);if(at&&at.getTime()<cutoff.getTime())expired.push(row)}last=page[page.length-1][model.primaryKey];if(options.batchSize!==undefined){if(page.length===size){if(typeof last==="bigint")last=last.toString();if(typeof last!=="string"&&typeof last!=="number")throw new TypeError("Retention requires a string or numeric primary key");next[model.model]=last}break}if(page.length<CHUNK)break}const pending=retention.action==="delete"?expired:expired.filter((row)=>needsAnonymizing(model,row));if(!dryRun&&pending.length){await transaction(async(handle)=>{if(retention.action==="delete")await deleteRows(handle,model,pending);else await anonymizeRows(handle,model,pending);if(options.batchSize!==undefined)await recordAudit(handle,"retention",null,options.actor??"scheduler",{changes:[{model:model.model,action:retention.action,matched:expired.length,changed:pending.length}],cutoffs:{[model.model]:cutoff.toISOString()}})})}changes.push({model:model.model,table:model.table,action:retention.action,matched:expired.length,changed:pending.length,fields:retention.action==="anonymize"?model.personal.map((field)=>field.column):[]})}if(!dryRun&&options.batchSize===undefined&&changes.some((change)=>change.changed>0)){await recordAudit(db,"retention",null,options.actor??"scheduler",{changes:changes.map(({model,action,matched,changed})=>({model,action,matched,changed})),cutoffs})}return{dryRun,cutoffs,changes:changes.sort((a,b)=>a.model.localeCompare(b.model)),skipped,...options.batchSize===undefined?{}:{next}}}
@@ -7,6 +7,7 @@ export type * from './types';
7
7
  * the vocabulary a model declares.
8
8
  */
9
9
  export {
10
+ anonymizedRows,
10
11
  eraseSubject,
11
12
  exportSubjectData,
12
13
  GDPR_AUDIT_TABLE,
@@ -1 +1 @@
1
- export{eraseSubject,exportSubjectData,GDPR_AUDIT_TABLE,GdprSubjectNotFoundError,gdprTableExists,pruneRetainedData,resolveGdprSubject}from"./engine";export{loadGdprModels}from"./models";export{assertGdprPlan,GDPR_SUBJECT_MODEL,GdprDeclarationError,gdprTableName,resolveGdprPlan}from"./plan";export{buildProcessingRegister,renderProcessingRegister}from"./register";
1
+ export{anonymizedRows,eraseSubject,exportSubjectData,GDPR_AUDIT_TABLE,GdprSubjectNotFoundError,gdprTableExists,pruneRetainedData,resolveGdprSubject}from"./engine";export{loadGdprModels}from"./models";export{assertGdprPlan,GDPR_SUBJECT_MODEL,GdprDeclarationError,gdprTableName,resolveGdprPlan}from"./plan";export{buildProcessingRegister,renderProcessingRegister}from"./register";
package/dist/gdpr/plan.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import{plural,snakeCase}from"@stacksjs/strings";const ERASURE_ACTIONS=new Set(["anonymize","delete","keep"]);const RETENTION_ACTIONS=new Set(["anonymize","delete"]);const LAWFUL_BASES=new Set(["consent","contract","legal_obligation","vital_interests","public_task","legitimate_interests"]);export const GDPR_SUBJECT_MODEL="User";export class GdprDeclarationError extends Error{problems;constructor(problems){super(`GDPR declarations cannot be honoured:
2
2
  ${problems.map((p)=>` - ${p.model}: ${p.message}`).join(`
3
- `)}`);this.name="GdprDeclarationError";this.problems=problems}}function modelList(models){const entries=Array.isArray(models)?models.map((definition)=>[definition.name??"",definition]):Object.entries(models);return entries.map(([key,definition])=>({name:String(definition?.name??key),definition})).filter((entry)=>entry.name&&entry.definition&&typeof entry.definition==="object").sort((a,b)=>a.name.localeCompare(b.name))}export function gdprTableName(name,definition){return definition.table??snakeCase(plural(name))}function belongsToEntries(definition){const raw=definition.belongsTo;const list=Array.isArray(raw)?raw:raw&&typeof raw==="object"?Object.values(raw):[];const entries=[];for(const item of list){if(typeof item==="string"){entries.push({model:item,foreignKey:`${snakeCase(item)}_id`});continue}if(item&&typeof item==="object"&&typeof item.model==="string"){const relation=item;entries.push({model:relation.model,foreignKey:relation.foreignKey??`${snakeCase(relation.model)}_id`})}}return entries}function personalOptions(value){if(value===true)return{};if(value&&typeof value==="object")return value;return null}function anonymizedValue(attribute,options){if(options.anonymize!==undefined)return{perRow:false,value:options.anonymize};const notNull=attribute.required===true&&attribute.nullable!==true;if(!notNull)return{perRow:false,value:null};const type=attribute.validation?.rule?.name??attribute.type??"string";if(type==="string"||type==="text")return attribute.unique?{perRow:true,value:null}:{perRow:false,value:"[erased]"};if(attribute.unique)return{problem:`is a NOT NULL unique ${type} column; declare personal: { anonymize: <value> } or make it nullable`};if(type==="number"||type==="integer"||type==="float"||type==="decimal")return{perRow:false,value:0};if(type==="boolean")return{perRow:false,value:false};if(type==="json")return{perRow:false,value:"{}"};return{problem:`is a NOT NULL ${type} column with no safe placeholder; declare personal: { anonymize: <value> }`}}export function resolveGdprPlan(models){const plans=new Map;const viaOf=new Map;const unclassified=[];const problems=[];const problem=(model,message)=>{problems.push({model,message})};for(const{name,definition}of modelList(models)){const attributes=definition.attributes??{};const gdpr=definition.traits?.gdpr;const belongsTo=belongsToEntries(definition);const userRelation=belongsTo.find((entry)=>entry.model===GDPR_SUBJECT_MODEL);const personalAttributes=Object.entries(attributes).map(([attribute,shape])=>({attribute,shape,options:personalOptions(shape?.personal)})).filter((entry)=>entry.options!==null);if(!gdpr&&personalAttributes.length===0){if(userRelation&&name!==GDPR_SUBJECT_MODEL)unclassified.push(name);continue}if(gdpr!==undefined&&(gdpr===null||typeof gdpr!=="object")){problem(name,"`traits.gdpr` must be an object");continue}const table=gdprTableName(name,definition);const primaryKey=definition.primaryKey??"id";let subject=null;let via;const declared=gdpr?.subject;if(declared===undefined){if(name===GDPR_SUBJECT_MODEL)subject={kind:"column",columns:[primaryKey],where:{}};else if(userRelation)subject={kind:"column",columns:[userRelation.foreignKey],where:{}}}else if(typeof declared==="string"){subject={kind:"column",columns:[declared],where:{}}}else if(Array.isArray(declared)){subject={kind:"column",columns:[...declared].map(String),where:{}}}else if(declared&&typeof declared==="object"&&"column"in declared){const columns=Array.isArray(declared.column)?[...declared.column].map(String):[String(declared.column)];subject={kind:"column",columns,where:{...declared.where??{}}}}else if(declared&&typeof declared==="object"&&"via"in declared){const relation=belongsTo.find((entry)=>entry.model===declared.via);if(!relation){problem(name,`subject { via: '${declared.via}' } names a model this one does not declare in belongsTo`)}else{via=relation.model;subject={kind:"via",model:relation.model,foreignKey:relation.foreignKey}}}else if(declared&&typeof declared==="object"&&"email"in declared){subject={kind:"email",column:String(declared.email)}}else{problem(name,"subject must be a column name, a list of columns, { column, where }, { via } or { email }")}if(subject?.kind==="column"&&subject.columns.length===0)problem(name,"subject names no column");const erasure=gdpr?.erasure??"anonymize";if(!ERASURE_ACTIONS.has(erasure))problem(name,`erasure must be one of ${[...ERASURE_ACTIONS].join(", ")}, got '${String(erasure)}'`);let retention=null;if(gdpr?.retention!==undefined){const policy=gdpr.retention;const action=policy?.action??"delete";if(!policy||typeof policy!=="object"||!Number.isInteger(policy.days)||policy.days<=0)problem(name,"retention.days must be a positive whole number of days");else if(!RETENTION_ACTIONS.has(action))problem(name,`retention.action must be one of ${[...RETENTION_ACTIONS].join(", ")}, got '${String(action)}'`);else retention={days:policy.days,column:policy.column??"created_at",action}}if(gdpr?.basis!==undefined&&!LAWFUL_BASES.has(gdpr.basis))problem(name,`basis must be one of ${[...LAWFUL_BASES].join(", ")}, got '${String(gdpr.basis)}'`);const anonymizes=erasure==="anonymize"&&subject!==null||retention?.action==="anonymize";const personal=[];for(const{attribute,shape,options}of personalAttributes){const resolved=anonymizedValue(shape,options);if("problem"in resolved){if(anonymizes)problem(name,`personal attribute '${attribute}' ${resolved.problem}`);personal.push({attribute,column:snakeCase(attribute),export:options.export!==false,perRow:false,anonymizeTo:null});continue}personal.push({attribute,column:snakeCase(attribute),export:options.export!==false,perRow:resolved.perRow,anonymizeTo:resolved.value})}if(subject!==null&&erasure==="anonymize"&&personal.length===0)problem(name,`declares a subject but no personal attributes, so 'anonymize' would change nothing; mark the personal attributes, or declare erasure 'keep' or 'delete'`);if(retention?.action==="anonymize"&&personal.length===0)problem(name,`retention anonymizes, but no attribute is marked personal`);plans.set(name,{model:name,table,primaryKey,subject,personal,erasure,retention,purpose:gdpr?.purpose??null,basis:gdpr?.basis??null,depth:0,exportColumns:[...new Set([primaryKey,"uuid","created_at","updated_at"])]});if(via)viaOf.set(name,via)}const depthOf=(name,seen)=>{const via=viaOf.get(name);if(!via)return 0;if(seen.has(name))return null;const parent=plans.get(via);if(!parent?.subject)return null;seen.add(name);const parentDepth=depthOf(via,seen);return parentDepth===null?null:parentDepth+1};for(const plan of plans.values()){const via=viaOf.get(plan.model);if(!via)continue;const parent=plans.get(via);if(!parent?.subject){problem(plan.model,`subject { via: '${via}' } points at a model that declares no subject of its own`);continue}const depth=depthOf(plan.model,new Set);if(depth===null)problem(plan.model,`subject { via: '${via}' } is part of a cycle`);else plan.depth=depth}return{models:[...plans.values()],unclassified:unclassified.sort(),problems}}export function assertGdprPlan(plan){if(plan.problems.length)throw new GdprDeclarationError(plan.problems);return plan}
3
+ `)}`);this.name="GdprDeclarationError";this.problems=problems}}function modelList(models){const entries=Array.isArray(models)?models.map((definition)=>[definition.name??"",definition]):Object.entries(models);return entries.map(([key,definition])=>({name:String(definition?.name??key),definition})).filter((entry)=>entry.name&&entry.definition&&typeof entry.definition==="object").sort((a,b)=>a.name.localeCompare(b.name))}export function gdprTableName(name,definition){return definition.table??snakeCase(plural(name))}function belongsToEntries(definition){const raw=definition.belongsTo;const list=Array.isArray(raw)?raw:raw&&typeof raw==="object"?Object.values(raw):[];const entries=[];for(const item of list){if(typeof item==="string"){entries.push({model:item,foreignKey:`${snakeCase(item)}_id`});continue}if(item&&typeof item==="object"&&typeof item.model==="string"){const relation=item;entries.push({model:relation.model,foreignKey:relation.foreignKey??`${snakeCase(relation.model)}_id`})}}return entries}function personalOptions(value){if(value===true)return{};if(value&&typeof value==="object")return value;return null}function anonymizedValue(attribute,options){if(options.anonymize!==undefined)return{perRow:false,value:options.anonymize};const required=attribute.required===true||attribute.validation?.rule?.isRequired===true;const notNull=required&&attribute.nullable!==true;if(!notNull)return{perRow:false,value:null};const type=attribute.validation?.rule?.name??attribute.type??"string";if(type==="string"||type==="text")return attribute.unique?{perRow:true,value:null}:{perRow:false,value:"[erased]"};if(attribute.unique)return{problem:`is a NOT NULL unique ${type} column; declare personal: { anonymize: <value> } or make it nullable`};if(type==="number"||type==="integer"||type==="float"||type==="decimal")return{perRow:false,value:0};if(type==="boolean")return{perRow:false,value:false};if(type==="json")return{perRow:false,value:"{}"};return{problem:`is a NOT NULL ${type} column with no safe placeholder; declare personal: { anonymize: <value> }`}}export function resolveGdprPlan(models){const plans=new Map;const viaOf=new Map;const unclassified=[];const problems=[];const problem=(model,message)=>{problems.push({model,message})};for(const{name,definition}of modelList(models)){const attributes=definition.attributes??{};const gdpr=definition.traits?.gdpr;const belongsTo=belongsToEntries(definition);const userRelation=belongsTo.find((entry)=>entry.model===GDPR_SUBJECT_MODEL);const personalAttributes=Object.entries(attributes).map(([attribute,shape])=>({attribute,shape,options:personalOptions(shape?.personal)})).filter((entry)=>entry.options!==null);if(!gdpr&&personalAttributes.length===0){if(userRelation&&name!==GDPR_SUBJECT_MODEL)unclassified.push(name);continue}if(gdpr!==undefined&&(gdpr===null||typeof gdpr!=="object")){problem(name,"`traits.gdpr` must be an object");continue}const table=gdprTableName(name,definition);const primaryKey=definition.primaryKey??"id";let subject=null;let via;const declared=gdpr?.subject;if(declared===undefined){if(name===GDPR_SUBJECT_MODEL)subject={kind:"column",columns:[primaryKey],where:{}};else if(userRelation)subject={kind:"column",columns:[userRelation.foreignKey],where:{}}}else if(typeof declared==="string"){subject={kind:"column",columns:[declared],where:{}}}else if(Array.isArray(declared)){subject={kind:"column",columns:[...declared].map(String),where:{}}}else if(declared&&typeof declared==="object"&&"column"in declared){const columns=Array.isArray(declared.column)?[...declared.column].map(String):[String(declared.column)];subject={kind:"column",columns,where:{...declared.where??{}}}}else if(declared&&typeof declared==="object"&&"via"in declared){const relation=belongsTo.find((entry)=>entry.model===declared.via);if(!relation){problem(name,`subject { via: '${declared.via}' } names a model this one does not declare in belongsTo`)}else{via=relation.model;subject={kind:"via",model:relation.model,foreignKey:relation.foreignKey}}}else if(declared&&typeof declared==="object"&&"email"in declared){subject={kind:"email",column:String(declared.email)}}else{problem(name,"subject must be a column name, a list of columns, { column, where }, { via } or { email }")}if(subject?.kind==="column"&&subject.columns.length===0)problem(name,"subject names no column");const erasure=gdpr?.erasure??"anonymize";if(!ERASURE_ACTIONS.has(erasure))problem(name,`erasure must be one of ${[...ERASURE_ACTIONS].join(", ")}, got '${String(erasure)}'`);let retention=null;if(gdpr?.retention!==undefined){const policy=gdpr.retention;const action=policy?.action??"delete";if(!policy||typeof policy!=="object"||!Number.isInteger(policy.days)||policy.days<=0)problem(name,"retention.days must be a positive whole number of days");else if(!RETENTION_ACTIONS.has(action))problem(name,`retention.action must be one of ${[...RETENTION_ACTIONS].join(", ")}, got '${String(action)}'`);else retention={days:policy.days,column:policy.column??"created_at",action}}if(gdpr?.basis!==undefined&&!LAWFUL_BASES.has(gdpr.basis))problem(name,`basis must be one of ${[...LAWFUL_BASES].join(", ")}, got '${String(gdpr.basis)}'`);const anonymizes=erasure==="anonymize"&&subject!==null||retention?.action==="anonymize";const personal=[];for(const{attribute,shape,options}of personalAttributes){const resolved=anonymizedValue(shape,options);if("problem"in resolved){if(anonymizes)problem(name,`personal attribute '${attribute}' ${resolved.problem}`);personal.push({attribute,column:snakeCase(attribute),export:options.export!==false,perRow:false,anonymizeTo:null});continue}personal.push({attribute,column:snakeCase(attribute),export:options.export!==false,perRow:resolved.perRow,anonymizeTo:resolved.value})}if(subject!==null&&erasure==="anonymize"&&personal.length===0)problem(name,`declares a subject but no personal attributes, so 'anonymize' would change nothing; mark the personal attributes, or declare erasure 'keep' or 'delete'`);if(retention?.action==="anonymize"&&personal.length===0)problem(name,`retention anonymizes, but no attribute is marked personal`);plans.set(name,{model:name,table,primaryKey,subject,personal,erasure,retention,purpose:gdpr?.purpose??null,basis:gdpr?.basis??null,depth:0,exportColumns:[...new Set([primaryKey,"uuid","created_at","updated_at"])]});if(via)viaOf.set(name,via)}const depthOf=(name,seen)=>{const via=viaOf.get(name);if(!via)return 0;if(seen.has(name))return null;const parent=plans.get(via);if(!parent?.subject)return null;seen.add(name);const parentDepth=depthOf(via,seen);return parentDepth===null?null:parentDepth+1};for(const plan of plans.values()){const via=viaOf.get(plan.model);if(!via)continue;const parent=plans.get(via);if(!parent?.subject){problem(plan.model,`subject { via: '${via}' } points at a model that declares no subject of its own`);continue}const depth=depthOf(plan.model,new Set);if(depth===null)problem(plan.model,`subject { via: '${via}' } is part of a cycle`);else plan.depth=depth}return{models:[...plans.values()],unclassified:unclassified.sort(),problems}}export function assertGdprPlan(plan){if(plan.problems.length)throw new GdprDeclarationError(plan.problems);return plan}
@@ -95,4 +95,8 @@ export default defineModel({
95
95
  factory: faker => faker.internet.ip(),
96
96
  },
97
97
  },
98
+
99
+ dashboard: {
100
+ columns: ['description', 'type', 'subjectType', 'causer', 'createdAt'],
101
+ },
98
102
  } as const)
@@ -73,4 +73,8 @@ export default defineModel({
73
73
  },
74
74
  },
75
75
  },
76
+
77
+ dashboard: {
78
+ columns: ['name', 'category', 'path', 'value', 'createdAt'],
79
+ },
76
80
  } as const)
@@ -20,4 +20,8 @@ export default defineModel({
20
20
  graph: { required: true, fillable: true, validation: { rule: schema.json() }, factory: () => JSON.stringify({ nodes: [], edges: [] }) },
21
21
  publishedAt: { required: false, fillable: true, validation: { rule: schema.timestamp() }, factory: () => null },
22
22
  },
23
+
24
+ dashboard: {
25
+ columns: ['name', 'status', 'version', 'team', 'publishedAt'],
26
+ },
23
27
  } as const)
@@ -23,4 +23,8 @@ export default defineModel({
23
23
  finishedAt: { required: false, fillable: true, validation: { rule: schema.timestamp() }, factory: () => null },
24
24
  error: { type: 'text', required: false, fillable: true, validation: { rule: schema.string() }, factory: () => null },
25
25
  },
26
+
27
+ dashboard: {
28
+ columns: ['automation', 'status', 'subjectType', 'startedAt', 'finishedAt'],
29
+ },
26
30
  } as const)
@@ -113,5 +113,8 @@ export default defineModel({
113
113
  // not the auto-derived `/models/board` viewer — the sidebar entry is
114
114
  // hand-added in `dashboard-utils.ts` / `sidebar.ts` and points at
115
115
  // the real page. Hiding the auto-row keeps it from double-listing.
116
- dashboard: { enabled: false },
116
+ dashboard: {
117
+ columns: ['name', 'team', 'archived', 'createdAt'],
118
+ enabled: false,
119
+ },
117
120
  } as const)
@@ -86,5 +86,8 @@ export default defineModel({
86
86
  },
87
87
  },
88
88
 
89
- dashboard: { enabled: false },
89
+ dashboard: {
90
+ columns: ['name', 'board', 'position', 'cardLimit'],
91
+ enabled: false,
92
+ },
90
93
  } as const)
@@ -323,4 +323,8 @@ export default defineModel({
323
323
  },
324
324
  },
325
325
  },
326
+
327
+ dashboard: {
328
+ columns: ['name', 'type', 'status', 'emailList', 'scheduledAt', 'sentCount'],
329
+ },
326
330
  } as const)
@@ -190,4 +190,8 @@ export default defineModel({
190
190
  factory: () => JSON.stringify({}),
191
191
  },
192
192
  },
193
+
194
+ dashboard: {
195
+ columns: ['recipient', 'campaign', 'channel', 'status', 'sentAt', 'openedAt'],
196
+ },
193
197
  } as const)
@@ -22,4 +22,8 @@ export default defineModel({
22
22
  conversionCount: { required: true, fillable: true, default: 0, validation: { rule: schema.number().min(0) }, factory: () => 0 },
23
23
  isWinner: { required: true, fillable: true, default: false, validation: { rule: schema.boolean() }, factory: () => false },
24
24
  },
25
+
26
+ dashboard: {
27
+ columns: ['name', 'campaign', 'allocation', 'sentCount', 'openCount', 'clickCount', 'isWinner'],
28
+ },
25
29
  } as const)
@@ -114,5 +114,8 @@ export default defineModel({
114
114
  },
115
115
  },
116
116
 
117
- dashboard: { enabled: false },
117
+ dashboard: {
118
+ columns: ['title', 'board', 'boardColumn', 'user', 'dueDate', 'archived'],
119
+ enabled: false,
120
+ },
118
121
  } as const)
@@ -107,4 +107,8 @@ export default defineModel({
107
107
  factory: faker => faker.number.int({ min: 1000, max: 500_000 }),
108
108
  },
109
109
  },
110
+
111
+ dashboard: {
112
+ columns: ['path', 'card', 'mimeType', 'sizeBytes', 'createdAt'],
113
+ },
110
114
  } as const)
@@ -20,4 +20,8 @@ export default defineModel({
20
20
  suppressedAt: { required: true, fillable: true, validation: { rule: schema.timestamp() }, factory: () => new Date().toISOString() },
21
21
  liftedAt: { required: false, fillable: false, validation: { rule: schema.timestamp() }, factory: () => null },
22
22
  },
23
+
24
+ dashboard: {
25
+ columns: ['recipient', 'channel', 'reason', 'suppressedAt', 'liftedAt'],
26
+ },
23
27
  } as const)
@@ -28,4 +28,8 @@ export default defineModel({
28
28
  ipAddress: { personal: true, required: false, fillable: true, validation: { rule: schema.string().max(45) }, factory: faker => faker.internet.ip() },
29
29
  occurredAt: { required: true, fillable: true, validation: { rule: schema.timestamp() }, factory: () => new Date().toISOString() },
30
30
  },
31
+
32
+ dashboard: {
33
+ columns: ['recipient', 'channel', 'action', 'purpose', 'occurredAt'],
34
+ },
31
35
  } as const)
@@ -112,6 +112,7 @@ export default defineModel({
112
112
  },
113
113
 
114
114
  dashboard: {
115
+ columns: ['commitMessage', 'branch', 'environment', 'status', 'duration', 'createdAt'],
115
116
  highlight: true,
116
117
  },
117
118
  } as const)
@@ -137,4 +137,8 @@ export default defineModel({
137
137
  factory: () => 1,
138
138
  },
139
139
  },
140
+
141
+ dashboard: {
142
+ columns: ['name', 'status', 'subscriberCount', 'activeCount', 'isPublic', 'createdAt'],
143
+ },
140
144
  } as const)
@@ -89,4 +89,8 @@ export default defineModel({
89
89
  factory: () => null,
90
90
  },
91
91
  },
92
+
93
+ dashboard: {
94
+ columns: ['subscriber', 'emailList', 'status', 'source', 'subscribedAt'],
95
+ },
92
96
  } as const)
@@ -100,4 +100,8 @@ export default defineModel({
100
100
  factory: faker => faker.lorem.paragraph(),
101
101
  },
102
102
  },
103
+
104
+ dashboard: {
105
+ columns: ['type', 'message', 'status', 'createdAt'],
106
+ },
103
107
  } as const)
@@ -86,4 +86,8 @@ export default defineModel({
86
86
  factory: () => '2024-12-23 13:32:19',
87
87
  },
88
88
  },
89
+
90
+ dashboard: {
91
+ columns: ['queue', 'connection', 'exception', 'attempts', 'failedAt'],
92
+ },
89
93
  } as const)
@@ -126,4 +126,8 @@ export default defineModel({
126
126
  factory: () => null,
127
127
  },
128
128
  },
129
+
130
+ dashboard: {
131
+ columns: ['label', 'board', 'expiresAt', 'lastUsedAt', 'revokedAt'],
132
+ },
129
133
  } as const)
@@ -74,4 +74,8 @@ export default defineModel({
74
74
  factory: () => new Date().toISOString(),
75
75
  },
76
76
  },
77
+
78
+ dashboard: {
79
+ columns: ['type', 'subjectId', 'actor', 'status', 'occurredAt'],
80
+ },
77
81
  } as const)
@@ -71,4 +71,8 @@ export default defineModel({
71
71
  factory: () => null,
72
72
  },
73
73
  },
74
+
75
+ dashboard: {
76
+ columns: ['queue', 'attempts', 'availableAt', 'reservedAt', 'createdAt'],
77
+ },
74
78
  } as const)
@@ -133,4 +133,8 @@ export default defineModel({
133
133
  factory: faker => faker.system.filePath().substring(0, 255),
134
134
  },
135
135
  },
136
+
137
+ dashboard: {
138
+ columns: ['timestamp', 'type', 'source', 'message'],
139
+ },
136
140
  } as const)
@@ -89,4 +89,8 @@ export default defineModel({
89
89
  factory: () => null,
90
90
  },
91
91
  },
92
+
93
+ dashboard: {
94
+ columns: ['email', 'user', 'expiresAt', 'consumedAt', 'createdAt'],
95
+ },
92
96
  } as const)
@@ -215,4 +215,8 @@ export default defineModel({
215
215
  },
216
216
  },
217
217
  },
218
+
219
+ dashboard: {
220
+ columns: ['mailbox', 'accountName', 'theme', 'language', 'displayDensity'],
221
+ },
218
222
  } as const)
@@ -69,4 +69,8 @@ export default defineModel({
69
69
  },
70
70
 
71
71
  },
72
+
73
+ dashboard: {
74
+ columns: ['type', 'user', 'readAt', 'createdAt'],
75
+ },
72
76
  } as const)
@@ -107,4 +107,8 @@ export default defineModel({
107
107
  },
108
108
  },
109
109
  },
110
+
111
+ dashboard: {
112
+ columns: ['recipient', 'channel', 'subject', 'status', 'sentAt'],
113
+ },
110
114
  } as const)
@@ -220,4 +220,8 @@ export default defineModel({
220
220
  },
221
221
  },
222
222
  },
223
+
224
+ dashboard: {
225
+ columns: ['name', 'userId', 'scopes', 'revoked', 'expiresAt', 'createdAt'],
226
+ },
223
227
  } as const)
@@ -189,4 +189,8 @@ export default defineModel({
189
189
  },
190
190
  },
191
191
  },
192
+
193
+ dashboard: {
194
+ columns: ['query', 'duration', 'status', 'connection', 'model', 'executedAt'],
195
+ },
192
196
  } as const)
@@ -16,4 +16,8 @@ export default defineModel({
16
16
  status: { required: true, default: 'registered', validation: { rule: schema.enum(['registered', 'qualified']) } },
17
17
  qualifiedAt: { nullable: true, validation: { rule: schema.date() } },
18
18
  },
19
+
20
+ dashboard: {
21
+ columns: ['code', 'status', 'referrerId', 'referredUserId', 'qualifiedAt'],
22
+ },
19
23
  } as const)
@@ -88,6 +88,7 @@ export default defineModel({
88
88
  },
89
89
 
90
90
  dashboard: {
91
+ columns: ['version', 'type', 'status', 'downloads', 'author', 'createdAt'],
91
92
  highlight: true,
92
93
  },
93
94
  } as const)
@@ -144,4 +144,8 @@ export default defineModel({
144
144
  factory: faker => faker.helpers.maybe(() => faker.lorem.sentence(), { probability: 0.2 }),
145
145
  },
146
146
  },
147
+
148
+ dashboard: {
149
+ columns: ['method', 'path', 'statusCode', 'durationMs', 'ipAddress', 'createdAt'],
150
+ },
147
151
  } as const)
@@ -21,4 +21,8 @@ export default defineModel({
21
21
  verifiedAt: { required: false, fillable: true, validation: { rule: schema.timestamp() }, factory: () => null },
22
22
  lastCheckedAt: { required: false, fillable: true, validation: { rule: schema.timestamp() }, factory: () => null },
23
23
  },
24
+
25
+ dashboard: {
26
+ columns: ['domain', 'status', 'team', 'verifiedAt', 'lastCheckedAt'],
27
+ },
24
28
  } as const)
@@ -107,6 +107,7 @@ export default defineModel({
107
107
  },
108
108
 
109
109
  dashboard: {
110
+ columns: ['name', 'subdomain', 'status', 'timezone', 'team'],
110
111
  highlight: true,
111
112
  },
112
113
  })
@@ -75,4 +75,8 @@ export default defineModel({
75
75
  factory: () => 'pending',
76
76
  },
77
77
  },
78
+
79
+ dashboard: {
80
+ columns: ['domain', 'site', 'isPrimary', 'sslStatus', 'verifiedAt'],
81
+ },
78
82
  })
@@ -143,4 +143,8 @@ export default defineModel({
143
143
  factory: faker => faker.string.alphanumeric(20),
144
144
  },
145
145
  },
146
+
147
+ dashboard: {
148
+ columns: ['content', 'platform', 'status', 'scheduledAt', 'publishedAt', 'likes'],
149
+ },
146
150
  } as const)
@@ -136,5 +136,8 @@ export default defineModel({
136
136
  },
137
137
  },
138
138
 
139
- dashboard: { enabled: false },
139
+ dashboard: {
140
+ columns: ['path', 'disk', 'kind', 'state', 'attempts', 'finishedAt'],
141
+ enabled: false,
142
+ },
140
143
  } as const)
@@ -88,4 +88,8 @@ export default defineModel({
88
88
  factory: () => null,
89
89
  },
90
90
  },
91
+
92
+ dashboard: {
93
+ columns: ['email', 'status', 'source', 'user', 'createdAt'],
94
+ },
91
95
  } as const)
@@ -153,4 +153,8 @@ export default defineModel({
153
153
  },
154
154
  },
155
155
  },
156
+
157
+ dashboard: {
158
+ columns: ['plan', 'type', 'providerStatus', 'quantity', 'user', 'endsAt'],
159
+ },
156
160
  } as const)
@@ -75,6 +75,7 @@ export default defineModel({
75
75
  },
76
76
 
77
77
  dashboard: {
78
+ columns: ['name', 'memberCount', 'status', 'createdAt'],
78
79
  highlight: true,
79
80
  },
80
81
  } as const)
@@ -156,6 +156,7 @@ export default defineModel({
156
156
  },
157
157
 
158
158
  dashboard: {
159
+ columns: ['email', 'team', 'role', 'status', 'deliveryStatus', 'expiresAt'],
159
160
  enabled: false,
160
161
  },
161
162
  } as const)
@@ -84,6 +84,7 @@ export default defineModel({
84
84
  },
85
85
 
86
86
  dashboard: {
87
+ columns: ['user', 'team', 'role', 'status', 'createdAt'],
87
88
  enabled: false,
88
89
  },
89
90
  } as const)
@@ -21,4 +21,8 @@ export default defineModel({
21
21
  metadata: { required: false, fillable: true, validation: { rule: schema.json() }, factory: () => JSON.stringify({}) },
22
22
  occurredAt: { required: true, fillable: true, validation: { rule: schema.timestamp() }, factory: () => new Date().toISOString() },
23
23
  },
24
+
25
+ dashboard: {
26
+ columns: ['meter', 'quantity', 'team', 'occurredAt'],
27
+ },
24
28
  } as const)
@@ -77,10 +77,13 @@ export default defineModel({
77
77
  order: 2,
78
78
  fillable: true,
79
79
  validation: {
80
- rule: schema.string().required().min(5).max(100),
80
+ // The same floor registration applies. This rule said five while its
81
+ // message said three, so "Ava" could sign up and then could not have
82
+ // a letter of her name corrected. The ceiling is the column's.
83
+ rule: schema.string().required().min(2).max(100),
81
84
  message: {
82
- min: 'Name must have a minimum of 3 characters',
83
- max: 'Name must have a maximum of 255 characters',
85
+ min: 'Name must have a minimum of 2 characters',
86
+ max: 'Name must have a maximum of 100 characters',
84
87
  },
85
88
  },
86
89
 
@@ -157,5 +160,14 @@ export default defineModel({
157
160
  },
158
161
  dashboard: {
159
162
  highlight: true,
163
+ // The list is for telling accounts apart. The two-factor step, the
164
+ // billing id and the rest are on the account's own page.
165
+ columns: ['name', 'email', 'emailVerifiedAt', 'createdAt'],
166
+ // Operators add, edit and remove accounts from the dashboard. Not through
167
+ // `useApi` above: a generated PATCH would let any signed-in caller change
168
+ // their own email and password outside the flows that verify them.
169
+ // `store` is by invitation: no form can supply a password, so the account
170
+ // is created and its holder is mailed a link to choose one.
171
+ writes: ['store', 'update', 'destroy'],
160
172
  },
161
173
  } as const)
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/orm",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.538",
5
+ "version": "0.75.541",
6
6
  "description": "The Stacks ORM integration",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -63,31 +63,31 @@
63
63
  "prepublishOnly": "bun run build"
64
64
  },
65
65
  "dependencies": {
66
- "@stacksjs/cache": "0.75.538",
67
- "@stacksjs/cli": "0.75.538",
68
- "@stacksjs/config": "0.75.538",
69
- "@stacksjs/database": "0.75.538",
70
- "@stacksjs/env": "0.75.538",
71
- "@stacksjs/error-handling": "0.75.538",
72
- "@stacksjs/events": "0.75.538",
73
- "@stacksjs/logging": "0.75.538",
74
- "@stacksjs/model-meta": "0.75.538",
75
- "@stacksjs/pagination": "0.75.538",
76
- "@stacksjs/path": "0.75.538",
77
- "@stacksjs/query-builder": "0.75.538",
78
- "@stacksjs/realtime": "0.75.538",
79
- "@stacksjs/router": "0.75.538",
80
- "@stacksjs/storage": "0.75.538",
81
- "@stacksjs/strings": "0.75.538",
66
+ "@stacksjs/cache": "0.75.541",
67
+ "@stacksjs/cli": "0.75.541",
68
+ "@stacksjs/config": "0.75.541",
69
+ "@stacksjs/database": "0.75.541",
70
+ "@stacksjs/env": "0.75.541",
71
+ "@stacksjs/error-handling": "0.75.541",
72
+ "@stacksjs/events": "0.75.541",
73
+ "@stacksjs/logging": "0.75.541",
74
+ "@stacksjs/model-meta": "0.75.541",
75
+ "@stacksjs/pagination": "0.75.541",
76
+ "@stacksjs/path": "0.75.541",
77
+ "@stacksjs/query-builder": "0.75.541",
78
+ "@stacksjs/realtime": "0.75.541",
79
+ "@stacksjs/router": "0.75.541",
80
+ "@stacksjs/storage": "0.75.541",
81
+ "@stacksjs/strings": "0.75.541",
82
82
  "@stacksjs/ts-validation": "^0.5.7",
83
- "@stacksjs/validation": "0.75.538",
83
+ "@stacksjs/validation": "0.75.541",
84
84
  "bun-query-builder": "^0.3.44"
85
85
  },
86
86
  "peerDependencies": {
87
- "@stacksjs/auth": "0.75.538",
88
- "@stacksjs/payments": "0.75.538",
89
- "@stacksjs/queue": "0.75.538",
90
- "@stacksjs/search-engine": "0.75.538",
87
+ "@stacksjs/auth": "0.75.541",
88
+ "@stacksjs/payments": "0.75.541",
89
+ "@stacksjs/queue": "0.75.541",
90
+ "@stacksjs/search-engine": "0.75.541",
91
91
  "stripe": "23.0.0"
92
92
  },
93
93
  "peerDependenciesMeta": {
@@ -108,7 +108,7 @@
108
108
  }
109
109
  },
110
110
  "devDependencies": {
111
- "@stacksjs/types": "0.75.538",
111
+ "@stacksjs/types": "0.75.541",
112
112
  "better-dx": "^0.2.24",
113
113
  "stripe": "23.0.0"
114
114
  }