@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.
- package/dist/gdpr/engine.d.ts +14 -0
- package/dist/gdpr/engine.js +1 -1
- package/dist/gdpr/index.d.ts +1 -0
- package/dist/gdpr/index.js +1 -1
- package/dist/gdpr/plan.js +1 -1
- package/dist/models/Activity.ts +4 -0
- package/dist/models/AnalyticsEvent.ts +4 -0
- package/dist/models/Automation.ts +4 -0
- package/dist/models/AutomationRun.ts +4 -0
- package/dist/models/Board.ts +4 -1
- package/dist/models/BoardColumn.ts +4 -1
- package/dist/models/Campaign.ts +4 -0
- package/dist/models/CampaignSend.ts +4 -0
- package/dist/models/CampaignVariant.ts +4 -0
- package/dist/models/Card.ts +4 -1
- package/dist/models/CardAttachment.ts +4 -0
- package/dist/models/CommunicationSuppression.ts +4 -0
- package/dist/models/ConsentEvent.ts +4 -0
- package/dist/models/Deployment.ts +1 -0
- package/dist/models/EmailList.ts +4 -0
- package/dist/models/EmailListSubscriber.ts +4 -0
- package/dist/models/Error.ts +4 -0
- package/dist/models/FailedJob.ts +4 -0
- package/dist/models/FeedbackToken.ts +4 -0
- package/dist/models/GdprRequest.ts +4 -0
- package/dist/models/Job.ts +4 -0
- package/dist/models/Log.ts +4 -0
- package/dist/models/MagicLinkToken.ts +4 -0
- package/dist/models/MailPreference.ts +4 -0
- package/dist/models/Notification.ts +4 -0
- package/dist/models/NotificationDelivery.ts +4 -0
- package/dist/models/PersonalAccessToken.ts +4 -0
- package/dist/models/QueryLog.ts +4 -0
- package/dist/models/Referral.ts +4 -0
- package/dist/models/Release.ts +1 -0
- package/dist/models/Request.ts +4 -0
- package/dist/models/SenderDomain.ts +4 -0
- package/dist/models/Site.ts +1 -0
- package/dist/models/SiteDomain.ts +4 -0
- package/dist/models/SocialPost.ts +4 -0
- package/dist/models/StorageItemTask.ts +4 -1
- package/dist/models/Subscriber.ts +4 -0
- package/dist/models/Subscription.ts +4 -0
- package/dist/models/Team.ts +1 -0
- package/dist/models/TeamInvitation.ts +1 -0
- package/dist/models/TeamMember.ts +1 -0
- package/dist/models/UsageEvent.ts +4 -0
- package/dist/models/User.ts +15 -3
- package/package.json +23 -23
package/dist/gdpr/engine.d.ts
CHANGED
|
@@ -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
|
*
|
package/dist/gdpr/engine.js
CHANGED
|
@@ -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}}}
|
package/dist/gdpr/index.d.ts
CHANGED
package/dist/gdpr/index.js
CHANGED
|
@@ -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
|
|
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}
|
package/dist/models/Activity.ts
CHANGED
|
@@ -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)
|
package/dist/models/Board.ts
CHANGED
|
@@ -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: {
|
|
116
|
+
dashboard: {
|
|
117
|
+
columns: ['name', 'team', 'archived', 'createdAt'],
|
|
118
|
+
enabled: false,
|
|
119
|
+
},
|
|
117
120
|
} as const)
|
package/dist/models/Campaign.ts
CHANGED
|
@@ -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)
|
package/dist/models/Card.ts
CHANGED
|
@@ -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)
|
package/dist/models/EmailList.ts
CHANGED
package/dist/models/Error.ts
CHANGED
package/dist/models/FailedJob.ts
CHANGED
package/dist/models/Job.ts
CHANGED
package/dist/models/Log.ts
CHANGED
package/dist/models/QueryLog.ts
CHANGED
package/dist/models/Referral.ts
CHANGED
|
@@ -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)
|
package/dist/models/Release.ts
CHANGED
package/dist/models/Request.ts
CHANGED
|
@@ -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)
|
package/dist/models/Site.ts
CHANGED
package/dist/models/Team.ts
CHANGED
|
@@ -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)
|
package/dist/models/User.ts
CHANGED
|
@@ -77,10 +77,13 @@ export default defineModel({
|
|
|
77
77
|
order: 2,
|
|
78
78
|
fillable: true,
|
|
79
79
|
validation: {
|
|
80
|
-
rule
|
|
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
|
|
83
|
-
max: 'Name must have a maximum of
|
|
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.
|
|
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.
|
|
67
|
-
"@stacksjs/cli": "0.75.
|
|
68
|
-
"@stacksjs/config": "0.75.
|
|
69
|
-
"@stacksjs/database": "0.75.
|
|
70
|
-
"@stacksjs/env": "0.75.
|
|
71
|
-
"@stacksjs/error-handling": "0.75.
|
|
72
|
-
"@stacksjs/events": "0.75.
|
|
73
|
-
"@stacksjs/logging": "0.75.
|
|
74
|
-
"@stacksjs/model-meta": "0.75.
|
|
75
|
-
"@stacksjs/pagination": "0.75.
|
|
76
|
-
"@stacksjs/path": "0.75.
|
|
77
|
-
"@stacksjs/query-builder": "0.75.
|
|
78
|
-
"@stacksjs/realtime": "0.75.
|
|
79
|
-
"@stacksjs/router": "0.75.
|
|
80
|
-
"@stacksjs/storage": "0.75.
|
|
81
|
-
"@stacksjs/strings": "0.75.
|
|
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.
|
|
83
|
+
"@stacksjs/validation": "0.75.541",
|
|
84
84
|
"bun-query-builder": "^0.3.44"
|
|
85
85
|
},
|
|
86
86
|
"peerDependencies": {
|
|
87
|
-
"@stacksjs/auth": "0.75.
|
|
88
|
-
"@stacksjs/payments": "0.75.
|
|
89
|
-
"@stacksjs/queue": "0.75.
|
|
90
|
-
"@stacksjs/search-engine": "0.75.
|
|
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.
|
|
111
|
+
"@stacksjs/types": "0.75.541",
|
|
112
112
|
"better-dx": "^0.2.24",
|
|
113
113
|
"stripe": "23.0.0"
|
|
114
114
|
}
|